-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathadvanced_example.py
More file actions
47 lines (35 loc) · 1.04 KB
/
advanced_example.py
File metadata and controls
47 lines (35 loc) · 1.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# Start example
import asyncio
from contextlib import asynccontextmanager
from typing import AsyncGenerator
import uvicorn
from fastapi import FastAPI
from fastapi.responses import JSONResponse
from psqlpy import PSQLPool
db_pool = PSQLPool(
dsn="postgres://postgres:postgres@localhost:5432/postgres",
max_db_pool_size=2,
)
@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
"""Startup database connection pool and close it on shutdown."""
app.state.db_pool = db_pool
yield
await db_pool.close()
app = FastAPI(lifespan=lifespan)
async def some_long_func() -> None:
# Some very long execution.
await asyncio.sleep(10)
@app.get("/")
async def pg_pool_example() -> JSONResponse:
await some_long_func()
db_connection = await db_pool.connection()
query_result = await db_connection.execute(
"SELECT * FROM users",
)
return JSONResponse(content=query_result.result())
if __name__ == "__main__":
uvicorn.run(
"advanced_example:app",
port=8001,
)