Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add route prefix to Flask application running behing Gunicorn

tldr; Looking for a way to prefix all routes within an app running behind Gunicorn without a reverse proxy/blueprint/duplicate prefix in @route(PREFIX + '/') etc.


Creating a few Python services, using Flask, running in Docker containers.
Not, currently, using Nginx/Apache for reverse proxying.

Have something like below that works when running flask by itself
- (eg % python app.py responds with localhost:5000/a/b/some-route)

base_path = "/a/b"
app = DispatcherMiddleware(_root_app, {base_path: self})
run_simple(host, port, app, **options)

Not sure how to achieve the same result when running behind Gunicorn.
(Would really like to do this without making a blueprint for the main app. Also trying to avoid having the same prefix in every @route(PREFIX + ''))

Reason for doing this
Using an extension that adds a few routes, along with a blueprint. Would like to have app routes AND extension/blueprint routes to all be prefixed.

This question asked this specifically for Flask, which I'm able to get working using the DispatcherMiddleware approach.
My question is how to get this working when running behind Gunicorn (no Nginx or Apache in front, just Gunicorn)


Potential Fix:

Currently using a subclass of Flask (needed to do some customized logging nonsense.)
Overriding the add_url_rule works.

prefixed_rule = self._prefix_rule(rule)
super().add_url_rule(prefixed_rule,
                     endpoint=endpoint,
                     view_func=view_func,
                     **options)

This also works with our extensions too

like image 743
Justin Avatar asked Oct 26 '25 23:10

Justin


1 Answers

If you are doing app composition, then you can use the DispatcherMiddleware trick you referenced. However, it sounds like you are trying to have a single service that is subpath mounted, but doesn't serve anything out of the "higher" paths at all.

There are several different ways to do this.

  1. Replace Flask.url_map._rules with a werkzeug.routing.Submount rule factory:

    from werkzeug.routing import SubPath
    
    app = Flask(__name__)
    
    # register blueprints and extensions
    # load config, etc.
    
    app.url_map._rules = SubPath(app.config['APPLICATION_ROOT'], app.url_map._rules)
    
  2. Replace Flask.url_rule_class:

    from werkzeug.routing import Rule
    
    app.url_rule_class = lambda path, **options: Rule(PREFIX + path, **options)
    
  3. Replace add_url_rule, as you suggest in your question.

like image 199
Sean Vieira Avatar answered Oct 28 '25 13:10

Sean Vieira