wuxiekeji
wuxiekeji

Reputation: 1902

How do I pass constructor arguments to a Flask Blueprint?

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?

Upvotes: 2

Views: 2645

Answers (2)

Menno
Menno

Reputation: 1143

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...

Upvotes: 2

Leon Young
Leon Young

Reputation: 585

There are several attributes of request object can be used to get url_prefix of a Blueprint object.

Perhaps request.script_root is simply what you want. For more information, the Flask documentation about request object is recommended.

Upvotes: 0

Related Questions