Package: channelsrestframework
NoteThis repo is cloned fromchannels-apiChannels APIChannels API exposes a RESTful Streaming API over WebSockets using
channels. It provides aResourceBindingwhich is comparable to Django
Rest Framework’sModelViewSet. It is based on DRF serializer
classes.It requires Python 3, Django 1.8, and Django Rest Framework 3.0Table of ContentsGetting StartedResourceBindingSubscriptionsErrorsRoadmapHow does it work?The API builds on top of channels’WebsocketBindingclass. It works by having
the client send astreamandpayloadparameters. This allows
us to route messages to different streams (or resources) for a particular
action. SoPOST /userwould have a message that looks like the followingvarmsg={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 StartedThis tutorial assumes you’re familiar with channels and have completed
theGetting
StartedAddchannels_frameworkto requirements.txtpipinstallchannels_frameworkAddchannels_frameworktoINSTALLED_APPSINSTALLED_APPS=('rest_framework','channels','channels_framework')Add aWebsocketDemultiplexerto yourchannel_routing# proj/routing.pyfromchannels.generic.websocketsimportWebsocketDemultiplexerfromchannels.routingimportroute_classclassAPIDemultiplexer(WebsocketDemultiplexer):mapping={'questions':'questions_channel'}channel_routing=[route_class(APIDemultiplexer)]Add your first resource binding# polls/bindings.pyfromchannels_framework.bindingsimportResourceBindingfrom.modelsimportQuestionfrom.serializersimportQuestionSerializerclassQuestionBinding(ResourceBinding):model=Questionstream="questions"serializer_class=QuestionSerializerqueryset=Question.objects.all()# proj/routing.pyfromchannels.routingimportroute_class,routefrompolls.bindingsimportQuestionBindingchannel_routing=[route_class(APIDemultiplexer),route("question_channel",QuestionBinding.consumer)]That’s it. You can now make REST WebSocket requests to the server.varws=newWebSocket("ws://"+window.location.host+"/")ws.onmessage=function(e){console.log(e.data)}varmsg={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:200request_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 whenDEBUG=TRUE.# proj/urls.pyfromdjango.conf.urlsimportincludeurlpatterns=[url(r'^channels-api/',include('channels_framework.urls'))]ResourceBindingBy default theResourceBindingimplements the following REST methods:createretrieveupdatelistdeletesubscribeSee the test suite for usage examples for each method.List PaginationPagination is handled bydjango.core.paginator.PaginatorYou can configure theDEFAULT_PAGE_SIZEby overriding the settings.# settings.pychannels_framework={'DEFAULT_PAGE_SIZE':25}SubscriptionsSubscriptions are a way to programmatically receive updates
from the server whenever a resource is created, updated, or deletedBy default channels-api has implemented the following subscriptionscreate a Resourceupdate any Resourceupdate this Resourcedelete any Resourcedelete this ResourceTo subscribe to a particular event just use the subscribe action
with the parameters to filter// get an event when any question is updatedvarmsg={stream:"questions",payload:{action:"subscribe",data:{action:"update"}}}// get an event when question(1) is updatedvarmsg={stream:"questions",payload:{action:"subscribe"data:{action:"update",pk:"1"}}}