RuntimeError:使用aiohttp会话时,会话已关闭

问题描述 投票:-1回答:1

我正在尝试使用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

谢谢

python
1个回答
0
投票

原因

由于此行而发生这种情况:

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:
© www.soinside.com 2019 - 2024. All rights reserved.