我试图用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
多谢各位
理由
这是因为这一行:
使用
with
语句时,底层块一完成session
就会关闭。稍后当您尝试使用同一会话时mysession
已关闭,无法使用解决方案
解决办法相当简单。而不是
做
执行此
with
语句后,将处理此会话的关闭:相关问题 更多 >
编程相关推荐