Issue:
I have a Bottle application where I raise HTTPResponse
in case of an error. Simplified version of the code provided below:
Now, when I hit the URL: http://localhost:8080/error
I get:
APP 1 - Before Request http://localhost:8080/error
APP 1 - After Request http://localhost:8080/error - status code: 200
127.0.0.1 - - [10/Nov/2014 12:05:38] "GET /error HTTP/1.1" 400 0
Notice the line with status code as 200
even though I am raising the HTTPResponse
status code of 400
(which is evident in the last line).
This means the request.status_code
is incorrect when accessed in the after_request
method.
Workaround:
To circumnavigate the issue I used Bottle's Plugin
concept like so:
Notice the access_status_correctly
method. It is very similar to Spring's AOP around advice. In other words: Bottle's Plugin
== Springs AOP Around advice
.
Breaking down the work around:
Simply put you can do a bunch of things before and after an api method call. In my case I am:
before method call:
print "Before making the actual method call"
actual method call:
body = callback(*args, **kwargs)
after method call:
print "After method call: Yay!"
exception handling for method call:
except CustomHttpException as exc:
print "Correct error status code here: {}".format(exc.status_code)
raise HTTPResponse(status=exc.status_code, body={'message': exc.message})
except Exception:
print "A general exception occurred"
raise HTTPResponse(status=500)
Even though I have a work around I would have ideally liked the after_request
method to have worked i.e. use response.status_code
to access the actual status_code
.
May be I don't understand the after_request
concept correctly. I have a Stackoverflow question open here.
Comments/feedback? Were you able to make it work?