首页 文章

aiohttp web.response body as json

提问于
浏览
17

我在 aiohttp 上有python-3.6的HTTP服务器 . 如何通过JSON(来自 dict )返回 web.Response()

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

1 回答

  • 20

    你可以使用web.json_response

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

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

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

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

相关问题