gpt4 book ai didi

python - aiohhttp中的 session 重用

转载 作者:行者123 更新时间:2023-12-01 15:24:07 27 4
gpt4 key购买 nike

我尝试重用 HTTP session 作为 aiohttp 文档建议

Don’t create a session per request. Most likely you need a session per application which performs all requests altogether.



但是我与请求库一起使用的通常模式不起作用:
def __init__(self):
self.session = aiohttp.ClientSession()

async def get_u(self, id):
async with self.session.get('url') as resp:
json_resp = await resp.json()

return json_resp.get('data', {})

然后我尝试
await client.get_u(1)

我有错误
RuntimeError: Timeout context manager should be used inside a task

任何 async_timeout 的解决方法都没有帮助。

另一种方法是工作:
async def get_u(self, id):
async with aiohttp.ClientSession() as session:
with async_timeout.timeout(3):
async with session.get('url') as resp:
json_resp = await resp.json()
return json_resp.get('data', {})

但似乎每个请求都创建 session 。
所以我的问题是:如何正确重用 aiohttp-session?

UPD:最小工作示例。具有以下 View 的 Sanic 应用程序
import aiohttp
from sanic.views import HTTPMethodView


class Client:
def __init__(self):
self.session = aiohttp.ClientSession()
self.url = 'https://jsonplaceholder.typicode.com/todos/1'

async def get(self):
async with self.session.get(self.url) as resp:
json_resp = await resp.json()

return json_resp


client = Client()


class ExView(HTTPMethodView):
async def get(self, request):
todo = await client.get()
print(todo)

最佳答案

我有同样的错误。我的解决方案是在异步函数中初始化客户端。例如:

class SearchClient(object):

def __init__(self, search_url: str, api_key: str):
self.search_url = search_url
self.api_key = api_key
self.session = None

async def _get(self, url, attempt=1):
if self.session is None:
self.session = aiohttp.ClientSession(raise_for_status=True)

headers = {
'Content-Type': 'application/json',
'api-key': self.api_key
}
logger.info("Running Search: {}".format(url))
try:
with timeout(60):
async with self.session.get(url, headers=headers) as response:
results = await response.json()
return results

关于python - aiohhttp中的 session 重用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52532075/

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