@@ -253,14 +253,7 @@ def __init__(self, path=None, settings=None, development=None):
253253        self ._plugInLoader  =  None 
254254        self .loadPlugIns ()
255255
256-         self ._needsShutDown  =  [True ]
257-         atexit .register (self .shutDown )
258-         if  self .setting ('RegisterSignalHandler' ):
259-             self ._sigTerm  =  signal .signal (signal .SIGTERM , self .sigTerm )
260-             try :
261-                 self ._sigHup  =  signal .signal (signal .SIGHUP , self .sigTerm )
262-             except  AttributeError :
263-                 pass   # SIGHUP does not exist on Windows 
256+         self .registerShutDownHandler ()
264257
265258    def  initErrorPage (self ):
266259        """Initialize the error page related attributes.""" 
@@ -385,6 +378,42 @@ def startSessionSweeper(self):
385378                                     task , "SessionSweeper" )
386379                print ("Session sweeper has started." )
387380
381+     def  registerShutDownHandler (self ):
382+         """Register shutdown handler in various ways. 
383+ 
384+         We want to make sure the shutdown handler is called, so that the 
385+         application can save the sessions to disk and do cleanup tasks. 
386+         """ 
387+         self ._needsShutDown  =  [True ]
388+         # register as Python atexit handler 
389+         atexit .register (self .shutDown )
390+         # register as termination signal handler 
391+         if  self .setting ('RegisterSignalHandler' ):
392+             self ._sigTerm  =  signal .signal (signal .SIGTERM , self .sigTerm )
393+             try :
394+                 self ._sigHup  =  signal .signal (signal .SIGHUP , self .sigTerm )
395+             except  AttributeError :
396+                 pass   # SIGHUP does not exist on Windows 
397+         # register as mod_wsgi shutdown handler 
398+         try :
399+             import  mod_wsgi 
400+         except  ImportError :  # mod_wsgi not installed 
401+             subscribeShutdown  =  None 
402+         else :
403+             try :
404+                 subscribeShutdown  =  mod_wsgi .subscribe_shutdown 
405+             except  AttributeError :  # mod_wsgi < 4.8.0 
406+                 try :
407+                     subscribeShutdown  =  mod_wsgi .subscribe_events 
408+                 except  AttributeError :  # mod_wsgi < 4.4.11 
409+                     subscribeShutdown  =  None 
410+         if  subscribeShutdown :
411+             def  shutDownHandler (event , ** _kwargs ):
412+                 if  event  ==  'process_stopping' :
413+                     print ("\n WSGI application has been notified to shutdown." )
414+                     self .shutDown ()
415+             subscribeShutdown (shutDownHandler )
416+ 
388417    def  shutDown (self ):
389418        """Shut down the application. 
390419
0 commit comments