flask的蓝图(blueprint)

1.新建目录结构

2.在蓝图模块admin下__init__.py加入以下(home同理)

from flask import Blueprint

admin = Blueprint('admin', __name__)

from . import views

3.在蓝图模块admin下views.py加入以下..测试(home同理)

from . import admin

@admin.route('/')
def index():
    return '测试2............', 200

4.在app下的__init__.py中加入

from flask import Flask
from flask_sqlalchemy import SQLAlchemy


db = SQLAlchemy()
# ...


def create_app():
    app = Flask(__name__)

    # 导入配置文件
    app.config.from_object('app.settings')
    # ...

    # 初始化数据库
    db.init_app(app)
    # ...

    # 注册蓝图(最后一步)
    register(app)

    return app


def register(app):
    from .admin import admin
    from .home import home
    app.register_blueprint(admin, url_prefix='/admin')
    app.register_blueprint(home)

5.在app下的settings配置文件加入

SQLALCHEMY_TRACK_MODIFICATIONS = True
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:123456@127.0.0.1/xxx'

6.在app下的models.py加入

from datetime import datetime
from app import db

class People(db.Models):
    pass

7.在总目录下的执行文件manage.py下加入

from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from app import create_app

# 此刻导入models.py下的db (app/__init__.py  ----> app/models.py -----> manage.py)
from app.models import db

# 创建app对象
app = create_app()

# 数据库迁移配置
manager = Manager(app)
migrate = Migrate(app, db)
manager.add_command('db', MigrateCommand)

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

8.models中表过多问题

1.新建app/models文件夹, 在其中的__init__.py 中加入db = SQLALchemy()
2.在app/models/admin.py和app/models/home.py 下 分别引入 from . import db
3.在app/__init__.py下引入from app.models import admin和from app.models import home和from app.models import db
**********************以后加入一个文件就引入一次*******************

4.   ... db.init(app) ...

9.执行命令

# 数据库迁移
python manage.py db init
python manage.py db migrate
python manage.py db upgrade

运行
python manage.py runserver
posted @ 2018-02-06 20:45  lilied  阅读(383)  评论(0编辑  收藏  举报