我正在尝试使用asyncio构建一个简单的类,但我遇到了错误
builtins.RuntimeError: Session is closed
我认为这不是与服务器有关,而是与我的代码架构有关。
代码如下:
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谢谢
发布于 2020-04-05 22:31:32
原因
这是因为下面这行代码:
async with aiohttp.ClientSession(cookie_jar=jar) as session:使用with语句时,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语句后处理的:
async with mysession as session:https://stackoverflow.com/questions/61043291
复制相似问题