首页 > 解决方案 > 将响应发送到客户端(在 PythonAnywhere 上)后,如何在 Django 中执行代码?

问题描述

在将响应发送到客户端后,我正在寻找一种在 Django 中执行代码的方法。我知道通常的方法是实现一个任务队列(例如 Celery)。但是,截至 2019 年 5 月,我使用的 PaaS 服务 (PythonAnywhere) 不支持任务队列。对于一些简单的用例来说,它似乎也过于复杂。我在 SO 上找到了以下解决方案:Execute code in Django after response has been sent to the client。接受的答案在本地运行时效果很好。但是,在 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 秒后执行。)

标签: djangotask-queuepythonanywhere

解决方案


推荐阅读