gpt4 book ai didi

python - 如何使用 aiohttp 模拟外部请求?

转载 作者:行者123 更新时间:2023-11-28 18:59:09 24 4
gpt4 key购买 nike

我正在尝试模拟对外部 URL 的单个请求,但在文档中仅存在内部请求示例(以“/”开头),不可能在当前版本中添加不以“/”开头的路由器的 aiohttp。我正在使用 pytest 和 pytest-aiohttp,这里是请求代码的示例:

import aiohttp
import asyncio

async def fetch(client):
async with client.get('http://python.org') as resp:
return resp.status, (await resp.text())

async def main():
async with aiohttp.ClientSession() as client:
html = await fetch(client)
print(html)

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

我想做的那种断言很简单,比如检查状态码、头部和内容。

最佳答案

您可以修补(使用 asynctest.patch)您的 ClientSession。但在这种情况下,您需要使用 .status、async .text() (async .json()) 等方法和属性来实现简单的ResponseContextManager

关于python - 如何使用 aiohttp 模拟外部请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54632639/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com