在Django init上启动一个简单的python线程

时间:2013-01-31 16:25:56

标签: python django python-2.7

我刚刚开始使用django。在我的开发环境中,我使用:

来启动django服务器
python manage.py runserver 0.0.0.0:8000

我的Web应用程序正在按预期工作,但我也有很多错误......但是到目前为止我想在服务器init上运行后台线程,我需要一些指导。

这是我想添加的线程代码:

def synchronized(L):
    def lock_around(f):
        def locked(*a, **k):
            with L:
                return f(*a, **k)
        locked.__name__ = f.__name__
        locked.__doc__ = f.__doc__
        return locked
    return lock_around


class ProcessMsgQueue:

    def __init__(self):
        try:
            print "jaojdajdoaj"
            self.dataCounter = 0
            self.errorCounter = 0
            self.setupQueueTable()
            self.wrapperFuns = structureWrapper.WrapperClass()
            msgStruct = MsgStruct()
            self.VerifyMsgQueue()
        except:
            raise

    def setupQueueTable(self):
        self.hash_object = QueueHandler("queue_details")
        self.hash_object.EnableListener()
        self.hash_object.createNewHashRef()
        self.hash_object.create("dataMsgQueue")
        self.hash_object.create("errorMsgQueue")

    @synchronized(lock)     
    def pendMessage(self):
        print "pendMsg"
        try:
            res_mq = posix_ipc.MessageQueue(RESPONSE_QUEUE_NAME)
            res_msg = None
            res_msg,t_size = res_mq.receive()
            #print res_msg.encode('hex')
            return res_msg
        except Exception as e:
            print e
            raise
        finally:
            res_mq.close()

    def VerifyMsgQueue(self):
        while(self.hash_object.Queuelisten):
            try:
                posixQueueMessage=self.pendMessage()
                if not posixQueueMessage == None:
                    msgStruct = None
                    msgStruct = MsgStruct()
                    self.wrapperFuns.memCopy(posixQueueMessage,msgStruct)
                    if(msgStruct.msgType == palMsgType["DOOR_OPEN_INSERVICE_MSG"]):
                        print "Added Error to hastable"
                        self.hash_object.set("errorMsgQueue",self.errorCounter,msgStruct.msgBuf)
                    else:
                        print "Added Data to hastable"
                        self.hash_object.set("dataMsgQueue",msgStruct.msgType,msgStruct.msgBuf)
                    posixQueueMessage=None
            except:
                raise

1 个答案:

答案 0 :(得分:2)

尝试从wsgi.py文件的末尾调用您的初始化代码。它将在服务器启动时执行一次。