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.
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.
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) .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With