Skip to content

Commit 8b55c16

Browse files
committed
Setup a global aiohttp.ClientSession instance
1 parent d3ac880 commit 8b55c16

File tree

4 files changed

+34
-0
lines changed

4 files changed

+34
-0
lines changed

Pipfile

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ pytest = "*"
1414
pytest-cov = "*"
1515

1616
[packages]
17+
aiohttp = "*"
1718
cachetools = "*"
1819
fastapi = "*"
1920
gunicorn = "*"

app/main.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
from .data import data_source
1414
from .router.v1 import V1
1515
from .router.v2 import V2
16+
from .utils.httputils import setup_client_session, teardown_client_session
1617

1718
# ############
1819
# FastAPI App
@@ -28,6 +29,8 @@
2829
version="2.0.1",
2930
docs_url="/",
3031
redoc_url="/docs",
32+
on_startup=[setup_client_session],
33+
on_shutdown=[teardown_client_session],
3134
)
3235

3336
# #####################

app/utils/httputils.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import logging
2+
3+
from aiohttp import ClientSession
4+
5+
6+
# Singleton aiohttp.ClientSession instance.
7+
client_session: ClientSession
8+
9+
10+
LOGGER = logging.getLogger(__name__)
11+
12+
13+
async def setup_client_session():
14+
"""Set up the application-global aiohttp.ClientSession instance.
15+
16+
aiohttp recommends that only one ClientSession exist for the lifetime of an application.
17+
See: https://docs.aiohttp.org/en/stable/client_quickstart.html#make-a-request
18+
19+
"""
20+
global client_session
21+
LOGGER.info("Setting up global aiohttp.ClientSession.")
22+
client_session = ClientSession()
23+
24+
25+
async def teardown_client_session():
26+
"""Close the application-global aiohttp.ClientSession.
27+
"""
28+
global client_session
29+
LOGGER.info("Closing global aiohttp.ClientSession.")
30+
await client_session.close()

tests/test_httputils.py

Whitespace-only changes.

0 commit comments

Comments
 (0)