SlideShare a Scribd company logo
1 of 27
Download to read offline
Django Channels
Andy Dai
andydai@gliacloud.com
Django awarded MOSS
Grant
We've been awarded $150,000 to help fund the
development of Channels, the initiative to rewrite the
core of Django to support (among other things)
WebSockets and background tasks, and to integrate
key parts of the Django REST Framework request/
response code into Django, such as content
negotiation.
Andrew Godwin
Concept of Channels
What is Channel
• First-in first-out queue
• At-Most-Once delivery
How to use Channels?
def my_consumer(message):
pass
channel_routing = {
"some-channel": "myapp.consumers.my_consumer",
}
Consumer function
Assign a channel to it in the channel
routing
Three separate layers
• Interface servers
• The channel backend
• The Workers
def my_consumer(message):
Channel(
message.reply_channel
).send(HttpResponse(“ok”))
channel_routing = {
"http.request": "myapp.consumers.my_consumer",
}
Groups
Channels can’t do
broadcast
redis_conn = redis.Redis("localhost", 6379)
@receiver(post_save, sender=BlogUpdate)
def send_update(sender, instance, **kwargs):
# Loop through all response channels and send the update
for reply_channel in redis_conn.smembers("readers"):
Channel(reply_channel).send(
id=instance.id,
content=instance.content,
)
# Connected to websocket.connect
def ws_connect(message):
# Add to reader set
redis_conn.sadd("readers", message.reply_channel.name)
With Groups
@receiver(post_save, sender=BlogUpdate)
def send_update(sender, instance, **kwargs):
Group("readers").send(
id=instance.id,
content=instance.content,
)
# Connected to websocket.connect and websocket.keepalive
def ws_connect(message):
# Add to reader group
Group("readers").add(message.reply_channel)
Let’s build a simple
chat room
pip install channels
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'channels',
)
Add ‘channels’
CHANNEL_BACKENDS = {
"default": {
"BACKEND": "channels.backends.redis_py.RedisChannelBackend",
"ROUTING": {
"websocket.connect": "chatroom.consumers.ws_add",
"websocket.keepalive": "chatroom.consumers.ws_add",
"websocket.receive": "chatroom.consumers.ws_message",
"websocket.disconnect": "chatroom.consumers.ws_disconnect",
},
},
}
CHANNEL_BACKENDS
16
from channels import Group
# Connected to websocket.connect and websocket.keepalive
def ws_add(message):
Group("chat").add(message.reply_channel)
# Connected to websocket.receive
def ws_message(message):
Group("chat").send(message.content)
# Connected to websocket.disconnect
def ws_disconnect(message):
Group("chat").discard(message.reply_channel)
consumers.py
pip install autobahn[twisted]
python manage.py runwsserver
Run WebSocket server
socket = new WebSocket("ws://127.0.0.1:9000/");
socket.onmessage = function(e) {
$('body').append(e.data+'<br>');
}
Added Some javascript
Persisting Data
from channels.decorators import channel_session
@channel_session
def ws_add(message):
room = message.content.get('path').strip('/')
message.channel_session['room'] = room
print "Room: {room} - ws_add".format(room=room)
Group("chat-%s" % room).add(
message.reply_channel
)
@channel_session
def ws_keepalive(message):
room = message.channel_session['room']
Group("chat-%s" % room).add(
message.reply_channel
)
Linearization
The linearize decorator. Any handler decorated with this will
use locking to ensure it does not run at the same time as
any other view with linearize on messages with the same
reply channel.
@linearize
@channel_session
def ws_add(message):
room = message.content.get('path').strip('/')
message.channel_session['room'] = room
print "Room: {room} - ws_add".format(room=room)
Group("chat-%s" % room).add(
message.reply_channel
)
@linearize
@channel_session
def ws_message(message):
Group("chat-%s" % message.channel_session['room']).send(
content=message.content
)
Authentication
from channels.auth import (
http_session_user, channel_session_user, transfer_user
)
@channel_session
@http_session_user
def ws_add(message):
# Copy user from HTTP to channel session
transfer_user(message.http_session, message.channel_session)
# Add them to the right group
Group(
"chat-%s" % message.user.username[0]
).add(message.reply_channel)
@channel_session_user
def ws_keepalive(message):
# Keep them in the right group
Group(
"chat-%s" % message.user.username[0]
).add(message.reply_channel)
DEMO
https://github.com/daikeren/
channel-example
Some Thoughts
• Channels will become a built-in feature for
Django 1.10
• Not stable yet
• Documentation…
• Read the source code!
Q&A

More Related Content

What's hot

Build your own PHP extension
Build your own PHP extensionBuild your own PHP extension
Build your own PHP extension
Võ Duy Tuấn
 
Operation Oriented Web Applications / Yokohama pm7
Operation Oriented Web Applications / Yokohama pm7Operation Oriented Web Applications / Yokohama pm7
Operation Oriented Web Applications / Yokohama pm7
Masahiro Nagano
 

What's hot (20)

[WSO2 Integration Summit Madrid 2019] Integration + Ballerina
[WSO2 Integration Summit Madrid 2019] Integration + Ballerina[WSO2 Integration Summit Madrid 2019] Integration + Ballerina
[WSO2 Integration Summit Madrid 2019] Integration + Ballerina
 
8 Minutes On Rack
8 Minutes On Rack8 Minutes On Rack
8 Minutes On Rack
 
BUILDING MODERN PYTHON WEB FRAMEWORKS USING FLASK WITH NEIL GREY
BUILDING MODERN PYTHON WEB FRAMEWORKS USING FLASK WITH NEIL GREYBUILDING MODERN PYTHON WEB FRAMEWORKS USING FLASK WITH NEIL GREY
BUILDING MODERN PYTHON WEB FRAMEWORKS USING FLASK WITH NEIL GREY
 
How we used ruby to build locaweb's cloud (http://presentations.pothix.com/ru...
How we used ruby to build locaweb's cloud (http://presentations.pothix.com/ru...How we used ruby to build locaweb's cloud (http://presentations.pothix.com/ru...
How we used ruby to build locaweb's cloud (http://presentations.pothix.com/ru...
 
Security in php
Security in phpSecurity in php
Security in php
 
Datagrids with Symfony 2, Backbone and Backgrid
Datagrids with Symfony 2, Backbone and BackgridDatagrids with Symfony 2, Backbone and Backgrid
Datagrids with Symfony 2, Backbone and Backgrid
 
Heavy Web Optimization: Backend
Heavy Web Optimization: BackendHeavy Web Optimization: Backend
Heavy Web Optimization: Backend
 
4 Basic PHP
4 Basic PHP4 Basic PHP
4 Basic PHP
 
Rack Middleware
Rack MiddlewareRack Middleware
Rack Middleware
 
Rack
RackRack
Rack
 
Varnish
VarnishVarnish
Varnish
 
Caching on the Edge
Caching on the EdgeCaching on the Edge
Caching on the Edge
 
içerik
içerikiçerik
içerik
 
Flask restfulservices
Flask restfulservicesFlask restfulservices
Flask restfulservices
 
Build your own PHP extension
Build your own PHP extensionBuild your own PHP extension
Build your own PHP extension
 
Rails missing features
Rails missing featuresRails missing features
Rails missing features
 
Introduction to Flask Micro Framework
Introduction to Flask Micro FrameworkIntroduction to Flask Micro Framework
Introduction to Flask Micro Framework
 
Operation Oriented Web Applications / Yokohama pm7
Operation Oriented Web Applications / Yokohama pm7Operation Oriented Web Applications / Yokohama pm7
Operation Oriented Web Applications / Yokohama pm7
 
Making the Most of HTTP In Your Apps
Making the Most of HTTP In Your AppsMaking the Most of HTTP In Your Apps
Making the Most of HTTP In Your Apps
 
Whats new in ASP.NET 4.0
Whats new in ASP.NET 4.0Whats new in ASP.NET 4.0
Whats new in ASP.NET 4.0
 

Viewers also liked

Django deployment and rpm+yum
Django deployment and rpm+yumDjango deployment and rpm+yum
Django deployment and rpm+yum
Walter Liu
 
Coderfaire Data Networking for Developers
Coderfaire Data Networking for DevelopersCoderfaire Data Networking for Developers
Coderfaire Data Networking for Developers
Jason Myers
 
Flask - Python microframework
Flask - Python microframeworkFlask - Python microframework
Flask - Python microframework
André Mayer
 

Viewers also liked (20)

Django deployment and rpm+yum
Django deployment and rpm+yumDjango deployment and rpm+yum
Django deployment and rpm+yum
 
Django for IoT: From hackathon to production (DjangoCon US)
Django for IoT: From hackathon to production (DjangoCon US)Django for IoT: From hackathon to production (DjangoCon US)
Django for IoT: From hackathon to production (DjangoCon US)
 
The future of async i/o in Python
The future of async i/o in PythonThe future of async i/o in Python
The future of async i/o in Python
 
Implementation of RSA Algorithm for Speech Data Encryption and Decryption
Implementation of RSA Algorithm for Speech Data Encryption and DecryptionImplementation of RSA Algorithm for Speech Data Encryption and Decryption
Implementation of RSA Algorithm for Speech Data Encryption and Decryption
 
Python, do you even async?
Python, do you even async?Python, do you even async?
Python, do you even async?
 
Django Introduction & Tutorial
Django Introduction & TutorialDjango Introduction & Tutorial
Django Introduction & Tutorial
 
Quattro passi tra le nuvole (e non scordate il paracadute)
Quattro passi tra le nuvole (e non scordate il paracadute)Quattro passi tra le nuvole (e non scordate il paracadute)
Quattro passi tra le nuvole (e non scordate il paracadute)
 
Diabetes and Me: My Journey So Far
Diabetes and Me: My Journey So FarDiabetes and Me: My Journey So Far
Diabetes and Me: My Journey So Far
 
Intro python-object-protocol
Intro python-object-protocolIntro python-object-protocol
Intro python-object-protocol
 
CoderDojo Romagna
CoderDojo RomagnaCoderDojo Romagna
CoderDojo Romagna
 
Hands on django part 1
Hands on django part 1Hands on django part 1
Hands on django part 1
 
Fuga dalla Comfort Zone
Fuga dalla Comfort ZoneFuga dalla Comfort Zone
Fuga dalla Comfort Zone
 
Filling the flask
Filling the flaskFilling the flask
Filling the flask
 
Python Static Analysis Tools
Python Static Analysis ToolsPython Static Analysis Tools
Python Static Analysis Tools
 
Online / Offline
Online / OfflineOnline / Offline
Online / Offline
 
Introduction to SQLAlchemy and Alembic Migrations
Introduction to SQLAlchemy and Alembic MigrationsIntroduction to SQLAlchemy and Alembic Migrations
Introduction to SQLAlchemy and Alembic Migrations
 
Coderfaire Data Networking for Developers
Coderfaire Data Networking for DevelopersCoderfaire Data Networking for Developers
Coderfaire Data Networking for Developers
 
The State of WebSockets in Django
The State of WebSockets in DjangoThe State of WebSockets in Django
The State of WebSockets in Django
 
RESTful Web API and MongoDB go for a pic nic
RESTful Web API and MongoDB go for a pic nicRESTful Web API and MongoDB go for a pic nic
RESTful Web API and MongoDB go for a pic nic
 
Flask - Python microframework
Flask - Python microframeworkFlask - Python microframework
Flask - Python microframework
 

Similar to Django channels

Pushing Datatothe Browserwith Comet Ajax W
Pushing Datatothe Browserwith Comet Ajax WPushing Datatothe Browserwith Comet Ajax W
Pushing Datatothe Browserwith Comet Ajax W
rajivmordani
 

Similar to Django channels (20)

Pushing Datatothe Browserwith Comet Ajax W
Pushing Datatothe Browserwith Comet Ajax WPushing Datatothe Browserwith Comet Ajax W
Pushing Datatothe Browserwith Comet Ajax W
 
Webservices
WebservicesWebservices
Webservices
 
Play Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and ScalaPlay Framework: async I/O with Java and Scala
Play Framework: async I/O with Java and Scala
 
How to perform debounce in react
How to perform debounce in reactHow to perform debounce in react
How to perform debounce in react
 
WebSockets in JEE 7
WebSockets in JEE 7WebSockets in JEE 7
WebSockets in JEE 7
 
SignalR
SignalRSignalR
SignalR
 
Servlets
ServletsServlets
Servlets
 
Web services in java
Web services in javaWeb services in java
Web services in java
 
Google Wave API: Now and Beyond
Google Wave API: Now and BeyondGoogle Wave API: Now and Beyond
Google Wave API: Now and Beyond
 
Major project report
Major project reportMajor project report
Major project report
 
GWT Web Socket and data serialization
GWT Web Socket and data serializationGWT Web Socket and data serialization
GWT Web Socket and data serialization
 
Scott Guthrie at Dot Net Startup meetup
Scott Guthrie at Dot Net Startup meetupScott Guthrie at Dot Net Startup meetup
Scott Guthrie at Dot Net Startup meetup
 
Google app engine by example
Google app engine by exampleGoogle app engine by example
Google app engine by example
 
Advanced #2 networking
Advanced #2   networkingAdvanced #2   networking
Advanced #2 networking
 
08 ajax
08 ajax08 ajax
08 ajax
 
Building interactivity with websockets
Building interactivity with websocketsBuilding interactivity with websockets
Building interactivity with websockets
 
Chat Room System using Java Swing
Chat Room System using Java SwingChat Room System using Java Swing
Chat Room System using Java Swing
 
Building apps with tuscany
Building apps with tuscanyBuilding apps with tuscany
Building apps with tuscany
 
Using WordPress as your application stack
Using WordPress as your application stackUsing WordPress as your application stack
Using WordPress as your application stack
 
The Future of Responsive Design Standards
The Future of Responsive Design StandardsThe Future of Responsive Design Standards
The Future of Responsive Design Standards
 

More from Andy Dai

Tradeoffs of replacing core components
Tradeoffs of replacing core componentsTradeoffs of replacing core components
Tradeoffs of replacing core components
Andy Dai
 
Boost your django admin with Grappelli
Boost your django admin with GrappelliBoost your django admin with Grappelli
Boost your django admin with Grappelli
Andy Dai
 

More from Andy Dai (17)

Grpc + python.key
Grpc + python.keyGrpc + python.key
Grpc + python.key
 
該怎麼樣(認真的)部署你的 Python Web 應用程式?
該怎麼樣(認真的)部署你的 Python Web 應用程式?該怎麼樣(認真的)部署你的 Python Web 應用程式?
該怎麼樣(認真的)部署你的 Python Web 應用程式?
 
Power UP your CLI
Power UP your CLIPower UP your CLI
Power UP your CLI
 
Search search search
Search search searchSearch search search
Search search search
 
Django Third party packages
Django Third party packagesDjango Third party packages
Django Third party packages
 
Practical django secuirty
Practical django secuirtyPractical django secuirty
Practical django secuirty
 
總之來講講 Search
總之來講講 Search總之來講講 Search
總之來講講 Search
 
Python web meetup 11 18
Python web meetup 11 18Python web meetup 11 18
Python web meetup 11 18
 
Django in heavy load environment
Django in heavy load environmentDjango in heavy load environment
Django in heavy load environment
 
電腦不只會幫你選土豆,還會幫你選新聞
電腦不只會幫你選土豆,還會幫你選新聞電腦不只會幫你選土豆,還會幫你選新聞
電腦不只會幫你選土豆,還會幫你選新聞
 
用 Python 打造你自己的 summly
用 Python 打造你自己的 summly用 Python 打造你自己的 summly
用 Python 打造你自己的 summly
 
Tradeoffs of replacing core components
Tradeoffs of replacing core componentsTradeoffs of replacing core components
Tradeoffs of replacing core components
 
ElastiCache
ElastiCacheElastiCache
ElastiCache
 
Dynamo db
Dynamo dbDynamo db
Dynamo db
 
Django deploy
Django deployDjango deploy
Django deploy
 
Build your own trello witihin 100 LOC (with Meteor)
Build your own trello witihin 100 LOC (with Meteor)Build your own trello witihin 100 LOC (with Meteor)
Build your own trello witihin 100 LOC (with Meteor)
 
Boost your django admin with Grappelli
Boost your django admin with GrappelliBoost your django admin with Grappelli
Boost your django admin with Grappelli
 

Recently uploaded

TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
anilsa9823
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 

Recently uploaded (20)

Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 

Django channels