Daphne causing Modulenotfound error on production

hi @KenWhitesell I getting same issue and tried the solution provided.
Im trying to run daphne for websocket but its failing and throwing same error like above with my project directory name. im attaching daphne error log for more info below.

Traceback (most recent call last):
  File "/home/administrator/people/peoples/venv/bin/daphne", line 8, in <module>
    sys.exit(CommandLineInterface.entrypoint())
  File "/home/administrator/people/peoples/venv/lib/python3.8/site-packages/daphne/cli.py", line 170, in entrypoint
  cls().run(sys.argv[1:])
 File "/home/administrator/people/peoples/venv/lib/python3.8/site-packages/daphne/cli.py", line 232, in run
application = import_by_path(args.application)
 File "/home/administrator/people/peoples/venv/lib/python3.8/site-packages/daphne/utils.py", line 12, in import_by_path
   target = importlib.import_module(module_path)
 File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module
   return _bootstrap._gcd_import(name[level:], package, level)
   File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
 File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
   File "<frozen importlib._bootstrap_external>", line 848, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
 File "/home/administrator/people/peoples/./peoples/asgi.py", line 6, in <module>
     from chat.consumers import ChatRoomConsumer
 File "/home/administrator/people/peoples/./chat/consumers.py", line 6, in <module>
  from people.models import User
 File "/home/administrator/people/peoples/./people/models.py", line 5, in <module>
Apr 18 11:48:03 35651.hostserv.eu python[119025]:     from django.contrib.auth.models import AbstractUser
 File "/home/administrator/people/peoples/venv/lib/python3.8/site-packages/django/contrib/auth/models.py", line 2, in <module>
  from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
 File "/home/administrator/people/peoples/venv/lib/python3.8/site-packages/django/contrib/auth/base_user.py", line 47, in <module>
Apr 18 11:48:03 35651.hostserv.eu python[119025]:     class AbstractBaseUser(models.Model):
File "/home/administrator/people/peoples/venv/lib/python3.8/site-packages/django/db/models/base.py", line 107, in __new__
   app_config = apps.get_containing_app_config(module)
  File "/home/administrator/people/peoples/venv/lib/python3.8/site-packages/django/apps/registry.py", line 252, in get_containing_app_config
self.check_apps_ready()
  File "/home/administrator/people/peoples/venv/lib/python3.8/site-packages/django/apps/registry.py", line 134, in check_apps_ready
 settings.INSTALLED_APPS
  File "/home/administrator/people/peoples/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 76, in __getattr__
  self._setup(name)
File "/home/administrator/people/peoples/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 57, in _setup
   raise ImproperlyConfigured(
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.

Follwing is daphne file config

[Unit]
Description=WebSocket Daphne Service
After=network.target

[Service]
Type=simple
User=root
Group=root
WorkingDirectory=/home/administrator/people/peoples
ExecStart=/home/administrator/people/peoples/venv/bin/python /home/administrator/people/peoples/venv/bin/daphne -e ssl:8001:privateKey=/etc/letsencrypt/live/www.peoplestogether.com/privkey.pem:certKey=/etc/letsencrypt/live/www.peoplestogether.com/fullchain.pem  peoples.asgi:application
Restart=on-failure

[Install]
WantedBy=multi-user.target

hope that helps

It’s telling you what’s wrong right here:

What happens if you run it manually from the command line? If it works, check your environment variables and make sure the proper settings are made in your systemd file.

I Checked, on command line its working fine after 1-2 adjustments. but no luck with systemd file

So what changes did you make to the systemd file.

instaed of ssl i tried /home/administrator/people/peoples/venv/bin/daphne -b 0.0.0.0 -p 8001 peoples.asgi:application this command

The adjustments ware inside asgi file as per channel deployment info provided

What does your asgi.py file look like then?

import os
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter

from django.urls import re_path, path
from django.core.asgi import get_asgi_application
from channels.security.websocket import AllowedHostsOriginValidator


os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'peoples.settings')

django_asgi_app = get_asgi_application()

from chat.consumers import ChatRoomConsumer

application = ProtocolTypeRouter({
    'http': django_asgi_app,
    'websocket':AllowedHostsOriginValidator( AuthMiddlewareStack(
        URLRouter([
            path('chat/<str:room_name>/<str:from_user>/', ChatRoomConsumer.as_asgi()),
            re_path(r'^ws/chat/(?P<room_name>\w+)/(?P<from_user>\w+)/$', ChatRoomConsumer.as_asgi()),
        ])
    )
    )
})

both path are same, specificallly to say, “path” was working previously on prod with re_path not so i kept both for local and prod.

And confirming that your settings file is located at:
/home/administrator/people/peoples/peoples/settings.py?

(Note, if this is a reference to your URLRouter paths, they’re not part of this issue. What’s happening here is happening at an earlier point of the startup process.
The fundamental root cause here is that the Django startup process is not finding your settings.py file.)

Which means i guess I need to check boot log for more info, which triggering systemd file right?

Can you confirm that your settings file is located at:

I don’t expect your boot log to have any further information than this, but it never hurts to check.

Yes, confirming that its the right location.
ok

When you successfully ran it from the command line, what was your current directory?

Is this the command being run after the adjustments that worked?

This command didnot worked but following did on command line

/home/administrator/people/peoples# daphne -b 0.0.0.0 -p 8001 peoples.asgi:application

till # is the present working directory.

Which means you have a PATH setting referencing the location for daphne, along with (possibly) a PYTHONPATH.

I’m guessing you’re running this from within a logged-in shell under the name administrator. In your systemd file, you’re trying to run this as root, which is not going to have the same environment variables set - especially since it’s not a logged-in shell.

When you run it and it works, use the env command to see what your environment settings are that may affect this, and set them accordingly.
You want to try and recreate your shell’s environment as closely as necessary to ensure all the appropriate references are available.

Seems to be working fine now. Websocket is able to communicate both ways. Can you add comment for env command, Im not sure how I can do it. You are right it could be user issue. But will check in sometime.
Im cuurently logged in as root.

The env command is just that - env. Try it.

:grinning: User is administrator. so daphne service should be using the same right?

It’s not a requirement to be the same. I don’t use the same account for production services as when doing development - I have separate accounts set up for that. You just need to ensure that all the permissions and environment settings are configured appropriately.

1 Like

Than for suggestions, As this issue is resolved @KenWhitesell cn you close this?

As the person who opened it, you can mark this item as resolved. (Specifically, you can select any response as being the “solution”.)
Beyond that, there’s no reason - or mechanism that I’m familiar with - to “close” this topic.

1 Like