Django post_save信号异步吗? [英] Is Django post_save signal asynchronous?

查看:372
本文介绍了Django post_save信号异步吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个喜欢的功能,就像社交网络一样,或者是竖起大拇指的功能;用户点击星号/心/任何将内容标记为喜欢的内容。它是用ajax完成的,必须快。这里唯一的问题是,由于某些原因,我必须为每个喜欢做一些任务,我发现它们在喜欢视图中直接编码,并且使其变慢。我正在考虑使用信号使这些任务的执行异步,所以视图可以将json立即发回到javascript,而无需等待任务完成。我开始为喜欢创建了一个信号,然后意识到Django的信号不是异步的,它会结束一样,视图必须等待信号完成发回它的响应。所以我可以尝试使这个信号是异步的,因为这里和这里解释,但是我也可以使用post_save信号为'like'模型,但现在我不知道视图是否可以在信号执行前完成?

解决方案

你想要的是一个线程。它们很容易使用。你只需要 threading.Thread ,并写一个运行方法:





$ b class LikeThread(threading.Thread):
def __init __(self,user,likes,** kwargs):
self.user = user
self.liked =喜欢
超级(LikeThread,self).__ init __(** kwargs)

def run(self):
#长运行代码这里

然后,当你准备完成任务时, :

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

您的其余视图代码或任何将恢复并返回响应,线程将高兴地完成工作,直到完成,然后结束。



查看完整的文档: http://docs.python .org / library / threading.html


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. It is done with ajax and must be fast. The only problem here is that for some reasons I have to do some tasks for each 'like' and I found out they were coded straight in the 'like' view and it makes it slow. I am thinking of using signals to make the execution of these tasks asynchronous so the view can send back the json right away to the javascript without waiting for the tasks to finish. I started created a signal for the 'like' but then realized that Django's signals were not asynchronous and it would end up the same, the view would have to wait for the signal to finish to send back its response. So I could try to make that signal asynchronous as it is explained here and there but I would as well use the post_save signal for the 'like' model but now I wonder if the view can finish before the signal gets executed?

解决方案

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

这篇关于Django post_save信号异步吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆