Domanda

Vorrei eseguire call_method del Django all'interno di un thread. Questo è il codice di esempio:

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.

server di Django si avvia correttamente, ma ServerStarter si crea due volte .
E le istanze sia di ServerStarter correre.
Se io commento call_command ( "runserver", noreload = True) nel metodo di esecuzione, allora solo
un thread è creato (e questo è quello che voglio).
Grazie in anticipo!

È stato utile?

Soluzione

Credo che questo è probabilmente causato dal server interno Django ricaricare tutti i moduli come il suo solito. Prova qualunque sia l'equivalente di --noreload è per call_command (probabilmente call_command("runserver", noreload=True) ma non sono sicuro).

(anche QThreads sono iniziate da QApplication.exec_();. A meno che non si dispone di un requisito speciale per avviarlo prima, non credo si dovrebbe eseguire starter.start() te stesso)

Altri suggerimenti

Ho trovato una soluzione (Chris Morgan aveva ragione). Questo codice funziona come voglio:

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()
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top