如何缓存所有asyncio响应以确保它们具有CORS标头和JSON响应?

时间:2017-08-07 12:32:19

标签: python-3.x python-asyncio aiohttp

我正在尝试使用aiohttp Server构建服务。

但是我需要确保所有响应都正确处理CORS标头,并且所有错误都会返回JSON响应。

我该如何实现这样的事情?

2 个答案:

答案 0 :(得分:2)

关于CORS支持 - 使用aiohttp-cors。 自述文件包含所有设置和使用说明。

答案 1 :(得分:0)

您可能希望了解中间件:

http://aiohttp.readthedocs.io/en/stable/web.html#example

以下是一个例子:

from aiohttp import web


def setup_middlewares(app):
    error_middleware = error_pages({404: handle_404,
                                    500: handle_500})
    app.middlewares.append(error_middleware)


def error_pages(overrides):
    async def middleware(app, handler):
        async def middleware_handler(request):
            try:
                response = await handler(request)
                override = overrides.get(response.status)
                if override is None:
                    return response
                else:
                    return await override(request, response)
            except web.HTTPException as ex:
                override = overrides.get(ex.status)
                if override is None:
                    return await handle_any(request, ex)
                else:
                    return await override(request, ex)
            except Exception as ex:
                return await handle_500(request, error=ex)
        return middleware_handler
    return middleware


async def handle_any(request, response):
    return web.json_response({
        "status": response.status,
        "message": response.reason
    }, status=response.status)


async def handle_404(request, response):
    return web.json_response({
        "status": 404,
        "message": "Page '{}' not found".format(request.path)
    }, status=404)


async def handle_500(request, response=None, error=None):
    return web.json_response({
            "status": 503,
            "message": "Service currently unavailable"
        }, status=503)