Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return from before_request() in flask

I'm new to flask and currently converting an existing WSGI application to run through flask as long term it'll make life easier.

All requests are POST to specific routes however the current application inspects the post data prior to executing the route to see if the request needs to be run at all or not (i.e. if an identifier supplied in the post data already exists in our database or not).

If it does exist a 200 code and json is returned "early" and no other action is taken; if not the application continues to route as normal.

I think I can replicate the activity at the right point by calling before_request() but I'm not sure if returning a flask Response object from before_request() would terminate the request adequately at that point? Or if there's a better way of doing this?

NB: I must return this as a 200 - other examples I've seen result in a redirect or 4xx error handling (as a close parallel to this activity is authentication) so ultimately I'm doing this at the end of before_request():

    if check_request_in_progress(post_data) is True:
        response = jsonify({'request_status': 'already_running'})
        response.status_code = 200
        return response
    else:
        add_to_requests_in_progress(post_data)

Should this work (return and prevent further routing)?

If not how can I prevent further routing after calling before_request()?

Is there a better way?

like image 381
CoderChris Avatar asked Mar 05 '23 14:03

CoderChris


1 Answers

Based on what they have said in the documents, it should do what you want it to do.

The function will be called without any arguments. If the function returns a non-None value, it’s handled as if it was the return value from the view and further request handling is stopped. (source)

@app.route("/<name>")
def index(name):
    return f"hello {name}"

@app.before_request
def thing():
    if "john" in request.path:
    return "before ran"

with the above code, if there is a "john" in the url_path, we will see the before ran in the output, not the actual intended view. you will see hello X for other string. so yes, using before_request and returning something, anything other than None will stop flask from serving your actual view. you can redirect the user or send them a proper response.

like image 85
senaps Avatar answered Mar 19 '23 11:03

senaps