Request-specific after_request handlers
This commit is contained in:
@@ -256,6 +256,7 @@ class Request():
|
||||
self._json = None
|
||||
self._form = None
|
||||
self.g = Request.G()
|
||||
self.after_request_handlers = []
|
||||
|
||||
@staticmethod
|
||||
def create(app, client_stream, client_addr):
|
||||
@@ -340,6 +341,28 @@ class Request():
|
||||
self._form = self._parse_urlencoded(self.body.decode())
|
||||
return self._form
|
||||
|
||||
def after_request(self, f):
|
||||
"""Register a request-specific function to run after the request is
|
||||
handled. Request-specific after request handlers run at the very end,
|
||||
after the application's own after request handlers. The function must
|
||||
take two arguments, the request and response objects. The return value
|
||||
of the function must be the updated response object.
|
||||
|
||||
Example::
|
||||
|
||||
@app.route('/')
|
||||
def index(request):
|
||||
# register a request-specific after request handler
|
||||
@req.after_request
|
||||
def func(request, response):
|
||||
# ...
|
||||
return response
|
||||
|
||||
return 'Hello, World!'
|
||||
"""
|
||||
self.after_request_handlers.append(f)
|
||||
return f
|
||||
|
||||
@staticmethod
|
||||
def _safe_readline(stream):
|
||||
line = stream.readline(Request.max_readline + 1)
|
||||
@@ -740,9 +763,10 @@ class Microdot():
|
||||
|
||||
Example::
|
||||
|
||||
@app.before_request
|
||||
@app.after_request
|
||||
def func(request, response):
|
||||
# ...
|
||||
return response
|
||||
"""
|
||||
self.after_request_handlers.append(f)
|
||||
return f
|
||||
@@ -904,6 +928,8 @@ class Microdot():
|
||||
res = Response(res)
|
||||
for handler in self.after_request_handlers:
|
||||
res = handler(req, res) or res
|
||||
for handler in req.after_request_handlers:
|
||||
res = handler(req, res) or res
|
||||
elif 404 in self.error_handlers:
|
||||
res = self.error_handlers[404](req)
|
||||
else:
|
||||
|
||||
@@ -117,6 +117,10 @@ class TestMicrodot(unittest.TestCase):
|
||||
@app.before_request
|
||||
def before_request(req):
|
||||
if req.path == '/bar':
|
||||
@req.after_request
|
||||
def after_request(req, res):
|
||||
res.headers['X-Two'] = '2'
|
||||
return res
|
||||
return 'bar', 202
|
||||
req.g.message = 'baz'
|
||||
|
||||
@@ -143,6 +147,7 @@ class TestMicrodot(unittest.TestCase):
|
||||
app.run()
|
||||
self.assertTrue(fd.response.startswith(b'HTTP/1.0 202 N/A\r\n'))
|
||||
self.assertIn(b'X-One: 1\r\n', fd.response)
|
||||
self.assertIn(b'X-Two: 2\r\n', fd.response)
|
||||
self.assertIn(b'Set-Cookie: foo=bar\r\n', fd.response)
|
||||
self.assertIn(b'Content-Length: 3\r\n', fd.response)
|
||||
self.assertIn(b'Content-Type: text/plain\r\n', fd.response)
|
||||
|
||||
Reference in New Issue
Block a user