跟踪结果并处理失败
轮询任务状态并在出错时重试
跟踪结果并处理失败 是 CoddyKit 上的免费 Flask Academy 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Flask Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Flask Academy 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
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. ✅
用 AI 导师学习 Python — 免费
在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。
- 课程
- 30
- 课程
- 120
常见问题解答
「跟踪结果并处理失败」课时是免费的吗?
是的 — 「跟踪结果并处理失败」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Flask Academy 课程的其余内容,请升级到 CoddyKit PRO。 Flask Academy 课程共包含 4 节课。
「跟踪结果并处理失败」这节课中我会学到什么?
轮询任务状态并在出错时重试 你通过在浏览器中直接运行的动手代码来练习 Flask Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Flask Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Flask Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「跟踪结果并处理失败」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Flask Academy 课中编写并运行代码吗?
能。每节 Flask Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 为什么要将工作移出请求
- 将 Celery 接入应用工厂
- 定义并调用任务
- 跟踪结果并处理失败