Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - How to check if server is running in ASGI or in WSGI mode?

We are running the same django project in WSGI mode for handling HTTP requests and in ASGI mode for handling WebSockets. For WSGI mode we are using gunicorn3 server:

gunicorn3 --pythonpath . -b 0.0.0.0:8000 chat_bot.wsgi:application

For ASGI mode we are using daphne server:

daphne --root-path . -b 0.0.0.0 -p 8001 chat_bot.asgi:application

How to programatically detect which mode currently is running GreenUnicorn+WSGI or Daphne+ASGI?

like image 810
happy_marmoset Avatar asked Jan 03 '23 03:01

happy_marmoset


1 Answers

One possibility:

Inside of your wsgi.py file you can set an environment variable to one value you won't be setting anywhere else:

os.environ.setdefault('SERVER_GATEWAY_INTERFACE', 'Web')

And then inside of asgi.py set it to a different variable:

os.environ.setdefault('SERVER_GATEWAY_INTERFACE', 'Asynchronous')

Then in other parts of your code, just check against the environment variable:

if os.environ.get('SERVER_GATEWAY_INTERFACE') == 'Web':
    # WSGI, do something
else:
    # ASGI, do something else
like image 173
Robert Townley Avatar answered Jan 05 '23 14:01

Robert Townley