fanout / django-eventstream

Server-Sent Events for Django
MIT License
638 stars 84 forks source link

Django rest framework router register eventstream #138

Closed enzofrnt closed 3 months ago

enzofrnt commented 3 months ago

I recommand to use the following class and following registering to use django-eventstream with a viewset and a router.

If you want to hard code the used channels :

class EventsViewSet(ViewSet):
    """
    A ViewSet to encapsulate the function-based view 'events'.
    """

    def list(self, request, *args, **kwargs):
        """
        Redirects requests to the 'events' function, passing 'channels' as kwargs.
        """
        # Define 'channels' statically for this example
        channels = ['chat1', 'admin']

        # Add 'channels' to kwargs
        kwargs['channels'] = channels

        # Convert the DRF `request` object to Django's `HttpRequest` object if necessary
        django_request = request._request if hasattr(request, '_request') else request

        # Directly call the 'events' function with the updated kwargs
        return events(django_request, **kwargs)

And with channels choice send from the request :

class EventsViewSet(ViewSet):
    """
    A ViewSet to encapsulate the function-based view 'events'.
    """

    def list(self, request, *args, **kwargs):
        """
        Redirects requests to the 'events' function, dynamically extracting 'channels' from request parameters.
        """
        # Extract 'channels' from query parameters. 
        # It assumes 'channels' is passed as a comma-separated list (e.g., "channels=parser,scanner").
        channels_param = request.query_params.get('channels', '')
        if channels_param:
            channels = channels_param.split(',')
        else:
            channels = []  # Default to an empty list if no 'channels' parameter is provided

        # Add 'channels' to kwargs for passing to the events function
        kwargs['channels'] = channels

        # Convert the DRF `request` object to Django's `HttpRequest` object if necessary
        django_request = request._request if hasattr(request, '_request') else request

        # Directly call the 'events' function with the updated kwargs
        return events(django_request, **kwargs)

Maybe add this to the documentation ?

enzofrnt commented 3 months ago

The goal will be to add native support for viewset… Or documentation about it.

enzofrnt commented 3 months ago

@jkarneges Hi, I've come to realize that the modifications I'm implementing in this plugin require the use of Django REST Framework. In your opinion, would it be preferable to maintain two versions of the plugin—one tailored for Django REST Framework and another for setups without it—or should we integrate the Django REST Framework dependency directly into the existing module? Please let me know your thoughts, and I will adjust my proposal accordingly.