Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
65 lines (46 loc) · 1.81 KB
/
Copy pathmain.py
File metadata and controls
65 lines (46 loc) · 1.81 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
# Standard Library Imports
import logging
import os
# Third Party Imports
from fastapi import FastAPI
from fastapi.routing import APIRouter
from pydantic import BaseModel
# Imports from this repository
from fastapi_gcp_tasks import DelayedRouteBuilder, as_delayed_task
from fastapi_gcp_tasks.utils import emulator_client, queue_path
# set env var IS_LOCAL=false for your deployment environment
IS_LOCAL = os.getenv("IS_LOCAL", "true").lower() == "true"
client = None
if IS_LOCAL:
client = emulator_client()
DelayedRoute = DelayedRouteBuilder(
client=client,
# Externally reachable URL prefix where the task routes are hosted
callback_base_url=os.getenv("TASK_LISTENER_BASE_URL", default="http://localhost:8000"),
# Full queue path to which we'll send tasks.
# Edit values below to match your project
queue_path=queue_path(
project=os.getenv("TASK_PROJECT_ID", default="gcp-project-id"),
location=os.getenv("TASK_LOCATION", default="us-central1"),
queue=os.getenv("TASK_QUEUE", default="test-queue"),
),
)
delayed_router = APIRouter(route_class=DelayedRoute, prefix="/delayed")
logger = logging.getLogger("uvicorn")
class Payload(BaseModel):
"""Basic payload from the api."""
message: str
@delayed_router.post("/hello")
@as_delayed_task
async def hello(
p: Payload = Payload(message="Default"),
) -> None:
logger.warning(f"Hello task ran with payload: {p.message}")
app = FastAPI()
# A plain `def`: the sync `.delay()` makes a blocking gRPC call, so FastAPI runs this in its
# threadpool instead of stalling the event loop. See examples/full for `await .delay()`.
@app.get("/trigger")
def trigger() -> dict[str, str]:
hello.delay(p=Payload(message="Triggered task"))
return {"message": "Basic hello task triggered"}
app.include_router(delayed_router)