display data in real time and filter on the user (websocket)

Hello, I have a small problem I created a websocket to display data on a page in real time, the data is displayed but I would now like to filter them on the user who is connected I have already consulted the doc of Django Channels but it is not very clear for me if someone can help me :slight_smile:
here is my code :

consumers.py

class HubriseOrderConsumer(ListModelMixin, GenericAsyncAPIConsumer):

    def get_queryset(self, **kwargs):
        return HubriseOrder.objects.all()

    serializer_class = HubriseOrderSerializer
    permissions = (permissions.AllowAny,)

    async def connect(self, **kwargs):
        await self.model_change.subscribe()
        await super().connect()

    @model_observer(HubriseOrder)
    async def model_change(self, message, observer=None, **kwargs):
        await self.send_json(message)

    def model_serialize(self, instance, action, **kwargs):
        return dict(data=HubriseOrderSerializer(instance=instance).data, action=action.value)

asgi.py

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

application = get_asgi_application()

application = ProtocolTypeRouter({
    "http": application,
    "websocket": URLRouter(websocket_urlpatterns),
})

routing.py

websocket_urlpatterns = [
    re_path(r"^ws/$", consumers.HubriseOrderConsumer.as_asgi())]

and seralizers.py

class HubriseOrderSerializer(serializers.ModelSerializer):

    class Meta:
        model = HubriseOrder
        fields = "__all__"

When a consumer is called, it receives access to that connection’s scope object. Among other things, that scope contains a reference to the user object for that connection.

@KenWhitesell

If I understood correctly self.scope['user'] is used to determine the user to connect?
I did that but I still got an error, to tell the truth I had already tried that but I didn’t understand where the error came from

class HubriseOrderConsumer(ListModelMixin, GenericAsyncAPIConsumer):

    def get_queryset(self, **kwargs):
        return HubriseOrder.objects.all()

    serializer_class = HubriseOrderSerializer
    permissions = (permissions.AllowAny,)

    async def connect(self, **kwargs):
        print('session', self.scope['user'])
        await self.model_change.subscribe()
        await super().connect()

    @model_observer(HubriseOrder)
    async def model_change(self, message, observer=None, **kwargs):
        await self.send_json(message)

    def model_serialize(self, instance, action, **kwargs):
        return dict(data=HubriseOrderSerializer(instance=instance).data, action=action.value)

error

KeyError: 'user'

ok I had not seen I must also change in asgi, I also modified this

application = ProtocolTypeRouter({

    "http": application,
    "websocket": AllowedHostsOriginValidator(
        AuthMiddlewareStack(
            URLRouter(websocket_urlpatterns),
        )
    ),

})

my server sends me this error

    raise ImproperlyConfigured("Cannot import ASGI_APPLICATION module %r" % path)
django.core.exceptions.ImproperlyConfigured: Cannot import ASGI_APPLICATION module 'OrderLine1.asgi'

Can you post the complete asgi.py file? I’ve typically seen this error when there’s something else that has been changed or is otherwise incorrect in that file.

Also, how are you running your application? Are you using the Channels flavor of runserver or are you running Daphne directly?

I use channel

and my asgi.py

import os

from django.core.asgi import get_asgi_application

from channels.routing import ProtocolTypeRouter, URLRouter

from myapp.routing import websocket_urlpatterns

from myapp import consumers

from channels.security.websocket import AllowedHostsOriginValidator

from channels.auth import AuthMiddlewareStack

# from django.urls import re_path

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

application = get_asgi_application()

# application = ProtocolTypeRouter({
#     "http": application,
#     "websocket": URLRouter(websocket_urlpatterns),
# })

application = ProtocolTypeRouter({

    "http": application,
    "websocket": AllowedHostsOriginValidator(
        AuthMiddlewareStack(
            URLRouter(websocket_urlpatterns),
        )
    ),

}

You have:

But then you have:

You’re redefining the variable named application which is overwriting your previous definition of the name.

These two entities should have different names.

(No, I don’t have a good explanation why it may have worked for you in the earlier case, unless it is an issue of when that name is resolved to a value in the process of constructing the objects.)

I crushed

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

# application = get_asgi_application()

# application = ProtocolTypeRouter({
#     "http": application,
#     "websocket": URLRouter(websocket_urlpatterns),
# })

application = ProtocolTypeRouter({

    "websocket": AllowedHostsOriginValidator(
        AuthMiddlewareStack(
            URLRouter(websocket_urlpatterns),
        )
    ),

})

error

get_default_application
    raise ImproperlyConfigured("Cannot import ASGI_APPLICATION module %r" % path)
django.core.exceptions.ImproperlyConfigured: Cannot import ASGI_APPLICATION module 'OrderLine1.asgi'

Just removing the http entry actually creates different problems.

Change the name of the variable - don’t change anything else (yet).

I can’t see what the problem is

Go back to what you had earlier - before you removed the ‘http’ entry in your ProtocolTypeRouter definition.

However, change the name of the variable to something other than application, and change your get_asgi_application line to use that new name. (See the example at Security — Channels 4.0.0 documentation)

like this?

testapp = get_asgi_application()

# application = ProtocolTypeRouter({
#     "http": applicationhttp,
#     "websocket": URLRouter(websocket_urlpatterns),
# })

application = ProtocolTypeRouter({
    "http": testapp,
    "websocket": AllowedHostsOriginValidator(
        AuthMiddlewareStack(
            URLRouter(websocket_urlpatterns),
        )
    ),

})

Yes, that addresses the name-conflict issue.

I still have this error :sweat_smile:

in get_default_application
    raise ImproperlyConfigured("Cannot import ASGI_APPLICATION module %r" % path)
django.core.exceptions.ImproperlyConfigured: Cannot import ASGI_APPLICATION module 'OrderLine1.asgi'

So what does your complete asgi.py file look like right now?

like this

"""
ASGI config for OrderLine1 project.

It exposes the ASGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/4.0/howto/deployment/asgi/
"""

import os

from django.core.asgi import get_asgi_application

from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
from channels.security.websocket import AllowedHostsOriginValidator

from myapp.routing import websocket_urlpatterns

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

testapp = get_asgi_application()

# application = ProtocolTypeRouter({
#     "http": applicationhttp,
#     "websocket": URLRouter(websocket_urlpatterns),
# })

application = ProtocolTypeRouter({
    "http": testapp,
    "websocket": AllowedHostsOriginValidator(
        AuthMiddlewareStack(
            URLRouter(websocket_urlpatterns),
        )
    ),

})

What versions of Python, Django, and Channels are you using?
(Also, it might be helpful if you posted the complete command-line/error message combination in case there’s another error present.)

Traceback (most recent call last):
  File "C:\Users\Abder-Rahmanhe\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\channels\routing.py", line 28, in get_default_application
    module = importlib.import_module(path)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2288.0_x64__qbz5n2kfra8p0\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 688, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 883, in exec_module
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "C:\Users\Abder-Rahmanhe\Desktop\Django\Orderline APP\OrderLineApp\OrderLine1\asgi.py", line 15, in <module>
    from channels.auth import AuthMiddlewareStack
  File "C:\Users\Abder-Rahmanhe\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\channels\auth.py", line 15, in <module>
    from django.utils.translation import LANGUAGE_SESSION_KEY
ImportError: cannot import name 'LANGUAGE_SESSION_KEY' from 'django.utils.translation' (C:\Users\Abder-Rahmanhe\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\utils\translation\__init__.py)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2288.0_x64__qbz5n2kfra8p0\lib\threading.py", line 1016, in _bootstrap_inner
    self.run()
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2288.0_x64__qbz5n2kfra8p0\lib\threading.py", line 953, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\Abder-Rahmanhe\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\utils\autoreload.py", line 64, in wrapper    
    application=self.get_application(options),
  File "C:\Users\Abder-Rahmanhe\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\channels\management\commands\runserver.py", line 132, in get_application
    return StaticFilesWrapper(get_default_application())
  File "C:\Users\Abder-Rahmanhe\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\channels\routing.py", line 30, in get_default_application
    raise ImproperlyConfigured("Cannot import ASGI_APPLICATION module %r" % path)
django.core.exceptions.ImproperlyConfigured: Cannot import ASGI_APPLICATION module 'OrderLine1.asgi'
channels==3.0.1
channels-redis==2.4.2

This is the root error.

The error you’ve been trying to chase down here is one caused by the above message.

What version of Django are you using?