aiohttp 未关闭的客户端会话

huangapple go评论66阅读模式
英文:

aiohttp unclosed client session

问题

The error message you are encountering, "Unclosed client session," suggests that there might be an issue with how the aiohttp client session is being closed in your code. While your code appears to use async with and await correctly, there could be some external factors or issues causing this error. You might want to investigate further by checking for any potential exceptions or asynchronous tasks that could be preventing the session from closing properly.

However, without more context or debugging, it's challenging to pinpoint the exact cause of the error. You may want to consider looking into the aiohttp documentation or forums for more specific troubleshooting steps related to this error message.

英文:

Relating to my question posted earlier how to post aiohttp authenticated request? [duplicate] which was answered in Send user credentials in aiohttp request, I modified the code to below and managed to get the result from get_all_balances(), however I would have the error below prior to getting the result:

> Unclosed client session
> client_session: <aiohttp.client.ClientSession object at 0x0000019AD3E12790>
> Unclosed connector
> connections: ['[(<aiohttp.client_proto.ResponseHandler object at 0x0000019AD3E09470>, 613500.125)]']
> connector: <aiohttp.connector.TCPConnector object at 0x0000019AD34A93D0>

As far as I can see, the function is called with async with and the result is with await, my understanding is that the connection would be closed upon the result, so why is it that it's giving me an unclosed client session error?

import asyncio
import aiohttp
import json


base_url = &#39;https://api.luno.com&#39;
lapikey = &#39;&#39;
lapisecret = &#39;&#39;


async def do(method, path, req=None, auth=False):
    args = {}
    params = None
    if req:
        try:
            params = json.loads(json.dumps(req))
        except Exception:
            params = None
    if params:
        args = dict(params=params)
    url = make_url(path, params)
    if auth:
        args[&#39;auth&#39;] = aiohttp.BasicAuth(lapikey, lapisecret)
    async with aiohttp.ClientSession().request(method, url, **args) as res:
        try:
            return await res.json()
        except Exception as e:
            return e

def make_url(path, params):
    if params:
        for k, v in params.items():
            path = path.replace(&#39;{&#39; + k + &#39;}&#39;, str(v))
    return base_url + &#39;/&#39; + path.lstrip(&#39;/&#39;)

async def get_all_balances():
    return await do(&#39;GET&#39;, &#39;/api/1/balance&#39;, auth=True)


print(asyncio.run(get_all_balances()))

I have read other similar questions on aiohttp unclosed client session, as far as I can tell my code has already implemented all the requisite async with and await keywords to properly close the client session after the request, what is wrong?

答案1

得分: 2

以下是翻译后的代码部分:

尝试首先创建一个 aiohttp 的 `Session()`,然后执行请求

import asyncio
import aiohttp
import json

base_url = 'https://api.luno.com'
lapikey = ''
lapisecret = ''

async def do(method, path, req=None, auth=False):
    args = {}
    params = None
    if req:
        try:
            params = json.loads(json.dumps(req))
        except Exception:
            params = None
    if params:
        args = dict(params=params)
    url = make_url(path, params)
    if auth:
        args['auth'] = aiohttp.BasicAuth(lapikey, lapisecret)

    async with aiohttp.ClientSession() as session:  # <--- 在这里创建会话
        async with session.request(method, url, **args) as res:  # <--- 然后执行请求
            try:
                return await res.json()
            except Exception as e:
                return e

def make_url(path, params):
    if params:
        for k, v in params.items():
            path = path.replace('{' + k + '}', str(v))
    return base_url + '/' + path.lstrip('/')

async def get_all_balances():
    return await do('GET', '/api/1/balance', auth=True)

print(asyncio.run(get_all_balances()))

请注意,翻译中保留了代码中的特殊字符和标记。

英文:

Try to first make an aiohttp Session() and afterwards do a request:

import asyncio
import aiohttp
import json


base_url = &#39;https://api.luno.com&#39;
lapikey = &#39;&#39;
lapisecret = &#39;&#39;


async def do(method, path, req=None, auth=False):
    args = {}
    params = None
    if req:
        try:
            params = json.loads(json.dumps(req))
        except Exception:
            params = None
    if params:
        args = dict(params=params)
    url = make_url(path, params)
    if auth:
        args[&#39;auth&#39;] = aiohttp.BasicAuth(lapikey, lapisecret)

    async with aiohttp.ClientSession() as session:                # &lt;--- create session here
        async with session.request(method, url, **args) as res:   # &lt;-- and then do a request
            try:
                return await res.json()
            except Exception as e:
                return e

def make_url(path, params):
    if params:
        for k, v in params.items():
            path = path.replace(&#39;{&#39; + k + &#39;}&#39;, str(v))
    return base_url + &#39;/&#39; + path.lstrip(&#39;/&#39;)

async def get_all_balances():
    return await do(&#39;GET&#39;, &#39;/api/1/balance&#39;, auth=True)


print(asyncio.run(get_all_balances()))

huangapple
  • 本文由 发表于 2023年5月7日 00:49:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/76190068.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定