2

我会在线程中执行 django 的 call_method。这是示例代码:

import sys
sys.path.append("/my/django/project/path/")
import threading
import time 


# Import my django project configuration settings
from django.core.management import setup_environ
from mydjangoprojectname import settings
setup_environ(settings)

from django.core.management import call_command

class ServerStarter(threading.Thread):
    def __init__(self):
        super(ServerStarter, self).__init__()
        print "ServerStarter instance created"

    def run(self):
        print "Starting Django Server..."
        call_command("runserver", noreload=True)


if __name__ == '__main__':
    starter = ServerStarter()
    starter.start()

------------------------------
OutPut:
ServerStarter instance created
Starting Django Server...
ServerStarter instance created
Starting Django Server...
Validating models...
0 errors found
Django version 1.2.3, using settings 'mydjangoprojectname.settings'
Development server is running at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

Django 服务器正确启动,但 ServerStarter 被创建了两次
并且两个 ServerStarter 的实例都运行。
如果我在 run 方法中注释 call_command("runserver", noreload=True) ,那么只会
创建一个线程(这就是我想要的)。
提前致谢!

4

2 回答 2

5

我找到了解决方案(克里斯摩根是对的)。此代码按我的意愿工作:

import sys
sys.path.append("/my/django/project/path/")
import threading

# Import my django project configuration settings
from django.core.management import setup_environ, ManagementUtility

from mydjangoprojectname import settings
setup_environ(settings)


class ServerStarter(threading.Thread):
    def __init__(self):
        super(ServerStarter, self).__init__()
        print "ServerStarter instance created"

    def run(self):
        print "Starting Django Server..."
        utility = ManagementUtility()
        command = utility.fetch_command('runserver')
        command.execute(use_reloader=False)


if __name__ == '__main__':
    starter = ServerStarter()
    starter.start()
于 2010-12-12T17:22:13.517 回答
0

我认为这可能是由于 Django 内部服务器按惯例重新加载所有模块造成的。尝试任何等效的--noreload方法call_command(可能call_command("runserver", noreload=True)但我不确定)。

(也是QThreads 由 启动的QApplication.exec_();除非您有特殊要求更早启动它,否则我认为您不应该starter.start()自己运行。)

于 2010-12-12T12:29:14.077 回答