如何将构造函数参数传递给Flask Blueprint? [英] How do I pass constructor arguments to a Flask Blueprint?
问题描述
app.register_blueprint(gallery,url_prefix ='/ photos')
app.register_blueprint(gallery, url_prefix ='/ paintings')
然而,我希望图库的两个实例具有完全独立的内容源,所以蓝图需要一个额外的参数,即
app.register_blueprint(gallery,url_prefix ='/ photos',source_directory ='内容/照片/')
app.register_blueprint(gallery,url_prefix ='/ paintings',source_directory ='content / paintings /')
我如何使这成为可能?或者,我可以访问Blueprint中的 url_prefix 本身?
Flask实现了Werkzeug所做的所有路由选择(Flask基于Werkzeug),但是在werkzeug中,可以使用任何
路由,如下所示:
gallery = Blueprint(__ name__,__name__,url_prefix ='/< any(photos,paintings):source>')
如果您在视图上使用 @ gallery.route
会得到一个参数 source
,您可以使用它来确定您的源目录。
def show(source):
#显示来源为photos或paintings的内容
$ c $不知道这是否适用于Flask,但值得一试...
$ bIn a Flask website, I want to create a Blueprint called gallery which is a lightbox/art gallery application, but have multiple instances of it. For example,
app.register_blueprint(gallery,url_prefix='/photos') app.register_blueprint(gallery,url_prefix='/paintings')
However I want the two instances of gallery to have entirely independent content sources, so the Blueprint needs an additional argument, i.e.
app.register_blueprint(gallery,url_prefix='/photos',source_directory='content/photos/') app.register_blueprint(gallery,url_prefix='/paintings',source_directory='content/paintings/')
How do I make this possible? Alternatively can I access what url_prefix was in the Blueprint itself?
解决方案I'm not sure if Flask implements all of the routing stuff that Werkzeug does (Flask is based on Werkzeug), but in werkzeug you can use an
any
route, like so:gallery = Blueprint(__name__, __name__, url_prefix='/<any("photos,paintings"):source>')
If you use
@gallery.route
on your views, you'll get an argumentsource
, which you can use to determine your source directory.@gallery.route('/show') def show(source): # Show stuff based on source being "photos" or "paintings"
Not sure if that works in Flask, but worth a shot...
这篇关于如何将构造函数参数传递给Flask Blueprint?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!