|
@@ -1,6 +1,7 @@
|
|
import logging
|
|
import logging
|
|
import multiprocessing
|
|
import multiprocessing
|
|
import os
|
|
import os
|
|
|
|
+from contextlib import asynccontextmanager
|
|
from operator import attrgetter
|
|
from operator import attrgetter
|
|
from random import randint, sample
|
|
from random import randint, sample
|
|
|
|
|
|
@@ -42,6 +43,7 @@ sa_fortunes = Fortune.__table__
|
|
ADDITIONAL_FORTUNE = Fortune(
|
|
ADDITIONAL_FORTUNE = Fortune(
|
|
id=0, message="Additional fortune added at request time."
|
|
id=0, message="Additional fortune added at request time."
|
|
)
|
|
)
|
|
|
|
+MAX_POOL_SIZE = 1000//multiprocessing.cpu_count()
|
|
|
|
|
|
sort_fortunes_key = attrgetter("message")
|
|
sort_fortunes_key = attrgetter("message")
|
|
|
|
|
|
@@ -50,8 +52,6 @@ template_path = os.path.join(
|
|
)
|
|
)
|
|
templates = Jinja2Templates(directory=template_path)
|
|
templates = Jinja2Templates(directory=template_path)
|
|
|
|
|
|
-app = FastAPI()
|
|
|
|
-
|
|
|
|
|
|
|
|
async def setup_database():
|
|
async def setup_database():
|
|
dsn = "postgresql+asyncpg://%s:%s@tfb-database:5432/hello_world" % (
|
|
dsn = "postgresql+asyncpg://%s:%s@tfb-database:5432/hello_world" % (
|
|
@@ -62,6 +62,7 @@ async def setup_database():
|
|
engine = create_async_engine(
|
|
engine = create_async_engine(
|
|
dsn,
|
|
dsn,
|
|
future=True,
|
|
future=True,
|
|
|
|
+ pool_size=MAX_POOL_SIZE,
|
|
connect_args={
|
|
connect_args={
|
|
"ssl": False # NEEDED FOR NGINX-UNIT OTHERWISE IT FAILS
|
|
"ssl": False # NEEDED FOR NGINX-UNIT OTHERWISE IT FAILS
|
|
},
|
|
},
|
|
@@ -69,6 +70,18 @@ async def setup_database():
|
|
return sessionmaker(engine, class_=AsyncSession)
|
|
return sessionmaker(engine, class_=AsyncSession)
|
|
|
|
|
|
|
|
|
|
|
|
+@asynccontextmanager
|
|
|
|
+async def lifespan(app: FastAPI):
|
|
|
|
+ # Setup the database connection pool
|
|
|
|
+ app.state.db_session = await setup_database()
|
|
|
|
+ yield
|
|
|
|
+ # Close the database connection pool
|
|
|
|
+ await app.state.db_session.close()
|
|
|
|
+
|
|
|
|
+
|
|
|
|
+app = FastAPI(lifespan=lifespan)
|
|
|
|
+
|
|
|
|
+
|
|
def get_num_queries(queries):
|
|
def get_num_queries(queries):
|
|
try:
|
|
try:
|
|
query_count = int(queries)
|
|
query_count = int(queries)
|
|
@@ -82,16 +95,6 @@ def get_num_queries(queries):
|
|
return query_count
|
|
return query_count
|
|
|
|
|
|
|
|
|
|
[email protected]_event("startup")
|
|
|
|
-async def startup_event():
|
|
|
|
- app.state.db_session = await setup_database()
|
|
|
|
-
|
|
|
|
-
|
|
|
|
[email protected]_event("shutdown")
|
|
|
|
-async def shutdown_event():
|
|
|
|
- await app.state.db_session.close()
|
|
|
|
-
|
|
|
|
-
|
|
|
|
@app.get("/json")
|
|
@app.get("/json")
|
|
async def json_serialization():
|
|
async def json_serialization():
|
|
return UJSONResponse({"message": "Hello, world!"})
|
|
return UJSONResponse({"message": "Hello, world!"})
|