美文网首页
Python-Flask① | 路由规划

Python-Flask① | 路由规划

作者: Gawain_Knowknow | 来源:发表于2020-03-07 13:59 被阅读0次
    简单的一阶程度拆分:
    基本拆分.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'
    

    相关文章

      网友评论

          本文标题:Python-Flask① | 路由规划

          本文链接:https://www.haomeiwen.com/subject/qqccdhtx.html