Process webhooks in the background
Browse files(not tested but "should work")
When receiving a webhook, you should respond in less than 30s. If process takes longer than that, it's best to run it in a background task. You can use `fastapi.BackgroundTasks` for that. When you receive a webhook, you quickly check if it's a valid payload or not. If accepted, you schedule a task and return HTTP 202 (Accepted). Otherwise, you simply return a HTTP 200.
Inspired by https://huggingface.co/spaces/Wauplin/gradio-space-ci/blob/main/src/gradio_space_ci/webhook.py#L241.
app.py
CHANGED
|
@@ -1,6 +1,7 @@
|
|
| 1 |
import os
|
| 2 |
from pathlib import Path
|
| 3 |
|
|
|
|
| 4 |
import gradio as gr
|
| 5 |
from huggingface_hub import WebhookPayload, WebhooksServer
|
| 6 |
|
|
@@ -72,12 +73,15 @@ app = WebhooksServer(ui=ui.queue(), webhook_secret=WEBHOOK_SECRET)
|
|
| 72 |
|
| 73 |
|
| 74 |
@app.add_webhook("/dataset_repo")
|
| 75 |
-
async def community(payload: WebhookPayload):
|
| 76 |
-
if payload.event.scope.startswith("repo"):
|
| 77 |
-
|
| 78 |
-
else:
|
| 79 |
-
return
|
| 80 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 81 |
logger.info(f"Loading new dataset...")
|
| 82 |
dataset, original_dataset = load_datasets()
|
| 83 |
logger.info(f"Loaded new dataset")
|
|
|
|
| 1 |
import os
|
| 2 |
from pathlib import Path
|
| 3 |
|
| 4 |
+
from fastapi import BackgroundTasks, Response, status
|
| 5 |
import gradio as gr
|
| 6 |
from huggingface_hub import WebhookPayload, WebhooksServer
|
| 7 |
|
|
|
|
| 73 |
|
| 74 |
|
| 75 |
@app.add_webhook("/dataset_repo")
|
| 76 |
+
async def community(payload: WebhookPayload, task_queue: BackgroundTasks):
|
| 77 |
+
if not payload.event.scope.startswith("repo"):
|
| 78 |
+
return Response("No task scheduled", status_code=status.HTTP_200_OK)
|
|
|
|
|
|
|
| 79 |
|
| 80 |
+
logger.info(f"Webhook received from {payload.repo.name} indicating a repo {payload.event.action}")
|
| 81 |
+
task_queue.add_task(_process_webhook, payload=payload)
|
| 82 |
+
return Response("Task scheduled.", status_code=status.HTTP_202_ACCEPTED)
|
| 83 |
+
|
| 84 |
+
def _process_webhook(payload: WebhookPayload):
|
| 85 |
logger.info(f"Loading new dataset...")
|
| 86 |
dataset, original_dataset = load_datasets()
|
| 87 |
logger.info(f"Loaded new dataset")
|