我正在寻找一种在响应发送到客户端后在Django中执行代码的方法。 我知道通常的方法是实现一个任务队列(例如,芹菜)。 但是,截至2019年5月,我正在使用的PaaS服务(PythonAnywhere)不支持任务队列。 对于一些简单的用例来说,它似乎也过于复杂。 我在SO上找到了以下解决方案:在响应发送到客户端后在Django中执行代码。 接受的答案在本地运行时效果很好。 但是,在PythonAnywhere上的生产中,它仍然阻止将响应发送到客户端。 是什么原因造成的?
这是我的实现:
from time import sleep
from datetime import datetime
from django.http import HttpResponse
class HttpResponseThen(HttpResponse):
"""
WARNING: THIS IS STILL BLOCKING THE PAGE LOAD ON PA
Implements HttpResponse with a callback i.e.,
The callback function runs after the http response.
"""
def __init__(self, data, then_callback=lambda: 'hello world', **kwargs):
super().__init__(data, **kwargs)
self.then_callback = then_callback
def close(self):
super().close()
return_value = self.then_callback()
print(f"Callback return value: {return_value}")
def my_callback_function():
sleep(20)
print('This should print 20 seconds AFTER the page loads.')
print('On PA, the page actually takes 20 seconds to load')
def test_view(request):
return HttpResponseThen("Timestamp: "+str(datetime.now()),
then_callback=my_callback_function) # This is still blocking on PA
我期待响应立即发送到客户端,但实际上需要整整20秒才能加载页面。 (在我的笔记本电脑上,代码效果很好。 响应立即发送,打印语句在20秒后执行。)