30 - 个人博客项目-01-配置环境

(1). 安装第三方库

pip install flask==2.3.2 -i https://pypi.tuna.tsinghua.edu.cn/simple/
pip install pymysql -i https://pypi.tuna.tsinghua.edu.cn/simple/
pip3 install jinja2==3.1.2 -i https://pypi.tuna.tsinghua.edu.cn/simple/
pip install flask-script==2.0.5 -i https://pypi.tuna.tsinghua.edu.cn/simple/ 
pip install flask-sqlalchemy==3.0.3 -i https://pypi.tuna.tsinghua.edu.cn/simple/ 
pip install flask-migrate==2.7.0 -i https://pypi.tuna.tsinghua.edu.cn/simple/
pip install flask-bootstrap

(2). 配置settings.py 全局配置文件

# 前提:新建数据库
# create database flaskyyds(库名) charset = utf8;


# 配置文件
class Config:  # 公共配置
    DEBUG = True
    # mysql + pymysql ://user:password@hostip:port/databasename
    # 链接数据库
    SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:[email protected]:3306/flaskyyds'
    SQLALCHEMY_TRACK_MODIFICATIONS = False  # 忽略警告
    SQLALCHEMY_ECHO = True  # 开发调试


class DevelopmentConfig(Config):  # 开发环境
    ENV = "development"


class ProductionConfig(Config):  # 生产环境
    ENV = 'production'
    DEBUG = False

(3). 新建包文件 ext 包 / apps 包

(4). ext.__init__.py创建对象

# 创建映射对象
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()

# 创建bootstrap对象
from flask_bootstrap import Bootstrap
bootstrap = Bootstrap()

(5). apps / __init__.py 初始化对象 

import settings
from flask import Flask
from ext import db, bootstrap


def create_app():
    app = Flask(__name__, template_folder="../templates", static_folder="../static")
    # 导入settings.py文件
    app.config.from_object(settings.DevelopmentConfig)

    # 初始化配置db
    db.init_app(app=app)

    # 初始化bootstrap
    bootstrap.init_app(app)



    return app

(6). apps / user / views.py 定义蓝图

from flask import Blueprint

# url_prefix='/user': 前导航: xxxx/user/xxx
user_bp = Blueprint("user", __name__, url_prefix='/user')


@user_bp.route("/register", methods=["GET", "POST"])
def register():
    return "泰裤辣"

(7). apps / __init__.py 注册蓝图

from apps.user.view import user_bp


def create_app():
   ........
    # 注册蓝图
    app.register_blueprint(user_bp)

    return app

(8). 编辑app.py启动文件

from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager
from apps import create_app
from ext import db

app = create_app()

manager = Manager(app=app)

migrate = Migrate(app=app, db=db)
manager.add_command("db", MigrateCommand)

if __name__ == '__main__':
    manager.run()

(9). 终端启动项目

 python app.py runserver

# 浏览器访问:http://127.0.0.1:5000/user/register  ;出现 泰裤辣 表示配置成功

你可能感兴趣的:(Flask,flask)