如何在 Django 后台定期重复一个函数直到成功?
How to periodically repeat a function until success in background in Django?
我正在处理一个 Django 项目。我想向外部服务器发出 http 请求。但有时外部服务器returns 5xx。我想在后台重试请求,直到 returns 200。我该怎么做?
这是我想做的伪代码:
response = requests.post(url, json=param)
if response.status_code == 200:
# do something
elif response.status_code >= 500:
# schedule task to retry every 30 seconds until success
像这样的东西就可以了:
import time
RETRY_TIME = 30
referenceTime = time.time()
while(1):
currentTime = time.time()
dt = currentTime - referenceTime
if(dt > RETRY_TIME):
referenceTime += RETRY_TIME
print("hello")
# do your request here
if(response.status_code == 200):
break
由于下载任务不是同步任务,您需要一个任务队列来归档您的目标。
Celery 是分布式任务队列,可以轻松与 Django 集成。
您可以这样创建下载任务:
from proj.celery import app
@app.task(bind=True)
def download(self, url, param):
response = requests.post(url, json=param)
if response.status_code == 200:
# do something
...
elif response.status_code >= 500:
# schedule task to retry every 30 seconds until success
raise self.retry(countdown=30)
调用你的任务:
download.apply_async(('YOUR DOWNLOAD URL', None))
关于芹菜的参考资料:
我正在处理一个 Django 项目。我想向外部服务器发出 http 请求。但有时外部服务器returns 5xx。我想在后台重试请求,直到 returns 200。我该怎么做? 这是我想做的伪代码:
response = requests.post(url, json=param)
if response.status_code == 200:
# do something
elif response.status_code >= 500:
# schedule task to retry every 30 seconds until success
像这样的东西就可以了:
import time
RETRY_TIME = 30
referenceTime = time.time()
while(1):
currentTime = time.time()
dt = currentTime - referenceTime
if(dt > RETRY_TIME):
referenceTime += RETRY_TIME
print("hello")
# do your request here
if(response.status_code == 200):
break
由于下载任务不是同步任务,您需要一个任务队列来归档您的目标。
Celery 是分布式任务队列,可以轻松与 Django 集成。
您可以这样创建下载任务:
from proj.celery import app
@app.task(bind=True)
def download(self, url, param):
response = requests.post(url, json=param)
if response.status_code == 200:
# do something
...
elif response.status_code >= 500:
# schedule task to retry every 30 seconds until success
raise self.retry(countdown=30)
调用你的任务:
download.apply_async(('YOUR DOWNLOAD URL', None))
关于芹菜的参考资料: