Browse Source

[FASTAPI] Bump fastapi to 0.93.0 (#7991)

Introduce lifespan events
Micael Malta 2 năm trước cách đây
mục cha
commit
08b64d372c

+ 14 - 7
frameworks/Python/fastapi/app.py

@@ -1,3 +1,6 @@
+import multiprocessing
+from contextlib import asynccontextmanager
+
 import asyncpg
 import asyncpg
 import os
 import os
 from fastapi import FastAPI, Request
 from fastapi import FastAPI, Request
@@ -15,6 +18,8 @@ from random import randint, sample
 READ_ROW_SQL = 'SELECT "id", "randomnumber" FROM "world" WHERE id = $1'
 READ_ROW_SQL = 'SELECT "id", "randomnumber" FROM "world" WHERE id = $1'
 WRITE_ROW_SQL = 'UPDATE "world" SET "randomnumber"=$1 WHERE id=$2'
 WRITE_ROW_SQL = 'UPDATE "world" SET "randomnumber"=$1 WHERE id=$2'
 ADDITIONAL_ROW = [0, "Additional fortune added at request time."]
 ADDITIONAL_ROW = [0, "Additional fortune added at request time."]
+MAX_POOL_SIZE = 1000//multiprocessing.cpu_count()
+MIN_POOL_SIZE = max(int(MAX_POOL_SIZE / 2), 1)
 
 
 
 
 def get_num_queries(queries):
 def get_num_queries(queries):
@@ -34,8 +39,6 @@ connection_pool = None
 
 
 templates = Jinja2Templates(directory="templates")
 templates = Jinja2Templates(directory="templates")
 
 
-app = FastAPI()
-
 
 
 async def setup_database():
 async def setup_database():
     return await asyncpg.create_pool(
     return await asyncpg.create_pool(
@@ -44,17 +47,21 @@ async def setup_database():
         database="hello_world",
         database="hello_world",
         host="tfb-database",
         host="tfb-database",
         port=5432,
         port=5432,
+        min_size=MIN_POOL_SIZE,
+        max_size=MAX_POOL_SIZE,
     )
     )
 
 
 
 
[email protected]_event("startup")
-async def startup_event():
+@asynccontextmanager
+async def lifespan(app: FastAPI):
+    # Setup the database connection pool
     app.state.connection_pool = await setup_database()
     app.state.connection_pool = await setup_database()
+    yield
+    # Close the database connection pool
+    await app.state.connection_pool.close()
 
 
 
 
[email protected]_event("shutdown")
-async def shutdown_event():
-    await app.state.connection_pool.close()
+app = FastAPI(lifespan=lifespan)
 
 
 
 
 @app.get("/json")
 @app.get("/json")

+ 15 - 12
frameworks/Python/fastapi/app_orm.py

@@ -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!"})

+ 1 - 1
frameworks/Python/fastapi/requirements.txt

@@ -1,4 +1,4 @@
 asyncpg==0.27.0
 asyncpg==0.27.0
-fastapi==0.92.0
+fastapi==0.93.0
 Jinja2==3.1.2
 Jinja2==3.1.2
 ujson==5.7.0
 ujson==5.7.0