Repository navigation
Expand file tree
/
Copy pathfastapi_usage.py
More file actions
77 lines (62 loc) · 2.2 KB
/
Copy pathfastapi_usage.py
File metadata and controls
77 lines (62 loc) · 2.2 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import json
from contextlib import asynccontextmanager
from typing import AsyncGenerator
import asyncpg
from fastapi import Depends, FastAPI, Request, Response
from pgqueuer.db import AsyncpgPoolDriver
from pgqueuer.queries import Queries
def get_pgq_queries(request: Request) -> Queries:
"""Retrieve Queries instance from FastAPI app context."""
pgq_queries = request.app.extra["pgq_queries"]
assert isinstance(pgq_queries, Queries)
return pgq_queries
def create_app() -> FastAPI:
"""
Create and configure a FastAPI app with a lifespan context manager
to handle database connection.
"""
@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
"""Manage async database connection throughout the app's lifespan."""
async with asyncpg.create_pool() as pool:
app.extra["pgq_queries"] = Queries(AsyncpgPoolDriver(pool))
yield
app = FastAPI(lifespan=lifespan)
@app.get("/reset_password_email")
async def reset_password_email(
user_name: str,
queries: Queries = Depends(get_pgq_queries),
) -> Response:
"""Enqueue a job to reset a user's password, identified by user_name."""
await queries.enqueue(
"reset_email_by_user_name",
payload=json.dumps({"user_name": user_name}).encode(),
)
return Response(status_code=201)
@app.post("/enqueue")
async def enqueue_job(
entrypoint: str,
payload: str,
priority: int = 0,
queries: Queries = Depends(get_pgq_queries),
) -> dict[str, object]:
ids = await queries.enqueue(entrypoint, payload.encode(), priority)
return {"job_ids": ids}
@app.get("/queue-size")
async def get_queue_size(
queries: Queries = Depends(get_pgq_queries),
) -> list[dict[str, object]]:
stats = await queries.queue_size()
return [
{
"entrypoint": s.entrypoint,
"priority": s.priority,
"status": s.status,
"count": s.count,
}
for s in stats
]
return app
if __name__ == "__main__":
import uvicorn
uvicorn.run(create_app())