9

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

不要为每个请求创建会话。您很可能需要每个应用程序一个会话来完全执行所有请求。

但是我与 requests lib 一起使用的通常模式不起作用:

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', {})

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

UPD:最小的工作示例。具有以下视图的 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)
4

2 回答 2

6

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

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
于 2019-11-27T14:22:42.607 回答
1

例如,您可以ClientSession在应用启动时创建(使用on_startup信号https://docs.aiohttp.org/en/stable/web_advanced.html#signals)。将其存储到您的应用程序(aiohttp 应用程序具有此类问题的 dict 接口https://aiohttp.readthedocs.io/en/stable/faq.html#id4request.app['YOU_CLIENT_SESSION'] )并通过请求访问您的会话。

于 2018-09-28T13:24:31.143 回答