{"record":{"id":"37192122b7632643","repo":"aio-libs/aiohttp","slug":"session-is-closed","errorCode":null,"errorMessage":"Session is closed","messagePattern":"Session is closed","errorType":"exception","errorClass":"RuntimeError","httpStatus":null,"severity":"error","filePath":"aiohttp/client.py","lineNumber":503,"sourceCode":"        proxy: StrOrURL | None = None,\n        timeout: ClientTimeout | _SENTINEL | None = sentinel,\n        ssl: SSLContext | bool | Fingerprint | _SENTINEL = sentinel,\n        server_hostname: str | None = None,\n        proxy_headers: LooseHeaders | None = None,\n        trace_request_ctx: object = None,\n        read_bufsize: int | None = None,\n        auto_decompress: bool | None = None,\n        max_line_size: int | None = None,\n        max_field_size: int | None = None,\n        max_headers: int | None = None,\n        middlewares: Sequence[ClientMiddlewareType] | None = None,\n    ) -> ClientResponse:\n        # NOTE: timeout clamps existing connect and read timeouts.  We cannot\n        # set the default to None because we need to detect if the user wants\n        # to use the existing timeouts by setting timeout to None.\n\n        if self.closed:\n            raise RuntimeError(\"Session is closed\")\n\n        method = method.upper()\n\n        if ssl is sentinel:\n            ssl = self._default_ssl\n        if not isinstance(ssl, SSL_ALLOWED_TYPES):\n            raise TypeError(\n                \"ssl should be SSLContext, Fingerprint, or bool, \"\n                f\"got {ssl!r} instead.\"\n            )\n\n        if data is not None and json is not None:\n            raise ValueError(\n                \"data and json parameters can not be used at the same time\"\n            )\n        elif json is not None:\n            if self._json_serialize_bytes is not None:\n                data = payload.JsonBytesPayload(json, dumps=self._json_serialize_bytes)","sourceCodeStart":485,"sourceCodeEnd":521,"githubUrl":"https://github.com/aio-libs/aiohttp/blob/d041d4d0fd48c3f0832084d33be16cf1c4835f85/aiohttp/client.py#L485-L521","documentation":"Raised at the top of ClientSession.request (and therefore every .get/.post/...) when self.closed is True. Once close() has run (or the async with block has exited) the session's connector is gone and no further requests can be made.","triggerScenarios":"Calling session.get(...) after await session.close(). Calling a request method on a session that was used as async with session: ... and the block has exited. Calling from a task that outlived the session's owner task.","commonSituations":"Reusing a module-level session after shutdown. Holding a session reference in a long-lived object whose cleanup ran. Test fixtures closing the session in teardown while an assertion still issues a request.","solutions":["Create a new session for the new work: async with ClientSession() as s: ....","Structure ownership so the session's lifetime encloses every task that uses it.","Track closed state yourself and skip / reopen before calling request methods."],"exampleFix":"// before\nsession = ClientSession()\nawait session.close()\nawait session.get('http://x')  # raises\n// after\nasync with ClientSession() as session:\n    await session.get('http://x')\n# open a fresh session for further work","handlingStrategy":"try-catch","validationCode":"async def safe_get(session, url):\n    if session.closed:\n        raise RuntimeError('session closed; open a new one')\n    return await session.get(url)","typeGuard":"def is_open(session) -> bool:\n    return not session.closed","tryCatchPattern":"try:\n    resp = await session.get(url)\nexcept RuntimeError as e:\n    if 'Session is closed' in str(e):\n        async with ClientSession() as new_session:\n            resp = await new_session.get(url)\n    else:\n        raise","preventionTips":["Scope session lifetime with 'async with ClientSession() as s:'.","Track session ownership in one place and never use after close().","Add a liveness check helper for long-lived background tasks."],"tags":["lifecycle","client-session","resource-management"],"backgroundTag":null,"analyzedSha":"d041d4d0fd48c3f0832084d33be16cf1c4835f85","analyzedAt":"2026-08-11T20:44:15.550Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}