flask的蓝图(blueprint)

Posted lilied

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了flask的蓝图(blueprint)相关的知识,希望对你有一定的参考价值。

1.新建目录结构 ![](https://images2018.cnblogs.com/blog/1184359/201804/1184359-20180421214050328-2116777012.png)

2.在蓝图模块admin下__init__.py加入以下(home同理) ``` from flask import Blueprint

admin = Blueprint(\'admin\', name)

from . import views

<h2><font color=\'9400D3\'>3.在蓝图模块admin下views.py加入以下..测试(home同理)

from . import admin

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

<h2><font color=\'9400D3\'>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)

<h2><font color=\'9400D3\'>5.在app下的settings配置文件加入

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

<h2><font color=\'9400D3\'>6.在app下的models.py加入

from datetime import datetime
from app import db

class People(db.Models):
pass

<h2><font color=\'9400D3\'>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()

<h2><font color=\'9400D3\'>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
***以后加入一个文件就引入一次

  1. ... db.init(app) ...
<h2><font color=\'9400D3\'>9.执行命令

数据库迁移

python manage.py db init
python manage.py db migrate
python manage.py db upgrade

运行
python manage.py runserver

以上是关于flask的蓝图(blueprint)的主要内容,如果未能解决你的问题,请参考以下文章

Flask蓝图Blueprint的使用

Flask中的蓝图(BluePrint)

flask-蓝图(Blueprint)

Flask初学者:蓝图Blueprint

Flask基础之蓝图(blueprint)

flask中的蓝图 Blueprint