I’ve made this small example to help recreate the issue.
from sanic import Sanic
from sanic.response import HTTPResponse
app = Sanic("middleware_test")
@app.middleware("request")
async def _prepare(request):
request.ctx.test = 'ASDF'
@app.middleware("response")
async def _cleanup(request, response):
test = request.ctx.test
@app.route("/")
async def test(request):
test = request.ctx.test
return HTTPResponse("Got Test: %s" % test, content_type='text/html')
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8888)
If you run the code, you’ll notice the handler renders the response just fine, but if you look at the console output you’ll notice the traceback:
[2020-07-04 21:45:19 +0000] [21208] [ERROR] Exception occurred in one of response middleware handlers
Traceback (most recent call last):
File "<path>/env/lib/python3.6/site-packages/sanic/app.py", line 977, in handle_request
request, response, request_name=name
File "<path>/env/lib/python3.6/site-packages/sanic/app.py", line 1281, in _run_response_middleware
_response = await _response
File "mwtest.py", line 12, in _cleanup
test = request.ctx.test
AttributeError: 'types.SimpleNamespace' object has no attribute 'test'