I would to execute the django's call_method inside a Thread. This is the sample code:
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 server starts correctly, but ServerStarter is created twice.
And both ServerStarter's instances run. If I comment call_command("runserver", noreload=True) in the run method, then only one thread is created (and that is what I want). Thanks in advance!I found a solution (Chris Morgan was right). This code works as I want:
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()
I think this is probably caused by the Django internal server reloading all modules as is its wont. Try whatever the equivalent of --noreload
is for call_command
(probably call_command("runserver", noreload=True)
but I'm not sure).
(Also QThread
s are started by QApplication.exec_()
; unless you have a special requirement to start it earlier, I don't believe you should run starter.start()
yourself.)
精彩评论