GithubHelp home page GithubHelp logo

Comments (7)

J4CKVVH173 avatar J4CKVVH173 commented on July 17, 2024

image
I found out that my extra instances just ignored inside Consumer. Are there any other ways to pass extra instance inside ?

from channels.

carltongibson avatar carltongibson commented on July 17, 2024

You can only set attributes that exist on the class already. Set them as empty attributes on your class and then you can pass them as kwargs to as_asgi()

from channels.

J4CKVVH173 avatar J4CKVVH173 commented on July 17, 2024

You can only set attributes that exist on the class already. Set them as empty attributes on your class and then you can pass them as kwargs to as_asgi()

I did it of course
It looks like

class My consumer(AsyncWebSocketConsumer):

     extra_class = None

I've tried with None and without. With None I got error that extra class is none. Without None I wrote above

from channels.

carltongibson avatar carltongibson commented on July 17, 2024

You can see the code here:

def as_asgi(cls, **initkwargs):
"""
Return an ASGI v3 single callable that instantiates a consumer instance
per scope. Similar in purpose to Django's as_view().
initkwargs will be used to instantiate the consumer instance.
"""
async def app(scope, receive, send):
consumer = cls(**initkwargs)
return await consumer(scope, receive, send)
app.consumer_class = cls
app.consumer_initkwargs = initkwargs
# take name and docstring from class
functools.update_wrapper(app, cls, updated=())
return app

The initkwargs are passed to the consumer on line 93:

consumer = cls(**initkwargs)

So from the look of your example you'd need to assign that perhaps...

    self.extra_class = extra_class

? 🤔

from channels.

J4CKVVH173 avatar J4CKVVH173 commented on July 17, 2024

I didn't get it, could you please explain your idea ?

I can show you what I'm trying to do.

This is my urls.py

from uuid import UUID

from django.urls import path

from .classes import SessionConsumer
from .repositories import InMemorySessionRepository, WebsocketClientRepository

# Move to redis
session_map: dict[UUID, str] = {}
repositories = {
    'client_repository': WebsocketClientRepository(session_map),
    'session_repository': InMemorySessionRepository(session_map),
}



websocket_urlpatterns = [
    path('session/', SessionConsumer.as_asgi(**repositories)),
]

As you can see I have two extra exteranl class - WebsocketClientRepository, InMemorySessionRepository and I am trying to pass them inside SessionConsumer.

and this is SessionConsumer

from channels.generic.websocket import AsyncJsonWebsocketConsumer
from django.conf import settings
from core.application.classes import Viewer
from core.application.repositories import ClientRepository
from core.infrastructure.repositories import HttpPresenterRepository

from .repositories import SessionRepository


class SessionConsumer(AsyncJsonWebsocketConsumer):

    client_repository: ClientRepository
    session_repository: SessionRepository

    async def connect(self):
        await self.accept()

    async def receive_json(
        self, content: dict | None = None, bytes_data: bytes | None = None
    ):
        access_token = content['credentials']['access']
        presenter_repository = HttpPresenterRepository(
            access_token, settings.PRESENTER_URL
        )
        # Error here
        viewer = Viewer(self.client_repository, presenter_repository)  # noqa

And I can't get access to client repository inside SessionConsumer

This is the error.
AttributeError: 'SessionConsumer' object has no attribute 'client_repository'

If I use None as default state for client_repository I get error that self.cloent_session is None.

from channels.

J4CKVVH173 avatar J4CKVVH173 commented on July 17, 2024

And yeah I checked the source code and I got the idea that I can rewrite the __init__ method for chanels' consumer. But I want to use out of box solution if it's posible of course.

from channels.

J4CKVVH173 avatar J4CKVVH173 commented on July 17, 2024

My solution

from channels.generic.websocket import AsyncJsonWebsocketConsumer

class AsyncJsonConsumer(AsyncJsonWebsocketConsumer):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for key, value in kwargs.items():
            setattr(self, key, value)

from channels.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.