Skip to content

Commit 2d1e665

Browse files
committed
Added some examples for AioHTTP and FastAPI
1 parent cd166be commit 2d1e665

File tree

3 files changed

+138
-0
lines changed

3 files changed

+138
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
# Start example
2+
import asyncio
3+
from typing import cast
4+
from aiohttp import web
5+
from psqlpy import PSQLPool
6+
7+
8+
async def start_db_pool(app: web.Application) -> None:
9+
"""Initialize database connection pool."""
10+
db_pool = PSQLPool(
11+
dsn="postgres://postgres:postgres@localhost:5432/postgres",
12+
max_db_pool_size=2,
13+
)
14+
await db_pool.startup()
15+
16+
app["db_pool"] = db_pool
17+
18+
19+
async def stop_db_pool(app: web.Application) -> None:
20+
"""Close database connection pool."""
21+
db_pool = cast(PSQLPool, app.db_pool)
22+
await db_pool.close()
23+
24+
25+
async def pg_pool_example(request: web.Request):
26+
db_pool = cast(PSQLPool, request.app["db_pool"])
27+
connection = await db_pool.connection()
28+
await asyncio.sleep(10)
29+
query_result = await connection.execute(
30+
"SELECT * FROM users",
31+
)
32+
dict_result = query_result.result()
33+
return web.json_response(
34+
data=dict_result,
35+
)
36+
37+
38+
application = web.Application()
39+
application.on_startup.append(start_db_pool)
40+
application.add_routes([web.get('/', pg_pool_example)])
41+
42+
43+
if __name__ == "__main__":
44+
web.run_app(application)
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
# Start example
2+
import asyncio
3+
from contextlib import asynccontextmanager
4+
from typing import Annotated, AsyncGenerator, cast
5+
from fastapi import Depends, FastAPI, Request
6+
from fastapi.responses import JSONResponse
7+
from psqlpy import PSQLPool, Connection
8+
import uvicorn
9+
10+
11+
db_pool = PSQLPool(
12+
dsn="postgres://postgres:postgres@localhost:5432/postgres",
13+
max_db_pool_size=2,
14+
)
15+
16+
17+
@asynccontextmanager
18+
async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
19+
"""Startup database connection pool and close it on shutdown."""
20+
await db_pool.startup()
21+
app.state.db_pool = db_pool
22+
yield
23+
await db_pool.close()
24+
25+
26+
app = FastAPI(lifespan=lifespan)
27+
28+
29+
async def some_long_func() -> None:
30+
# Some very long execution.
31+
print("Executing...")
32+
await asyncio.sleep(10)
33+
print("Done.")
34+
35+
36+
@app.get("/")
37+
async def pg_pool_example():
38+
await some_long_func()
39+
db_connection = await db_pool.connection()
40+
query_result = await db_connection.execute(
41+
"SELECT * FROM users",
42+
)
43+
return JSONResponse(content=query_result.result())
44+
45+
46+
if __name__ == "__main__":
47+
uvicorn.run(
48+
"advanced_example:app",
49+
port=8001,
50+
)
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
# Start example
2+
from contextlib import asynccontextmanager
3+
from typing import Annotated, AsyncGenerator, cast
4+
from fastapi import Depends, FastAPI, Request
5+
from fastapi.responses import JSONResponse
6+
from psqlpy import PSQLPool, Connection
7+
import uvicorn
8+
9+
10+
@asynccontextmanager
11+
async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
12+
"""Startup database connection pool and close it on shutdown."""
13+
db_pool = PSQLPool(
14+
dsn="postgres://postgres:postgres@localhost:5432/postgres",
15+
max_db_pool_size=2,
16+
)
17+
await db_pool.startup()
18+
app.state.db_pool = db_pool
19+
yield
20+
await db_pool.close()
21+
22+
23+
app = FastAPI(lifespan=lifespan)
24+
25+
26+
async def db_connection(request: Request) -> Connection:
27+
"""Retrieve new connection from connection pool and return it."""
28+
return await (cast(PSQLPool, request.app.state.db_pool)).connection()
29+
30+
31+
@app.get("/")
32+
async def pg_pool_example(
33+
db_connection: Annotated[Connection, Depends(db_connection)],
34+
):
35+
query_result = await db_connection.execute(
36+
"SELECT * FROM users",
37+
)
38+
return JSONResponse(content=query_result.result())
39+
40+
41+
if __name__ == "__main__":
42+
uvicorn.run(
43+
"start_example:app",
44+
)

0 commit comments

Comments
 (0)