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

1

6

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?

Biancabiancha answered 19/7, 2018 at 19:45 Comment(0)
A
12

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
Adelaadelaida answered 19/7, 2018 at 20:8 Comment(1)
why an environment variable and not just setting a global python variable in one of the python modules in the project where it makes sense to store this?Viscus

© 2022 - 2024 — McMap. All rights reserved.