python - Add a prefix to all Flask routes -
i have prefix want add every route. right add constant route @ every definition. there way automatically?
prefix = "/abc/123" @app.route(prefix + "/") def index_page(): return "this website burritos" @app.route(prefix + "/about") def about_page(): return "this website burritos"
the answer depends on how serving application.
sub-mounted inside of wsgi container
assuming going run application inside of wsgi container (mod_wsgi, uwsgi, gunicorn, etc); need mount, @ prefix application sub-part of wsgi container (anything speaks wsgi do) , set application_root
config value prefix:
app.config["application_root"] = "/abc/123" @app.route("/") def index(): return "the url page {}".format(url_for("index")) # return "the url page /abc/123/"
setting application_root
config value limit flask's session cookie url prefix. else automatically handled flask , werkzeug's excellent wsgi handling capabilities.
an example of sub-mounting app
if not sure first paragraph means, take @ example application flask mounted inside of it:
from flask import flask, url_for werkzeug.serving import run_simple werkzeug.wsgi import dispatchermiddleware app = flask(__name__) app.config['application_root'] = '/abc/123' @app.route('/') def index(): return 'the url page {}'.format(url_for('index')) def simple(env, resp): resp(b'200 ok', [(b'content-type', b'text/plain')]) return [b'hello wsgi world'] app.wsgi_app = dispatchermiddleware(simple, {'/abc/123': app.wsgi_app}) if __name__ == '__main__': app.run('localhost', 5000)
proxying requests app
if, on other hand, running flask application @ root of wsgi container , proxying requests (for example, if it's being fastcgi'd to, or if nginx proxy_pass
-ing requests sub-endpoint stand-alone uwsgi
/ gevent
server can either:
- use blueprint, miguel points out in his answer.
- or use
dispatchermiddleware
werkzeug
(orprefixmiddleware
su27's answer) sub-mount application in stand-alone wsgi server you're using. (see an example of sub-mounting app above code use).
Comments
Post a Comment