Add a prefix to all Flask routes

后端 未结 10 1016
你的背包
你的背包 2020-11-22 09:40

I have a prefix that I want to add to every route. Right now I add a constant to the route at every definition. Is there a way to do this automatically?

PR         


        
10条回答
  •  时光说笑
    2020-11-22 10:19

    This is more of a python answer than a Flask/werkzeug answer; but it's simple and works.

    If, like me, you want your application settings (loaded from an .ini file) to also contain the prefix of your Flask application (thus, not to have the value set during deployment, but during runtime), you can opt for the following:

    def prefix_route(route_function, prefix='', mask='{0}{1}'):
      '''
        Defines a new route function with a prefix.
        The mask argument is a `format string` formatted with, in that order:
          prefix, route
      '''
      def newroute(route, *args, **kwargs):
        '''New function to prefix the route'''
        return route_function(mask.format(prefix, route), *args, **kwargs)
      return newroute
    

    Arguably, this is somewhat hackish and relies on the fact that the Flask route function requires a route as a first positional argument.

    You can use it like this:

    app = Flask(__name__)
    app.route = prefix_route(app.route, '/your_prefix')
    

    NB: It is worth nothing that it is possible to use a variable in the prefix (for example by setting it to /), and then process this prefix in the functions you decorate with your @app.route(...). If you do so, you obviously have to declare the prefix parameter in your decorated function(s). In addition, you might want to check the submitted prefix against some rules, and return a 404 if the check fails. In order to avoid a 404 custom re-implementation, please from werkzeug.exceptions import NotFound and then raise NotFound() if the check fails.

提交回复
热议问题