It should be noted that APPLICATION_ROOT NOT for this purpose.
All you have to do is write middleware to make the following changes:
- change
PATH_INFO to handle the URL prefix. - edit
SCRIPT_NAME to create a prefix URL.
Like this:
class PrefixMiddleware(object): def __init__(self, app, prefix=''): self.app = app self.prefix = prefix def __call__(self, environ, start_response): if environ['PATH_INFO'].startswith(self.prefix): environ['PATH_INFO'] = environ['PATH_INFO'][len(self.prefix):] environ['SCRIPT_NAME'] = self.prefix return self.app(environ, start_response) else: start_response('404', [('Content-Type', 'text/plain')]) return ["This url does not belong to the app.".encode()] start_response): class PrefixMiddleware(object): def __init__(self, app, prefix=''): self.app = app self.prefix = prefix def __call__(self, environ, start_response): if environ['PATH_INFO'].startswith(self.prefix): environ['PATH_INFO'] = environ['PATH_INFO'][len(self.prefix):] environ['SCRIPT_NAME'] = self.prefix return self.app(environ, start_response) else: start_response('404', [('Content-Type', 'text/plain')]) return ["This url does not belong to the app.".encode()]
Wrap the application with middleware, for example:
from flask import Flask, url_for app = Flask(__name__) app.debug = True app.wsgi_app = PrefixMiddleware(app.wsgi_app, prefix='/foo') @app.route('/bar') def bar(): return "The URL for this page is {}".format(url_for('bar')) if __name__ == '__main__': app.run('0.0.0.0', 9010)
Visit http://localhost:9010/foo/bar ,
You will get the correct result: The URL for this page is /foo/bar
And don't forget to set a cookie domain if you need to.
This solution is given by Larivact gist . APPLICATION_ROOT not for this job, although it seems like it is. This is really confusing.
su27 Mar 16 '16 at 10:57 2016-03-16 10:57
source share