-
-
Save synchronizing/e60532664fd50bb17058f24e3b674276 to your computer and use it in GitHub Desktop.
Start a WSGI app with N number of processes with Bjoern.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Starts a WSGI application with Bjoern; https://github.com/jonashaag/bjoern. | |
Make sure 'libev' is installed in your system. | |
Gist found here: | |
https://gist.github.com/synchronizing/e60532664fd50bb17058f24e3b674276 | |
""" | |
import logging | |
import multiprocessing | |
import os | |
import signal | |
import bjoern | |
def wsgi_application(): | |
""" | |
Retrieves WSGI application to start. | |
""" | |
from django.core.wsgi import get_wsgi_application | |
# Update line below if using Django. | |
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "djangosite.djangosite.settings") | |
return get_wsgi_application() | |
def start(host: str, port: int, workers: int): | |
""" | |
Starts the server with N workers. | |
""" | |
# Initial logger for main process. | |
logging.getLogger().setLevel(logging.INFO) | |
logger = logging.getLogger(__name__) | |
logger_handler = logging.StreamHandler() | |
logger_handler.setLevel(logging.INFO) | |
logger_handler.setFormatter(logging.Formatter("%(message)s")) | |
logger.addHandler(logger_handler) | |
# When worker number is set to -1 we max out the number of workers based | |
# on Guinicorn assumptions: https://docs.gunicorn.org/en/stable/design.html#how-many-workers | |
if workers == -1: | |
workers = multiprocessing.cpu_count() * 2 + 1 | |
# Start mainloop. | |
bjoern.listen(wsgi_application(), host, port) | |
logger.info("Started server on %s:%d with %d workers.", host, port, workers) | |
# Reconfigures logger so process ID is shown. | |
logger_handler.setFormatter(logging.Formatter("[%(process)s] %(message)s")) | |
# Start multiple processes with their own loggers. | |
workers_pid = [] | |
for _ in range(workers): | |
pid = os.fork() | |
if pid > 0: | |
workers_pid.append(pid) | |
elif pid == 0: | |
try: | |
logger.info("Starting worker.") | |
bjoern.run() | |
except KeyboardInterrupt: | |
exit() | |
# Waits for the workers to finish. | |
try: | |
for _ in range(workers): | |
os.wait() | |
except KeyboardInterrupt: | |
for pid in workers_pid: | |
os.kill(pid, signal.SIGINT) | |
if __name__ == "__main__": | |
start(host="127.0.0.1", port=8000, workers=1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment