【问题标题】:aiohttp web.response body as jsonaiohttp web.response 正文为 json
【发布时间】:2017-12-26 06:55:17
【问题描述】:

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

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

【问题讨论】:

    标签: python-3.6 python json python-3.x aiohttp


    【解决方案1】:

    你可以使用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。但是,如果您打算将复杂的对象写入客户端,您也许应该改变它。不过现在还好。

    【讨论】:

    • 如何在此处添加标题“Total”? match_count = len(matches) headers = {'total': match_count} return web.json_response({"matches": fdata})
    • @binrebin:您可以将字典传递给headers 参数,例如web.json_response(res, headers={'Total': '1425'})
    猜你喜欢
    • 1970-01-01
    • 2022-12-30
    • 2022-12-15
    • 1970-01-01
    • 1970-01-01
    • 2020-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多