I have a problem and after a few hours of searching I can't find a solution.
I have a flask based API. Under normal flow it works like this:
before_request
handler is used to validate things like the customer and their API key etc.- Then the requested endpoint function is called
- I then use
after_request
to log various stats about the API call
That all works great.
The problem is when I need to call abort during the before_request. For example, abort(404)
In this situation, the User receives the abort status error code (404) and the execution continues to the after_request handler (as expected)
My issue is that I cant work out how to "know", from within the after_request
handler, that the request has been aborted.
Within the after_request
function the response
object has a status_code of 200, not 404 - I assume because the endpoint was never called and 200 is its default setting.
I either need the response object to reflect the actual code that was returned to the end-user or have some way of knowing that the abort/exception occurred.
Any suggestions?
CodePudding user response:
I am seeing different result than you are:
from flask import Flask, request, abort
def create_app(config_file=None):
app = Flask(__name__)
app.debug = True
@app.before_request
def before_request():
print("Before request: pre 404")
abort(404)
print("Aborts before getting to this")
@app.after_request
def after_request(request):
print("After request: pre")
print(request.status_code) # <-- this is 404
print("After request: post")
return request
@app.route('/')
def index():
return "This string never makes it screen"
return app
Before request: pre 404
After request: pre
404
After request: post
127.0.0.1 - - [19/Nov/2021 15:01:03] "GET / HTTP/1.1" 404 -
What is your setup and what is the result for what you are seeing with comparable code?
CodePudding user response:
I found the problem. I had forgotten to return the error code as part of my custom error handler.