Split Python Flask app into multiple files

后端 未结 4 1276
执念已碎
执念已碎 2020-11-27 10:28

I\'m having trouble understanding how to split a flask app into multiple files.

I\'m creating a web service and I want to split the api\'s into different files (Acco

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-27 10:43

    Using Blueprint you can add your routes in the routes directory.

    Structure

    app.py
    routes
        __init__.py
        index.py
        users.py
    

    __init__.py

    from flask import Blueprint
    routes = Blueprint('routes', __name__)
    
    from .index import *
    from .users import *
    

    index.py

    from flask import render_template
    from . import routes
    
    @routes.route('/')
    def index():
        return render_template('index.html')
    

    users.py

    from flask import render_template
    from . import routes
    
    @routes.route('/users')
    def users():
        return render_template('users.html')
    

    app.py

    from routes import *
    app.register_blueprint(routes)
    

    If you want to add a new route file, say accounts.py, you just need to create the file accounts.py in the routes directory, just like index.py and users.py, then import it in the routes.__init__.py file

    from .accounts import *
    

提交回复
热议问题