我正在研究Django项目。我想向外部服务器发出http请求。但是有时外部服务器返回5xx。我想在后台重试请求,直到返回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))
关于芹菜的参考: