Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting whether a Flask app handles a URL

I have a case for having a preliminary frontend Flask app before continuing to my main app.

I've implemented it using a "middleware" pattern:

class MyMiddleware(object):
    def __init__(self, main_app, pre_app):
        self.main_app = main_app
        self.pre_app = pre_app

    def __call__(self, environ, start_response):
        # check whether pre_app has a rule for this URL
        with self.pre_app.request_context(environ) as ctx:
            if ctx.request.url_rule is None:
                return self.main_app(environ, start_response)

        return self.pre_app(environ, start_response)

Is there a more idiomatic way of doing this, without creating a context just to check whether the URL is handled by the app? I want to maintain the flexibility of keeping two apps.

like image 836
Ilya Avatar asked Apr 18 '16 10:04

Ilya


People also ask

How do I find my URL data in Flask?

In the first one we would use request. args. get('<argument name>') where request is the instance of the class request imported from Flask. Args is the module under which the module GET is present which will enable the retrieve of the parameters.

How do you get all the routes on a Flask?

To get list of all routes defined in the Python Flask app, we can use the app. url_map property. to print the list of routes in our app with print(app. url_map) .

How do I redirect a URL in Flask?

Flask – Redirect & ErrorsFlask class has a redirect() function. When called, it returns a response object and redirects the user to another target location with specified status code. location parameter is the URL where response should be redirected. statuscode sent to browser's header, defaults to 302.


1 Answers

Each flask.Flask app has a url_map property - which is a werkzeug.routing.Map. You could just run bind_to_environ and use the test method from MapAdapter:

if self.pre_app.url_map.bind_to_environ(environ).test(environ['PATH_INFO']):
    return self.pre_app(environ, start_response)

return self.main_app(environ, start_response)

I don't know that I'd call it "more idiomatic" but it is another way of handling your use case.

like image 196
Sean Vieira Avatar answered Oct 08 '22 20:10

Sean Vieira