55
66from django .core .management .base import BaseCommand
77from django .db import connection
8+ from django .utils import autoreload
9+ from django .utils .autoreload import raise_last_exception
810
911
1012class Worker (BaseCommand ):
@@ -24,6 +26,12 @@ def add_arguments(self, parser):
2426 action = 'store_true' ,
2527 help = "Use LISTEN/NOTIFY to wait for events."
2628 )
29+ parser .add_argument (
30+ '--noreload' ,
31+ action = 'store_false' ,
32+ dest = 'use_reloader' ,
33+ help = "Don't use the auto-reloader." ,
34+ )
2735
2836 def handle_shutdown (self , sig , frame ):
2937 if self ._in_task :
@@ -67,15 +75,23 @@ def handle(self, **options):
6775 self .delay = options ['delay' ]
6876 self .listen = options ['listen' ]
6977
78+ # Handle the signals for warm shutdown.
79+ signal .signal (signal .SIGINT , self .handle_shutdown )
80+ signal .signal (signal .SIGTERM , self .handle_shutdown )
81+
82+ self .run (** options )
83+
84+ def inner_run (self , ** options ):
85+ # If an exception was silenced in ManagementUtility.execute in order
86+ # to be raised in the child process, raise it now.
87+ raise_last_exception ()
88+
7089 with connection .cursor () as cursor :
7190 cursor .execute ("SET application_name TO %s" , ['dpq#{}' .format (os .getpid ())])
7291
7392 if self .listen :
7493 self .queue .listen ()
7594 try :
76- # Handle the signals for warm shutdown.
77- signal .signal (signal .SIGINT , self .handle_shutdown )
78- signal .signal (signal .SIGTERM , self .handle_shutdown )
7995
8096 while True :
8197 self .run_available_tasks ()
@@ -84,6 +100,13 @@ def handle(self, **options):
84100 # got shutdown signal
85101 pass
86102
103+ def run (self , ** options ):
104+ """Run the worker, using the autoreloader if needed."""
105+ if options ['use_reloader' ]:
106+ autoreload .run_with_reloader (self .inner_run , ** options )
107+ else :
108+ self .inner_run (None , ** options )
109+
87110 def wait (self ):
88111 if self .listen :
89112 count = len (self .queue .wait (self .delay ))
0 commit comments