Python aiohttp-每次API调用请求之前

Python aiohttp-每次API调用请求之前,python,python-asyncio,swagger-ui,aiohttp,connexion,Python,Python Asyncio,Swagger Ui,Aiohttp,Connexion,当我使用Flask时,每个API调用在处理之前都经过身份验证: app = connexion.App(__name__, specification_dir='./swagger/', swagger_json=True, swagger_ui=True, server='tornado') app.app.json_encoder = encoder.JSONEncoder app.add_api('swagger.yaml', arguments={'title': 'ABCD API'}

当我使用Flask时,每个API调用在处理之前都经过身份验证:

app = connexion.App(__name__, specification_dir='./swagger/', swagger_json=True, swagger_ui=True, server='tornado')
app.app.json_encoder = encoder.JSONEncoder
app.add_api('swagger.yaml', arguments={'title': 'ABCD API'})
# add CORS support
CORS(app.app)
options = {'swagger_path': 'swagger/', "swagger_ui": True}
app = connexion.AioHttpApp(__name__, specification_dir='swagger/', options=options)
app.add_api('swagger.yaml', arguments={'title': ' ABCD API'})
app = web.Application(middlewares=[auth_through_token])
当我将其更改为AioHttp时,我的身份验证设置不正确:

app = connexion.App(__name__, specification_dir='./swagger/', swagger_json=True, swagger_ui=True, server='tornado')
app.app.json_encoder = encoder.JSONEncoder
app.add_api('swagger.yaml', arguments={'title': 'ABCD API'})
# add CORS support
CORS(app.app)
options = {'swagger_path': 'swagger/', "swagger_ui": True}
app = connexion.AioHttpApp(__name__, specification_dir='swagger/', options=options)
app.add_api('swagger.yaml', arguments={'title': ' ABCD API'})
app = web.Application(middlewares=[auth_through_token])
我的请求没有被重定向到API方法

在请求每个API的身份验证之前,是否有人可以帮助我设置? 谢谢。

首先,您必须通过\u令牌将中间件\u处理程序从auth\u移出

那么, 引用您的代码:

options = {'swagger_path': 'swagger/', "swagger_ui": True}
app = connexion.AioHttpApp(__name__, specification_dir='swagger/', options=options)
app.add_api('swagger.yaml', arguments={'title': ' ABCD API'})
app = web.Application(middlewares=[auth_through_token])
您必须删除最后一行,并将第一行更改为:

options = {'swagger_path': 'swagger/', "swagger_ui": True, 'middlewares': [middleware_handler]}
最后,代码应该如下所示:

options = {'swagger_path': 'swagger/', "swagger_ui": True, 'middlewares': [middleware_handler]}
app = connexion.AioHttpApp(__name__, specification_dir='swagger/', options=options)
app.add_api('swagger.yaml', arguments={'title': ' ABCD API'})

@web.middleware
async def middleware_handler(request: web.Request, handler: Any) -> web.Response:
    headers = request.headers
    x_auth_token = headers.get("X-Token")
    app_id = headers.get("X-AppId")
    user, success = security.Security().authorize(x_auth_token)
    if not success:
        return web.json_response(status=401, data={
            "error": {
                "message": ("Not authorized. Reason: {}"
                            )
            }
        })
    response = await handler(request)
    return response

对我来说,似乎可以在中间件列表中使用
中间件\u handler
。如果您不想这样做,您需要通过令牌从
auth\u调用它。但我还没查过。如果有帮助,请告诉我。