django channels ImproperlyConfigured: Cannot find 'app' in ASGI_APPLICATION module - python

I am setting up channels asgi with Django. I have tried upgrading Django and Channels.
"Cannot find %r in ASGI_APPLICATION module %s" % (name, path)
django.core.exceptions.ImproperlyConfigured: Cannot find 'app' in ASGI_APPLICATION module <MyApp>.routing
my routing config is as per the tutorial in mysite/routing
application = ProtocolTypeRouter({
# (http->django views is added by default)
'websocket': AuthMiddlewareStack(
URLRouter(
chat.routing.websocket_urlpatterns
)
),
})
and the import statement that is supposed to just be simply
import chat.routing
my directory structure is exactly per the tutorial as well
with setting config
INSTALLED_APPS = [
'channels',
'chat',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
and
ASGI_APPLICATION = 'chat.routing.application'
Thanks

I got this kind of error when running my Django Channels's routing.py using daphne server.
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
This is what documentation explain about daphne servers,
Daphne is a HTTP, HTTP2 and WebSocket protocol server for ASGI and ASGI-HTTP, developed to power Django Channels.
It supports automatic negotiation of protocols; there’s no need for URL prefixing to determine WebSocket endpoints versus HTTP endpoints.
Note: Daphne 2 is not compatible with Channels 1.x applications, only with Channels 2.x and other ASGI applications. Install a 1.x version of Daphne for Channels 1.x support.
As you can see, we can use both HTTP and WSprotocol through daphne server without using Gunicorn server. What you can do is just add below line to top of your routing.py file.
from .wsgi import *
So now your routing.py file should be like this,
# DockerDjangoNginx is my project name
# your routing.py file should be in this location where the wsgi.py file is placed
# DockerDjangoNginx/DockerDjangoNginx/routing.py
from .wsgi import * # add this line to top of your code
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
import comapp.routing as routing
application = ProtocolTypeRouter({
# (http->django views is added by default)
'websocket': AuthMiddlewareStack(
URLRouter(
routing.websocket_urlpatterns
)
),
})
Now you can run your daphne server.
(venv) [root#t2mdocker]#daphne -b 0.0.0.0 -p 8000 DockerDjangoNginx.routing:application
2019-05-30 03:33:06,390 INFO Starting server at tcp:port=8000:interface=0.0.0.0
2019-05-30 03:33:06,391 INFO HTTP/2 support enabled
2019-05-30 03:33:06,391 INFO Configuring endpoint tcp:port=8000:interface=0.0.0.0
2019-05-30 03:33:06,392 INFO Listening on TCP address 0.0.0.0:8000
If you see something like this HTTP/2 support not enabled (install the http2 and tls Twisted extras) when running daphne server, you can run pip install -U Twisted[tls,http2] to correct those errors.

Pretty sure this was the problem. Needed to add this asgi.py file next to wsgi.py
import os
import django
from channels.routing import get_default_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "<myproj>.settings")
django.setup()
application = get_default_application()
and start server with
(vEnv)$daphne <myproj>.asgi:application --port 8888

Change:
ASGI_APPLICATION = 'myproject.routing.application'
To
ASGI_APPLICATION = "myproject.asgi.application"
and issue will hopefully be solved, check the official channels site for more details (https://channels.readthedocs.io/en/stable/installation.html)

Try the following, it worked for me:
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
from chat import routing # This change
application = ProtocolTypeRouter({
# (http->django views is added by default)
'websocket': AuthMiddlewareStack(
URLRouter(
routing.websocket_urlpatterns #This change
)
),
})

Check your settings.py, you stated it included:
ASGI_APPLICATION = 'chat.routing.application'
But chat is your added App, it should be the name of the django project itself, so in the tutorial you said you followed it should be something like:
ASGI_APPLICATION = 'mysite.routing.application'
# or
ASGI_APPLICATION = 'core.routing.application'

Related

Facing an error with django channels when deploying to elastic beanstalk

I am facing an issue with websockets. When I run the program locally it works fine but when I deploy it to aws elastic beanstalk I face the following issue. I have a simple code as mentioned below.
django.config
option_settings:
aws:elasticbeanstalk:container:python:
WSGIPath: playzone.wsgi:application
aws:elasticbeanstalk:environment:process:http:
Port: '80'
Protocol: HTTP
aws:elasticbeanstalk:environment:process:websocket:
Port: '5000'
Protocol: HTTP
aws:elasticbeanstalk:environment:proxy:staticfiles:
/static: static
Procfile
web: gunicorn my_app.wsgi
websocket: daphne -b :: -p 5000 my_app.asgi:application
asgi.py
import os
from django.core.asgi import get_asgi_application
from channels.routing import ProtocolTypeRouter,URLRouter
from . import routing
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my_app.settings')
application = get_asgi_application()
application = ProtocolTypeRouter({
'http': get_asgi_application(),
'websocket': URLRouter(
routing.websocket_urlpatterns
)
})
And there are 2 more simple files routing.py and consumers.py. I've even configured the load balancers on the environment's settings (80 - HTTP ; 5000 - HTTP). So once deployed, when I try routing to the webpage which has a websocket connection, I get an error saying WebSocket connection to 'ws://yyy.com/ws/' failed:. Please help me out on how I can fix it.
Also am not using redis or any channel layer. Please help me out on how I can fix it.

How to resolve “Error during WebSocket handshake: Unexpected response code: 503” error in a Django Channels Heroku app?

The error in the console :
app.e05f6d1a6569.js:105 WebSocket connection to 'wss://domecode.com/wss?session_key=${sessionKey}' failed: Error during WebSocket handshake: Unexpected response code: 503
(anonymous) # app.e05f6d1a6569.js:105
mightThrow # jquery.js:3762
process # jquery.js:3830
I'm running a Django Channels app ( Messaging app ) on Heroku using Daphne. All the files that correspond to this problem are included in this question.
routing.py - messaging app
from messaging import consumers
from django.urls import re_path
websocket_urlpatterns = [
re_path(r'^ws$', consumers.ChatConsumer),
]
app.js - snipped of the websocket part of the app.js file
var ws_scheme = window.location.protocol == 'https:' ? 'wss' : 'ws';
var socket = new WebSocket(ws_scheme + '://' + window.location.host + '/' + ws_scheme + '?session_key=${sessionKey}');
asgi.py - project's asgi
import os
import django
# from django.core.asgi import get_asgi_application
from channels.routing import get_default_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'domecode.settings')
django.setup() # to deploy with asgi when using channels
application = get_default_application()
Procfile
release: python3 manage.py makemigrations && python3 manage.py migrate
web: daphne domecode.asgi:application --port $PORT --bind 0.0.0.0 -v2
worker: python3 manage.py runworker channel_layer -v2
Django Settings snippet for CHANNEL_LAYERS - REDIS_URL is an env variable in Heroku.
CHANNEL_LAYERS = {
'default': {
'BACKEND': 'channels_redis.core.RedisChannelLayer',
'CONFIG': {
"hosts": [config('REDIS_URL')],
},
},
}
Any information on what went wrong here?
Sidenote: It works perfectly fine in the development server however it gives the error mentioned at the top in the production server at https://domecode.com/chat/.
When I send a message on the production server, it gives an error in the console and I don't see my message that was sent unless I reload the page. I've tried looking for similar questions everywhere but none of them were answered in a way that would work for me.
Changes in the Procfile, routing.py of the messaging app and some minor changes such as activating worker dyno on Heroku worked for me.
Procfile should be changed to :
release: python3 manage.py makemigrations && python3 manage.py migrate
web: daphne domecode.asgi:application --port $PORT --bind 0.0.0.0 -v2
worker: python3 manage.py runworker channels --settings=domecode.settings -v2
and Routing.py to :
from messaging import consumers
from django.urls import re_path
websocket_urlpatterns = [
re_path(r'^ws$', consumers.ChatConsumer),
]

Django ModuleNotFoundError: No module named 'mysite.settings' when trying to host application with wsgi server

So I wanted to deploy my first django application on a cherryPy webserver using wsgi. And I have issues with os.environ['DJANGO_SETTINGS_MODULE']. When trying to run application callable it throws error, that module is not found. Project structure:
ResourceManager
ResourceManager
ResourceManager
__init__.py
cherryserver.py
settings.py
urls.py
wsgi.py
SimpleResourceManager
migrations
__init__.py
admin.py
apps.py
models.py
serializers.py
tests.py
urls.py
views.py
manage.py
wsgi.py file:
import os
import sys
from django.core.wsgi import get_wsgi_application
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0,BASE_DIR)
os.environ['DJANGO_SETTINGS_MODULE'] = 'ResourceManager.settings'
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ResourceManager.settings')
application = get_wsgi_application()
cherryserver.py:
import cherrypy
from ResourceManager.ResourceManager.wsgi import application
if __name__ == '__main__':
# Mount the application
cherrypy.tree.graft(application, "/")
# Unsubscribe the default server
cherrypy.server.unsubscribe()
# Instantiate a new server object
server = cherrypy._cpserver.Server()
# Configure the server object
server.socket_host = "0.0.0.0"
server.socket_port = 8080
server.thread_pool = 30
# Subscribe this server
server.subscribe()
cherrypy.engine.start()
cherrypy.engine.block()
Application works fine when using command runserver 8080, but when i tried to run it on different server. It says ModuleNotFoundError: No module named "ResourceManager.settings".
So i tried: Change where cherryserver.py is located in directory, I have added additional lines of code to wsgy.py file and I'm running out of ideas what is wrong when I'm deploying my app on different server. Why I'm using cherryPy, well I have to test 5 web servers that are based on python.
Try changing from:
from ResourceManager.ResourceManager.wsgi import application
To:
from wsgi.py import application
This is because they are located in the same directory, if this does not work just mess around with the from as it seems that your path to the wsgi file is wrong.

How to generate asgi.py for existent project?

I have an existent django project in 2.2, but now i would like to start using channels, so I have to change to 3.0 and asgi instead of wsgi.
How can I generate the asgi.py that I need to run the app?
Django has a template file here that it uses to generate the asgi.py.
Jus copy paste this next to your wsgi.py:
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', '{{ project_name }}.settings')
application = get_asgi_application()
For Django==2.2, I found the solution in this link. For the asgi.py file, the content would be:
"""
ASGI entrypoint. Configures Django and then runs the application
defined in the ASGI_APPLICATION setting.
"""
import os
import django
from channels.routing import get_default_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings")
django.setup()
application = get_default_application()

How to configure wsgi application to migrate to django 1.7?

I'm trying to upgrade from Django 1.6 to 1.7.
When running python manage.py runserver, I got the following error :
django.core.exceptions.ImproperlyConfigured: WSGI application 'myapp.wsgi.application' could not be loaded; Error importing module: 'cannot import name get_path_info'
Here's the corresponding line in my settings.py :
WSGI_APPLICATION = 'myapp.wsgi.application'
Here's my wsgi.py file :
import os
# We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks
# if running multiple sites in the same mod_wsgi process. To fix this, use
# mod_wsgi daemon mode with each site in its own daemon process, or use
# os.environ["DJANGO_SETTINGS_MODULE"] = "myapp.settings"
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp.settings")
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
from django.core.wsgi import get_wsgi_application
# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application)
from dj_static import Cling
application = Cling(get_wsgi_application())
Any idea to fix it ?
What version of dj_static are you using?
I upgraded to Django 1.7 and my site broke, leading me to your question.
I checked my dj_static version (I had been using 0.0.5 and noticed that the latest release at the time of this writing is 0.0.6).
Upon updating dj_static, my site appears to be functioning properly under Django 1.7.

Categories