Python-Flask① | 路由规划

简单的一阶程度拆分:
基本拆分.png
注解:Manager启动会导入create_app,导入会进行创建初始化app,初始化时会导入views,回到init内部,返回manage.py

manage.py代码:

from flask_script import Manager
from App import create_app

app = create_app()
manager = Manager(app=app)
if __name__ == '__main__':
    manager.run()

App/views.py代码:

def init_route(app):
    @app.route('/')
    def hello_world():
        return 'Hello World!'

    @app.route('/hello/')
    def hello():
        return '1111!'

App/__init__.py代码:

from flask import Flask
from App.views import init_route

def create_app():
    app = Flask(__name__)

    init_route(app)

    return app

蓝图flask-blueprint(Demo):

App/manage.py代码:

from flask_script import Manager
from App import create_app

app = create_app()
manager = Manager(app=app)
if __name__ == '__main__':
    manager.run()

App/__init__.py代码:

from flask import Flask
from App.views import blue, second, init_view


def create_app():
   app = Flask(__name__)
   #app.register_blueprint(blue)
   #app.register_blueprint(second)
   #初始化view,传递app
   init_view(app=app)
   return app

views转换为包的形势→ 类名右键→ Refactor→ Convert to Python Package
App/views/__init__.py代码:

from App.views.fours_blue import fours
from .first_blue import blue
from .second_blue import second

def init_view(app):
    app.register_blueprint(blue)
    app.register_blueprint(second)
    app.register_blueprint(fours)

App/views/first_blue.py代码:

from flask import app, Blueprint

blue = Blueprint('blue', __name__)
@blue.route('/')
def index():
    return '我是蓝图的主页'

App/views/second_blue.py代码:

from flask import Blueprint

second = Blueprint('second', __name__)
@second.route('/hello/')
def hello():
    return 'Second Blue'
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容