Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Setup a global aiohttp.ClientSession instance
  • Loading branch information
james-gray committed Apr 2, 2020
commit 8b55c1637e4c29647168969e2f505fb6180cb9a7
1 change: 1 addition & 0 deletions Pipfile
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ pytest = "*"
pytest-cov = "*"

[packages]
aiohttp = "*"
cachetools = "*"
fastapi = "*"
gunicorn = "*"
Expand Down
3 changes: 3 additions & 0 deletions app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
from .data import data_source
from .router.v1 import V1
from .router.v2 import V2
from .utils.httputils import setup_client_session, teardown_client_session

# ############
# FastAPI App
Expand All @@ -28,6 +29,8 @@
version="2.0.1",
docs_url="/",
redoc_url="/docs",
on_startup=[setup_client_session],
on_shutdown=[teardown_client_session],
)

# #####################
Expand Down
30 changes: 30 additions & 0 deletions app/utils/httputils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import logging

from aiohttp import ClientSession


# Singleton aiohttp.ClientSession instance.
client_session: ClientSession


LOGGER = logging.getLogger(__name__)


async def setup_client_session():
"""Set up the application-global aiohttp.ClientSession instance.

aiohttp recommends that only one ClientSession exist for the lifetime of an application.
See: https://docs.aiohttp.org/en/stable/client_quickstart.html#make-a-request

"""
global client_session
LOGGER.info("Setting up global aiohttp.ClientSession.")
client_session = ClientSession()


async def teardown_client_session():
"""Close the application-global aiohttp.ClientSession.
"""
global client_session
LOGGER.info("Closing global aiohttp.ClientSession.")
await client_session.close()
Empty file added tests/test_httputils.py
Empty file.