我想在Thread中执行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),那么只有 创建了一个线程(这就是我想要的) 提前谢谢!
答案 0 :(得分:5)
我找到了解决方案(Chris Morgan是对的)。这段代码按我的意思运行:
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()
答案 1 :(得分:0)
我认为这可能是由Django内部服务器重新加载所有模块造成的。尝试--noreload
call_command
的等效内容(可能是call_command("runserver", noreload=True)
,但我不确定)。
(同样QThread
由QApplication.exec_()
启动;除非您有特殊要求提前启动它,否则我认为您不应该自己运行starter.start()
。)