aiohttp web.response body as json

mor*_*air 21 python json python-3.x aiohttp

我对HTTP服务器aiohttp.如何web.Response()通过JSON(来自a dict)返回?

async def api_server(request):
    res = {"q": "qqq", "a": "aaa"}
    return web.Response(res) # <-- as JSON
Run Code Online (Sandbox Code Playgroud)

Wil*_*sem 26

你可以使用web.json_response:

async def api_server(request):
    res = {"q": "qqq", "a": "aaa"}
    return web.json_response(res)
Run Code Online (Sandbox Code Playgroud)

此外,json_response还有其他参数,如:

json_response(data, text=None, body=None, status=200, reason=None,
              headers=None, content_type='application/json', dumps=json.dumps)
Run Code Online (Sandbox Code Playgroud)

大多数参数与泛型相同web.Response(..),但dumps更有趣:它是对将数据转换为JSON等效项的方法的引用.默认情况下它使用json.dumps.但是,如果您计划将复杂对象写入客户端,则可能应该更改它.现在它很好.