4

I want to attach a middleware to specific handler and if client is not authorized then want to return an error response. However with the following code :

async def middleware_factory(app, handler):
   async def auth_handler(request):
       if request.headers.get('Authorization') == 'Basic test1234':
           return await handler(request)
       return web.Response(text='Forbidden', status='403')
   return auth_handler

I am getting an exception that :

AssertionError: Handler <function AbstractRoute.__init__.
<locals>.handler_wrapper at 0x10da56bf8> should return response
instance, got <class 'NoneType'> [middlewares [<function 
middleware_factory at 0x1104cb268>]]

Documentation states that I should return a response object which I am doing. Still this error. Where am I going wrong?

h4ck3d
  • 6,134
  • 15
  • 51
  • 74
  • It seems the handler which was called and the middleware is trying to wrap did not reply with a web response, but that part is not in the code. I've seen similar errors with double response, too, it can be tricky to spot the problem – Jacopofar Apr 13 '17 at 14:16
  • @h4ck3d.... did you come up with the correct answer? do the favor of answering: https://stackoverflow.com/questions/58885706/aiohttp-before-request-for-each-api-call – Anant Nov 21 '19 at 21:13

1 Answers1

1

You can look to an example from official documentation.

But the main concern that if you want to have Middleware Factory - needs to be a function not a coroutine. Also, recommend to use @web.middleware decorator for that.

from aiohttp import web

def middleware_factory(text):
    @web.middleware
    async def sample_middleware(request, handler):
        resp = await handler(request)
        resp.text = resp.text + text
        return resp
    return sample_middleware
wowkin2
  • 5,895
  • 5
  • 23
  • 66
  • could you help me out? https://stackoverflow.com/questions/58885706/aiohttp-before-request-for-each-api-call – Anant Nov 21 '19 at 21:12