我正在阅读Flask示例,该示例从单个脚本应用程序转换到应用程序工厂,因此引入了蓝图。 使用蓝图的原因是因为应用程序实例现在是在运行时创建的,而不是在全局范围中存在(如在单个脚本应用程序中)。 这会导致app.route装饰器在调用create_app()后存在,本书指出这太晚了。 为什么在调用create_app()之后app.route装饰器存在为时已晚? 为什么我们要在调用create_app()之前访问路由?
I was reading up on a Flask example that transitions from a single script application to an application factory and for this reason blueprints are introduced. The reasoning for using blueprints is because the application instance is now created at runtime instead of existing in the global scope (as it was in the single script application). This causes the app.route decorator to exist after create_app() is invoked, which the book states is too late. Why is it considered too late for the app.route decorator to exist after create_app() is invoked? Why would we want to access the routes prior to invoking create_app()?
最满意答案
当您编写应用程序工厂时,在调用工厂之前您没有应用程序实例。 工厂只在运行服务器时调用,但在运行服务器之前需要定义路由。 因此,您将它们附加到蓝图上,并在工厂中的应用程序上注册蓝图。
# this would fail, app doesn't exist @app.route('/blog/<int:id>') def post(id): ... # this works because the route is registered on the blueprint # which is later registered on the app blog_bp = Blueprint('blog', __name__, url_prefix='/blog') @blog_bp.route('/<int:id>') def post(id): ... def create_app(): app = Flask(__name__) ... app.register_blueprint(blog_bp) ... return app # app still doesn't exist, it only exists when the server uses the factoryWhen you write an app factory, you don't have an app instance until the factory is called. The factory is only called when running the server, but you need to define your routes before you run the server. So you attach them to blueprints instead, and register the blueprints on the app in the factory.
# this would fail, app doesn't exist @app.route('/blog/<int:id>') def post(id): ... # this works because the route is registered on the blueprint # which is later registered on the app blog_bp = Blueprint('blog', __name__, url_prefix='/blog') @blog_bp.route('/<int:id>') def post(id): ... def create_app(): app = Flask(__name__) ... app.register_blueprint(blog_bp) ... return app # app still doesn't exist, it only exists when the server uses the factory更多推荐
发布评论