Skip to main content

Note

This repo is cloned from channels-api

Channels API

https://travis-ci.org/linuxlewis/channels-api.svg?branch=master

Channels API exposes a RESTful Streaming API over WebSockets using channels. It provides a ResourceBinding which is comparable to Django Rest Framework’s ModelViewSet. It is based on DRF serializer classes.

It requires Python 3, Django 1.8, and Django Rest Framework 3.0

Table of Contents

How does it work?

The API builds on top of channels’ WebsocketBinding class. It works by having the client send a stream and payload parameters. This allows us to route messages to different streams (or resources) for a particular action. So POST /user would have a message that looks like the following

var msg = {
  stream: "users",
  payload: {
    action: "create",
    data: {
      email: "test@example.com",
      password: "password",
    }
  }
}

ws.send(JSON.stringify(msg))

Why?

You’re already using Django Rest Framework and want to expose similar logic over WebSockets.

WebSockets can publish updates to clients without a request. This is helpful when a resource can be edited by multiple users across many platforms.

Getting Started

This tutorial assumes you’re familiar with channels and have completed the Getting Started

  • Add channels_framework to requirements.txt

pip install channels_framework
  • Add channels_framework to INSTALLED_APPS

INSTALLED_APPS = (
    'rest_framework',
    'channels',
    'channels_framework'
)
  • Add a WebsocketDemultiplexer to your channel_routing

# proj/routing.py


from channels.generic.websockets import WebsocketDemultiplexer
from channels.routing import route_class

class APIDemultiplexer(WebsocketDemultiplexer):

    mapping = {
      'questions': 'questions_channel'
    }

channel_routing = [
    route_class(APIDemultiplexer)
]
  • Add your first resource binding

# polls/bindings.py

from channels_framework.bindings import ResourceBinding

from .models import Question
from .serializers import QuestionSerializer

class QuestionBinding(ResourceBinding):

    model = Question
    stream = "questions"
    serializer_class = QuestionSerializer
    queryset = Question.objects.all()


# proj/routing.py

from channels.routing import route_class, route

from polls.bindings import QuestionBinding

channel_routing = [
  route_class(APIDemultiplexer),
  route("question_channel", QuestionBinding.consumer)
]

That’s it. You can now make REST WebSocket requests to the server.

var ws = new WebSocket("ws://" + window.location.host + "/")

ws.onmessage = function(e){
    console.log(e.data)
}

var msg = {
  stream: "questions",
  payload: {
    action: "create",
    data: {
      question_text: "What is your favorite python package?"
    },
    request_id: "some-guid"
  }
}
ws.send(JSON.stringify(msg))
// response
{
  stream: "questions",
  payload: {
    action: "create",
    data: {
      id: "1",
      question_text: "What is your favorite python package"
    }
    errors: [],
    response_status: 200
    request_id: "some-guid"
  }
}
  • Add the channels debugger page (Optional)

This page is helpful to debug API requests from the browser and see the response. It is only designed to be used when DEBUG=TRUE.

# proj/urls.py

from django.conf.urls import include

    urlpatterns = [
        url(r'^channels-api/', include('channels_framework.urls'))
    ]

ResourceBinding

By default the ResourceBinding implements the following REST methods:

  • create

  • retrieve

  • update

  • list

  • delete

  • subscribe

See the test suite for usage examples for each method.

List Pagination

Pagination is handled by django.core.paginator.Paginator

You can configure the DEFAULT_PAGE_SIZE by overriding the settings.

# settings.py

channels_framework = {
  'DEFAULT_PAGE_SIZE': 25
}

Subscriptions

Subscriptions are a way to programmatically receive updates from the server whenever a resource is created, updated, or deleted

By default channels-api has implemented the following subscriptions

  • create a Resource

  • update any Resource

  • update this Resource

  • delete any Resource

  • delete this Resource

To subscribe to a particular event just use the subscribe action with the parameters to filter

// get an event when any question is updated

var msg = {
  stream: "questions",
  payload: {
    action: "subscribe",
    data: {
      action: "update"
    }
  }
}

// get an event when question(1) is updated
var msg = {
  stream: "questions",
  payload: {
    action: "subscribe"
    data: {
      action: "update",
      pk: "1"
    }
  }
}

Metadata

Release files for channelsrestframework 0.1.4

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for channelsrestframework 0.1.4
File Size Uploaded Provenance Actions
channelsrestframework-0.1.4.tar.gz 7.9 kB Without provenance Details for channelsrestframework-0.1.4.tar.gz

Release files / channelsrestframework-0.1.4.tar.gz

Download URL channelsrestframework-0.1.4.tar.gz
Size 7.9 kB
Tags Source
SHA-256 checksum
How to use checksums
a0cab242f0016cf1fb63eba486ce15b0dfb6e6ce08f1f76607fcb5f96e7d13e2
BLAKE2b-256 checksum
How to use checksums
33d85dffcaf4f0dda20bc8a1b37ef23c5356ac5e8bff2224e2f18e6699cb142f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No

Security for channelsrestframework 0.1.4

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.4 This release

1 release file No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page