gpt4 book ai didi

python - 运行时错误 : Session is closed when using aiohttp session

转载 作者:行者123 更新时间:2023-12-05 00:57:10 26 4
gpt4 key购买 nike

我正在尝试使用 asyncio 构建一个简单的类,但出现错误

builtins.RuntimeError: session 已关闭

我认为这与服务器无关,而是与我的代码架构有关。

代码如下:

import aiohttp
import asyncio

class MordomusConnect:

def __init__(self, ip=None, port='8888'):
self._ip = ip
self._port = port


async def _getLoginSession(self):
jar = aiohttp.CookieJar(unsafe=True)
async with aiohttp.ClientSession(cookie_jar=jar) as session:
async with session.get('http://192.168.1.99:8888/json?sessionstate') as sessionstatus:
if sessionstatus.status == 200:
return session
else:
params = {'value': '4a8352b6a6ecdb4106b2439aa9e8638a0cdbb16ff3568616f4ccb788d92538fe',
'value1': '4701754001718'}
session.get('http://192.168.1.99:8888/logas',
params=params)
return


async def send_comand(self, url: str):
mysession = await self._getLoginSession()
async with mysession as session:
async with session.get(url) as resp:
print(resp.status)
print(await resp.text())
return True



#test the class method
async def main():
md = MordomusConnect()
await md.send_comand('http://192.168.1.99:8888/json?sessionstate')

asyncio.run(main())

这是回溯

File "C:\Users\Jorge Torres\Python\md.py", line 43, in <module>
asyncio.run(main())
File "C:\Users\Jorge Torres\AppData\Local\Programs\Python\Python37-32\Lib\asyncio\runners.py", line 43, in run
return loop.run_until_complete(main)
File "C:\Users\Jorge Torres\AppData\Local\Programs\Python\Python37-32\Lib\asyncio\base_events.py", line 579, in run_until_complete
return future.result()
File "C:\Users\Jorge Torres\Python\md.py", line 41, in main
await md.send_comand('http://192.168.1.99:8888/json?sessionstate')
File "C:\Users\Jorge Torres\Python\md.py", line 31, in send_comand
async with session.get(url) as resp:
File "C:\Users\Jorge Torres\AppData\Local\Programs\Python\Python37-32\Lib\site-packages\aiohttp\client.py", line 1013, in __aenter__
self._resp = await self._coro
File "C:\Users\Jorge Torres\AppData\Local\Programs\Python\Python37-32\Lib\site-packages\aiohttp\client.py", line 358, in _request
raise RuntimeError('Session is closed')

builtins.RuntimeError: Session is closed

谢谢

最佳答案

原因

这是因为这条线:

async with aiohttp.ClientSession(cookie_jar=jar) as session:

当您使用 with 语句时,session 会在底层 block 完成后立即关闭。稍后当您尝试使用相同的 session 时

mysession = await self._getLoginSession()
async with mysession as session:

mysession 已经关闭,无法使用。

解决方案

修复相当简单。而不是

async with aiohttp.ClientSession(cookie_jar=jar) as session

session = aiohttp.ClientSession(cookie_jar=jar)

在这个 with 语句执行后处理这个 session 的关闭:

async with mysession as session:

关于python - 运行时错误 : Session is closed when using aiohttp session,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61043291/

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