How to execute code in Django after response has been sent to the client (on PythonAnywhere)?

寵の児 提交于 2021-01-29 18:28:37

问题


I'm looking for a way to execute code in Django after the response has been sent to the client. I know the usual way is to implement a task queue (e.g., Celery). However, the PaaS service I'm using (PythonAnywhere) doesn't support task queues as of May 2019. It also seems overly complex for a few simple use cases. I found the following solution on SO: Execute code in Django after response has been sent to the client. The accepted answer works great when run locally. However, in production on PythonAnywhere, it still blocks the response from being sent to the client. What is causing that?

Here's my implementation:

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

I'm expecting the response to be sent to the client immediately, but it actually takes a full 20 seconds for the page to load. (On my laptop, the code works great. The response is sent immediately and the print statements execute 20 seconds later.)

来源:https://stackoverflow.com/questions/56200432/how-to-execute-code-in-django-after-response-has-been-sent-to-the-client-on-pyt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!