11import logging
22import multiprocessing
33import os
4+ from contextlib import asynccontextmanager
45from operator import attrgetter
56from random import randint , sample
67
@@ -42,6 +43,7 @@ class Fortune(Base):
4243ADDITIONAL_FORTUNE = Fortune (
4344 id = 0 , message = "Additional fortune added at request time."
4445)
46+ MAX_POOL_SIZE = 1000 // multiprocessing .cpu_count ()
4547
4648sort_fortunes_key = attrgetter ("message" )
4749
@@ -50,8 +52,6 @@ class Fortune(Base):
5052)
5153templates = Jinja2Templates (directory = template_path )
5254
53- app = FastAPI ()
54-
5555
5656async def setup_database ():
5757 dsn = "postgresql+asyncpg://%s:%s@tfb-database:5432/hello_world" % (
@@ -62,13 +62,26 @@ async def setup_database():
6262 engine = create_async_engine (
6363 dsn ,
6464 future = True ,
65+ pool_size = MAX_POOL_SIZE ,
6566 connect_args = {
6667 "ssl" : False # NEEDED FOR NGINX-UNIT OTHERWISE IT FAILS
6768 },
6869 )
6970 return sessionmaker (engine , class_ = AsyncSession )
7071
7172
73+ @asynccontextmanager
74+ async def lifespan (app : FastAPI ):
75+ # Setup the database connection pool
76+ app .state .db_session = await setup_database ()
77+ yield
78+ # Close the database connection pool
79+ await app .state .db_session .close ()
80+
81+
82+ app = FastAPI (lifespan = lifespan )
83+
84+
7285def get_num_queries (queries ):
7386 try :
7487 query_count = int (queries )
@@ -82,16 +95,6 @@ def get_num_queries(queries):
8295 return query_count
8396
8497
85- @app .on_event ("startup" )
86- async def startup_event ():
87- app .state .db_session = await setup_database ()
88-
89-
90- @app .on_event ("shutdown" )
91- async def shutdown_event ():
92- await app .state .db_session .close ()
93-
94-
9598@app .get ("/json" )
9699async def json_serialization ():
97100 return UJSONResponse ({"message" : "Hello, world!" })
0 commit comments