def response_middleware(app, next_handler):
async def handler(request):
result = await next_handler(request)
if not isinstance(result, Response):
accept = request.headers.get('accept', 'application/json')
if accept in ('application/json', '*/*'):
if isinstance(result, ErrorResponse):
data, status, headers = result.data, result.status, result.headers
if headers:
# Passing both Content-Type header
# and content_type or charset params is forbidden
# (json_response already passes content_type)
headers.pop('content-type', None)
else:
data, status, headers = result, HTTP_OK, None
result = json_response(data, status=status, headers=headers)
else:
logger.error('Unable to serialize response (accept=%s)', accept)
raise HTTPBadRequest()
return result
return handler
评论列表
文章目录