Is Django post_save signal asynchronous?

后端 未结 4 1653
小鲜肉
小鲜肉 2020-12-04 16:27

I have a like function which is just like social networks like or thumbs up function; the user clicks the star / heart / whatever to mark the content as liked.I

相关标签:
4条回答
  • 2020-12-04 17:12

    Also look into celery (or more specifically django-celery). It is an async task scheduler / handler. So your post_save signal handler creates a task, which is picked up and executed through celery. That way you still have your speedy application, while the heavy lifting is performed async, even on a different machine or batch of machines.

    0 讨论(0)
  • 2020-12-04 17:21

    The async-signals package (https://github.com/nyergler/async-signals) abstracts this issue. You call an async signal function; if Celery is present the package uses it to issue the signal asynchronously from a worker; and if Celery is not available the package sends the signal in the traditional synchronous way.

    0 讨论(0)
  • 2020-12-04 17:28

    Hm, first of all signals in Django are not asynchronous. For your particular case I think post_save is the wrong way to go. The most straightforward way is simply to fire an ajax request to view which do your like action and don't wait for the response. Instead modify your view/html directly after you fired the request.

    That would of course require that you know beforehand that your user is allowed to like this item and that your request will not fail.

    0 讨论(0)
  • 2020-12-04 17:30

    What you want is a thread. They're very easy to use. You just subclass threading.Thread and write a run method:

    import threading
    
    class LikeThread(threading.Thread):
        def __init__(self, user, liked, **kwargs):
            self.user = user
            self.liked = liked
            super(LikeThread, self).__init__(**kwargs)
    
        def run(self):
            # long running code here
    

    Then, when your ready to do the task, you fire it off with:

    LikeThread(request.user, something).start()
    

    The rest of your view code or whatever will resume and return the response, and the thread will happily do its work until it's done and then end itself.

    See full documentation: http://docs.python.org/library/threading.html

    0 讨论(0)
提交回复
热议问题