Jorge Torres
Jorge Torres

Reputation: 73

RuntimeError: Session is closed when using aiohttp session

I'm trying to build a simple class with asyncio but I have the error

builtins.RuntimeError: Session is closed

I think this is not to do with server but with my code architecture.

Here is the code:

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())      

And this is the traceback

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

Thank you

Upvotes: 5

Views: 11896

Answers (1)

Denis-Alexandru Nica
Denis-Alexandru Nica

Reputation: 316

Reason

This happens because of this line:

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

When you use the with statement, session closes as soon as the underlying block finishes. Later on when you try to use the same session

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

mysession is already closed and can not be used.

Solution

The fix is rather simple. Instead of

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

do

session = aiohttp.ClientSession(cookie_jar=jar)

The closure of this session is handled after this with statement is executed:

async with mysession as session:

Upvotes: 11

Related Questions