如何将构造函数参数传递给Flask Blueprint? [英] How do I pass constructor arguments to a Flask Blueprint?

查看:226
本文介绍了如何将构造函数参数传递给Flask Blueprint?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个Flask网站上,我想创建一个名为 gallery 的Blueprint,它是一个Lightbox /美术馆应用程序,但是它有多个实例。例如,

  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的内容



$ b

In 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 argument source, 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆