Tracciare i risultati e gestire gli errori
Controlli lo stato del task e riprovi in caso di errore.
Tracciare i risultati e gestire gli errori è una lezione Flask Academy gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Flask Academy, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Flask Academy include 4 lezioni in totale.
Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.
The AsyncResult Handle
When you enqueue a task you get an AsyncResult. Save its id so you can check on the job from any later request.
job = add.delay(2, 3)
ticket = job.idCheck the State
Each job has a state like PENDING, STARTED, SUCCESS, or FAILURE. You read it to know whether the work is done.
res = add.AsyncResult(ticket)
print(res.state)Read the Result
Once a job succeeds, its return value is stored in the backend. Access it through result on the AsyncResult.
if res.ready():
print(res.result)Poll, Do Not Block
In a web view, never call get() and wait. Instead return the task id and let the client poll a status endpoint.
A Status Endpoint
Expose a route that takes a task id and returns its state and result. The frontend hits it every few seconds until done.
@app.get("/status/<tid>")
def status(tid):
r = add.AsyncResult(tid)
return {"state": r.state}Failures Happen
External calls time out and code raises errors. When a task throws, Celery marks it FAILURE and records the exception.
Automatic Retries
Make a task retry itself on transient errors. Set max_retries and a delay so flaky calls get a few more chances.
@celery.task(bind=True, max_retries=3)
def fetch(self):
...Back Off Between Tries
Retrying instantly can hammer a struggling service. Use a growing delay, called backoff, so each retry waits longer.
Trigger a Retry
Inside the task, catch the error and call self.retry. Celery re-queues the job and counts it against max_retries.
try:
do_work()
except Exception as e:
self.retry(exc=e, countdown=5)Set Time Limits
A stuck task should not run forever. A time limit kills tasks that overrun, freeing the worker for other jobs.
Result Expiry
Stored results take space. Celery expires old results after a while, so design clients to fetch them promptly. ⏱️
Quick Check
Your task calls a flaky external API.
Recap
Track jobs by id, poll a status endpoint for state and result, and handle failures with retries, backoff, and time limits. ✅
Domande Frequenti
La lezione «Tracciare i risultati e gestire gli errori» è gratuita?
Sì — il testo completo di «Tracciare i risultati e gestire gli errori» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Flask Academy, passa a CoddyKit PRO. Il corso Flask Academy include 4 lezioni in totale.
Cosa imparerò in «Tracciare i risultati e gestire gli errori»?
Controlli lo stato del task e riprovi in caso di errore. Eserciti Flask Academy con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.
Ho bisogno di esperienza per iniziare Flask Academy?
Non è richiesta alcuna esperienza precedente. Flask Academy su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.
Quanto tempo richiede la lezione «Tracciare i risultati e gestire gli errori»?
La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.
Posso scrivere ed eseguire codice in questa lezione Flask Academy?
Sì. Ogni lezione Flask Academy include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.
Tutte le lezioni di questo corso
- Perché spostare il lavoro fuori dalla richiesta
- Collegare Celery alla app factory
- Definire e chiamare un task
- Tracciare i risultati e gestire gli errori