Files
asyncron/asyncron/gunicorn.py
2026-04-02 15:26:25 +02:00

52 lines
1.5 KiB
Python

##
## - Gunicorn compatibility
## Add this to gunicorn.py conf file:
## from asyncron.gunicorn import post_fork
##
## adds an asyncron worker in each gunicorn worker process
## Hooks into 'dev reload' and 'exist signals' for graceful termination of tasks
##
def post_fork( server, worker ): #worker and AsyncronWorker, pay attention!
post_fork.server = server
post_fork.worker = worker
#Temporary so I can work on this.
import time
for attempt in range(3):
try: from .workers import AsyncronWorker
except ImportError: time.sleep(0.1)
else: break
else: raise ImportError()
AsyncronWorker.IS_ACTIVE = True
AsyncronWorker.register_init_callback( _patch )
def _patch( aworker ):
gserver = post_fork.server
gworker = post_fork.worker
if not gworker.reloader: return #So if reload = False
#Attach gunicorn reload event to asyncron_worker exit signals
original_callback = gworker.reloader._callback
def new_callback( *args, **kwargs ):
aworker.stop( reason = "Gunicorn Reload" )
return original_callback( *args, **kwargs )
gworker.reloader._callback = new_callback
aworker.log.setLevel( gworker.log.loglevel )
aworker.log.info( "Attached worker to gunicorn." )
# Keeping the worker in post_fork.worker so we can add extra files in it for it to track
# LOW PRIORITY TODO: Currently unfinished, since i just realized using the "inotify" support of gunicorn
# makes this reduntant, but still here is the relevant code if I want to also support the simpler
# polling system
# Should be in asyncron.app.ready
# -> post_fork.worker.reloader.add_extra_file