Change flask url before routing

My Flask has URL routing defined as

self.add_url_rule('/api/1/accounts/<id_>', view_func=self.accounts, methods=['GET']) 

The problem is that one of the applications making requests to this application adds an additional / to the url, for example / api / 1 // accounts / id . I was unable to fix the application that makes such requests, so I cannot change it.

To solve this problem, I have now added a few rules

 self.add_url_rule('/api/1/accounts/<id_>', view_func=self.accounts, methods=['GET']) self.add_url_rule('/api/1//accounts/<id_>', view_func=self.accounts, methods=['GET']) 

There are many such routes, and this is an ugly workaround. Is there a way in a jar to change the URL before it gets into the routing logic?

+5
source share
1 answer

I would normalize the path before it gets to Flask, either using an HTTP server that hosts the WSGI container, or a proxy server that sits in front of your stack, or using the WSGI middleware.

The latter is easy to write:

 import re from functools import partial class PathNormaliser(object): _collapse_slashes = partial(re.compile(r'/+').sub, r'/') def __init__(self, application): self.application = application def __call__(self, env, start_response): env['PATH_INFO'] = self._collapse_slashes(env['PATH_INFO']) return self.application(env, start_response) 

You may need to register that you are applying this conversion, along with diagnostic information such as the REMOTE_HOST and HTTP_USER_AGENT entries. Personally, I would make this particular application generate non-broken URLs as soon as possible.

Take a look at your WSGI server documentation to learn how to add additional WSGI middleware components.

+4
source

Source: https://habr.com/ru/post/1269026/


All Articles