NilCoalescing / djangochannelsrestframework

A Rest-framework for websockets using Django channels-v4

Home Page:https://djangochannelsrestframework.readthedocs.io/en/latest/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Unable to access url parameter and response is NAN

Sirneij opened this issue · comments

I am building a kind of an analytic dashboard and needed to make some valuable data available via WebSocket for a real-time experience. The API was initially built using DRF's ModelViewset with the response data preprocessed using pandas. I basically have the following view:

class FrequencyViewSet(viewsets.ModelViewSet):
    serializer_class = FrequencySerilizer

    def list(self, request, *args, **kwargs):
        print(request.GET.get('meter_id'))
        frequency_data = Meter.history.filter(
            meter_id=request.GET.get('meter_id')).values_list('frequency', flat=True)
        df = read_frame(frequency_data, fieldnames=[
                        'frequency']).mean()
        res = [
            {
                'frequency': df[0]
            }
        ]
        return Response(res)

Using view_as_consumer, I tried to make it available via WebSocket like so:

websocket_urlpatterns = [
    re_path(r'^ws/meter/frequency/',
            view_as_consumer(consumers.FrequencyViewSet.as_view({'get': 'list'}))),
]

I connected to the WebSocket via wscat:

wscat -c "ws://localhost:8000/ws/meter/frequency/?meter_id=OND101"

And tried accessing the list action with the following:

{"action":"list", "request_id": 42}

I however got the following response:

{"errors": [], "data": [{"frequency": NaN}], "action": "list", "response_status": 200, "request_id": 42}

And on the log, the print statement I had there printed None to the console.

If I access the same endpoint via HTTP, without wrapping the viewset with view_as_consumer, I get the following response:

[
  {
    "frequency": 50.1
  }
]

Is there anything I am missing here?

  • OS: [e.g. Pop!_OS]
  • Version [e.g. 20.10]
  • Django (v. 4.0)

Good point, view_as_consumer currently does not pass through query params.

im not sure if it should since you might want to make multiple calls with the same WS connection open.

what I will add is the ability to include a query field in the ws message that will map to GET params.

How can this parameter be accessed in the view's method?

These values are written to the GET just like a query string so you should be able to use the same view code as you do for regular requests.

eg GET.get('meter_id') will read 42 from {"action":"list", "request_id": 42, 'query': {'meter_id': 42}}

I have one other change I want to finish off then I will do a new release but if you want to try this before the release you can get pip to install from master branch