SlideShare a Scribd company logo
1 of 27
DJANGO CHANNELS
by Chew Kok Hoor kokhoor@solutionx.com.
About Me
 Also Director of Third Life Sdn. Bhd. – co-
developer of Mobile Marketing app for Businesses:
channels.io
 Web Applications - Django
 Mobile Apps backend - Django
 Point-of-Sales system (POS) - Django
 POS Device Connectors - Tornado.
Objective
 General overview of Channels
 Simple Example
 Scaling
What is Django Channels
“Channels is a project to make Django able to
handle more than just plain HTTP requests,
including WebSockets and HTTP2, as well as the
ability to run code after a response has been sent for
things like thumbnailing or background calculation.”
- http://channels.readthedocs.io/
Web Applications Activities /
Tasks
 Respond to request (GET, POST, …)
 Batch activities – slower tasks such as sending
email etc.
 Web Sockets
Python Frameworks / Libraries
 Respond to request (GET, POST, …)
 DJANGO
 Batch processing
 Celery, RQ, Gearman
 Web Sockets
 Flask, Tornado, Twisted
Vanilla Django
 Built around
Requests and
Responses
 Incompatible with
WebSockets.
Source:
https://blog.heroku.com/in_deep_with_django_channels_the_future_of_real_time_apps_in_django
Django Channels
 Addition of Async Interface
Server and Channels Layer
(Asynchronous Server
Gateway Interface)
 Worker Processes able to
handle Request / Response,
WebSocket and Background
Processes
 Existing concepts of views still
applies to Request &
Response
Source:
https://blog.heroku.com/in_deep_with_django_channels_the_future_of_real_time_apps_in_django
Side-by-Side
Vanilla Django Django
Daphne
In-Memory /
IPC / Redis
Why Django Channels?
 Pros
 Consolidate and centralize configuration and program code
 Easier re-use
 Asynchronous in nature but you still write synchronous code
– no yields, monkey-patching etc.
 In one big package, so improvements and directions can be
aligned.
 Cons
 Celery more complete compared to what Channels has to
offer
 Channels Layer choices still limited (IPC, Redis)
 Stuck in an Opinionated Framework
Example app for Django
Channels
 Borrowed code from
https://github.com/jacobian/chann
els-example/
 Covers:
 Traditional Request Response
(TemplateViews)
 Batch (fake email sending)
 WebSockets
Getting Started
 pip install channels
 pip install asgi_redis
 settings.py
CHANNEL_LAYERS = {
"default": {
"BACKEND": "asgi_redis.RedisChannelLayer",
"CONFIG": {
"hosts": [‘redis://localhost:6379’],
},
"ROUTING": "main.routing.default_routing",
}
}
Routing
routing.py
from channels.routing import route
from . import consumers
from . import batch
channel_routing = [
route('send-invite', batch.send_invite),
]
chat_routing = [
route('websocket.connect', consumers.ws_connect),
route('websocket.receive', consumers.ws_receive),
route('websocket.disconnect', consumers.ws_disconnect),
]
default_routing = channel_routing + chat_routing
asgi.py
import os
import channels.asgi
os.environ.setdefault("DJANGO_SETTINGS_MODULE",
"channels_test.settings")
channel_layer = channels.asgi.get_channel_layer()
Excerpt of views.py
class InviteView(TemplateView):
template_name = "invite.html"
def post(self, request, *args, **kwargs):
context = self.get_context_data()
REQUEST_DATA = request.POST
email = REQUEST_DATA.get('email')
if not email:
context['error'] = "Email field not provided"
return super(TemplateView, self).render_to_response(context)
data = {
'email': email,
'message': u"Hi, %s, you're invited!! Check us out at http://www.solutionx.com.my for more
info!" % email
}
Channel('send-invite', alias=settings.BATCH_CHANNEL_LAYER).send(data)
context['message'] = "We're sending the invite for you!"
return super(TemplateView, self).render_to_response(context)
batch.py
import logging
import time
logger = logging.getLogger('email')
def send_invite(message):
logger.info("We receive a request to send email to: " +
message.get('email'))
logger.info("Message: " + message.get('message'))
time.sleep(10)
logger.info("Email sent successfully!")
Running the processes
1. redis-server
2. daphne main.asgi:channel_layer
3. python manage.py runworker
Scaling
1. Add more workers
1. Redis sharding (seems to still require further
testing)
2. Multiple Channel Layers
Scaling
1. Add more workers
- python manage.py runworker
Scaling (2)
1. Redis sharding (still requires further testing)
Redis Sharding
CHANNEL_LAYERS = {
"default": {
"BACKEND": "asgi_redis.RedisChannelLayer",
"CONFIG": {
"hosts": ['redis://localhost:6379',
'redis://localhost:7777'],
},
"ROUTING": "main.routing.default_routing",
}
}
Running the processes
(Sharding)
1. redis-server
2. redis-server --port 7777
3. daphne main.asgi_sharding:channel_layer
4. python manage.py runworker --settings
channels_test.settings_sharding
5. python manage.py runworker --settings
channels_test.settings_sharding
Scaling (3)
1. Multiple Channel Layers
Multiple Channel Layers
CHANNEL_LAYERS = {
"test": {
"BACKEND": "asgi_redis.RedisChannelLayer",
"CONFIG": {
"hosts": [‘redis://localhost:6379’],
},
"ROUTING": "main.routing.channel_routing",
},
"chat": {
"BACKEND": "asgi_redis.RedisChannelLayer",
"CONFIG": {
"hosts": [`redis://localhost:7777’],
},
"ROUTING": "main.routing.chat_routing",
},
}
Running the processes (Multiple
Channel Layers)
1. redis-server
2. redis-server --port 7777
3. daphne -b 0.0.0.0 -p 8000 main.asgi_test:channel_layer
4. python manage.py runworker --settings
channels_test.settings_prod --layer test --only-channels
http.request
5. python manage.py runworker --settings
channels_test.settings_prod --layer test --only-channels
send-invite
6. daphne -b 0.0.0.0 -p 8080 main.asgi_chat:channel_layer
7. python manage.py runworker --settings
channels_test.settings_prod --layer chat
Wrapping Up
 New but promising
 Hopefully makes writing complex web apps
easier
 References:
 https://blog.heroku.com/in_deep_with_django_channe
ls_the_future_of_real_time_apps_in_django
 http://www.machinalis.com/blog/introduction-to-
django-channels/
 http://channels.readthedocs.io/en/latest/
 https://github.com/andrewgodwin/channels
Q&A
Chew Kok Hoor
Director
kokhoor@solutionx.com.my
iOS
channels.io App (not related to Django Channels, name
similarity purely co-incidental)
http://channels.io
Android

More Related Content

What's hot

Border Gateway Protocol
Border Gateway ProtocolBorder Gateway Protocol
Border Gateway Protocol
Kashif Latif
 

What's hot (20)

Integration between Filebeat and logstash
Integration between Filebeat and logstash Integration between Filebeat and logstash
Integration between Filebeat and logstash
 
Data ingestion and distribution with apache NiFi
Data ingestion and distribution with apache NiFiData ingestion and distribution with apache NiFi
Data ingestion and distribution with apache NiFi
 
Easy Cloud Native Transformation with Nomad
Easy Cloud Native Transformation with NomadEasy Cloud Native Transformation with Nomad
Easy Cloud Native Transformation with Nomad
 
Firewall(linux)
Firewall(linux)Firewall(linux)
Firewall(linux)
 
Playlist Recommendations @ Spotify
Playlist Recommendations @ SpotifyPlaylist Recommendations @ Spotify
Playlist Recommendations @ Spotify
 
VPN con RouterOS MikroTik PPTP Server y Client.pdf
VPN con RouterOS MikroTik PPTP Server y Client.pdfVPN con RouterOS MikroTik PPTP Server y Client.pdf
VPN con RouterOS MikroTik PPTP Server y Client.pdf
 
Segment Routing Technology Deep Dive and Advanced Use Cases
Segment Routing Technology Deep Dive and Advanced Use CasesSegment Routing Technology Deep Dive and Advanced Use Cases
Segment Routing Technology Deep Dive and Advanced Use Cases
 
Apache Unomi In Depth - ApacheCon EU 2015 Session
Apache Unomi In Depth - ApacheCon EU 2015 SessionApache Unomi In Depth - ApacheCon EU 2015 Session
Apache Unomi In Depth - ApacheCon EU 2015 Session
 
SIEM ÜRÜNLERİNİN KORELASYON ÖZELLİKLERİ NASIL KARŞILAŞTIRILIR?
SIEM ÜRÜNLERİNİN KORELASYON ÖZELLİKLERİ NASIL KARŞILAŞTIRILIR?SIEM ÜRÜNLERİNİN KORELASYON ÖZELLİKLERİ NASIL KARŞILAŞTIRILIR?
SIEM ÜRÜNLERİNİN KORELASYON ÖZELLİKLERİ NASIL KARŞILAŞTIRILIR?
 
Ultimate Guide to Funnel Optimization
Ultimate Guide to Funnel OptimizationUltimate Guide to Funnel Optimization
Ultimate Guide to Funnel Optimization
 
Testing como parte de la cultura DevOps
Testing como parte de la cultura DevOpsTesting como parte de la cultura DevOps
Testing como parte de la cultura DevOps
 
[DockerCon 2019] Hardening Docker daemon with Rootless mode
[DockerCon 2019] Hardening Docker daemon with Rootless mode[DockerCon 2019] Hardening Docker daemon with Rootless mode
[DockerCon 2019] Hardening Docker daemon with Rootless mode
 
Jitsi
JitsiJitsi
Jitsi
 
A/B testing in Firebase. Intermediate and advanced approach
A/B testing in Firebase. Intermediate and advanced approachA/B testing in Firebase. Intermediate and advanced approach
A/B testing in Firebase. Intermediate and advanced approach
 
Palo alto outline course | Mostafa El Lathy
Palo alto outline course | Mostafa El LathyPalo alto outline course | Mostafa El Lathy
Palo alto outline course | Mostafa El Lathy
 
Border Gateway Protocol
Border Gateway ProtocolBorder Gateway Protocol
Border Gateway Protocol
 
Ipv6
Ipv6Ipv6
Ipv6
 
State Machine Workflow: Esoteric Techniques & Patterns Everyone Should Buy pr...
State Machine Workflow: Esoteric Techniques & Patterns Everyone Should Buy pr...State Machine Workflow: Esoteric Techniques & Patterns Everyone Should Buy pr...
State Machine Workflow: Esoteric Techniques & Patterns Everyone Should Buy pr...
 
Introduction To Git For Version Control Architecture And Common Commands Comp...
Introduction To Git For Version Control Architecture And Common Commands Comp...Introduction To Git For Version Control Architecture And Common Commands Comp...
Introduction To Git For Version Control Architecture And Common Commands Comp...
 
IP Geolocation Demystified
IP Geolocation  DemystifiedIP Geolocation  Demystified
IP Geolocation Demystified
 

Viewers also liked

Viewers also liked (9)

Async Tasks with Django Channels
Async Tasks with Django ChannelsAsync Tasks with Django Channels
Async Tasks with Django Channels
 
Real time web_apps_pycon2012-v1
Real time web_apps_pycon2012-v1Real time web_apps_pycon2012-v1
Real time web_apps_pycon2012-v1
 
Django channels
Django channelsDjango channels
Django channels
 
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
 
Django Introduction & Tutorial
Django Introduction & TutorialDjango Introduction & Tutorial
Django Introduction & Tutorial
 
The State of WebSockets in Django
The State of WebSockets in DjangoThe State of WebSockets in Django
The State of WebSockets in Django
 
Django Celery
Django Celery Django Celery
Django Celery
 
Advanced Django Forms Usage
Advanced Django Forms UsageAdvanced Django Forms Usage
Advanced Django Forms Usage
 
Real-Time Django
Real-Time DjangoReal-Time Django
Real-Time Django
 

Similar to PyConMY 2016 Django Channels

Rails 3: Dashing to the Finish
Rails 3: Dashing to the FinishRails 3: Dashing to the Finish
Rails 3: Dashing to the Finish
Yehuda Katz
 
[CB16] Esoteric Web Application Vulnerabilities by Andrés Riancho
[CB16] Esoteric Web Application Vulnerabilities by Andrés Riancho[CB16] Esoteric Web Application Vulnerabilities by Andrés Riancho
[CB16] Esoteric Web Application Vulnerabilities by Andrés Riancho
CODE BLUE
 
Rails 3 overview
Rails 3 overviewRails 3 overview
Rails 3 overview
Yehuda Katz
 

Similar to PyConMY 2016 Django Channels (20)

Pyramid Lighter/Faster/Better web apps
Pyramid Lighter/Faster/Better web appsPyramid Lighter/Faster/Better web apps
Pyramid Lighter/Faster/Better web apps
 
Denys Serhiienko "ASGI in depth"
Denys Serhiienko "ASGI in depth"Denys Serhiienko "ASGI in depth"
Denys Serhiienko "ASGI in depth"
 
Camel as a_glue
Camel as a_glueCamel as a_glue
Camel as a_glue
 
Rails missing features
Rails missing featuresRails missing features
Rails missing features
 
Python Code Camp for Professionals 3/4
Python Code Camp for Professionals 3/4Python Code Camp for Professionals 3/4
Python Code Camp for Professionals 3/4
 
Nodejs.meetup
Nodejs.meetupNodejs.meetup
Nodejs.meetup
 
The rise of Polymer and Web Components (Kostas Karolemeas) - GreeceJS #17
The rise of Polymer and Web Components (Kostas Karolemeas) - GreeceJS #17The rise of Polymer and Web Components (Kostas Karolemeas) - GreeceJS #17
The rise of Polymer and Web Components (Kostas Karolemeas) - GreeceJS #17
 
Google Polymer Framework
Google Polymer FrameworkGoogle Polymer Framework
Google Polymer Framework
 
SFScon 2020 - Nikola Milisavljevic - BASE - Python REST API framework
SFScon 2020 - Nikola Milisavljevic - BASE - Python REST API frameworkSFScon 2020 - Nikola Milisavljevic - BASE - Python REST API framework
SFScon 2020 - Nikola Milisavljevic - BASE - Python REST API framework
 
Rails 3: Dashing to the Finish
Rails 3: Dashing to the FinishRails 3: Dashing to the Finish
Rails 3: Dashing to the Finish
 
Codeigniter : Custom Routing - Manipulate Uri
Codeigniter : Custom Routing - Manipulate UriCodeigniter : Custom Routing - Manipulate Uri
Codeigniter : Custom Routing - Manipulate Uri
 
Building websites with Node.ACS
Building websites with Node.ACSBuilding websites with Node.ACS
Building websites with Node.ACS
 
Building websites with Node.ACS
Building websites with Node.ACSBuilding websites with Node.ACS
Building websites with Node.ACS
 
[CB16] Esoteric Web Application Vulnerabilities by Andrés Riancho
[CB16] Esoteric Web Application Vulnerabilities by Andrés Riancho[CB16] Esoteric Web Application Vulnerabilities by Andrés Riancho
[CB16] Esoteric Web Application Vulnerabilities by Andrés Riancho
 
Rails 3 overview
Rails 3 overviewRails 3 overview
Rails 3 overview
 
112 portfpres.pdf
112 portfpres.pdf112 portfpres.pdf
112 portfpres.pdf
 
Ato2019 weave-services-istio
Ato2019 weave-services-istioAto2019 weave-services-istio
Ato2019 weave-services-istio
 
All Things Open 2019 weave-services-istio
All Things Open 2019 weave-services-istioAll Things Open 2019 weave-services-istio
All Things Open 2019 weave-services-istio
 
Weave Your Microservices with Istio
Weave Your Microservices with IstioWeave Your Microservices with Istio
Weave Your Microservices with Istio
 
Monitoring a Kubernetes-backed microservice architecture with Prometheus
Monitoring a Kubernetes-backed microservice architecture with PrometheusMonitoring a Kubernetes-backed microservice architecture with Prometheus
Monitoring a Kubernetes-backed microservice architecture with Prometheus
 

Recently uploaded

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 

Recently uploaded (20)

EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 

PyConMY 2016 Django Channels

  • 1. DJANGO CHANNELS by Chew Kok Hoor kokhoor@solutionx.com.
  • 2. About Me  Also Director of Third Life Sdn. Bhd. – co- developer of Mobile Marketing app for Businesses: channels.io  Web Applications - Django  Mobile Apps backend - Django  Point-of-Sales system (POS) - Django  POS Device Connectors - Tornado.
  • 3. Objective  General overview of Channels  Simple Example  Scaling
  • 4. What is Django Channels “Channels is a project to make Django able to handle more than just plain HTTP requests, including WebSockets and HTTP2, as well as the ability to run code after a response has been sent for things like thumbnailing or background calculation.” - http://channels.readthedocs.io/
  • 5. Web Applications Activities / Tasks  Respond to request (GET, POST, …)  Batch activities – slower tasks such as sending email etc.  Web Sockets
  • 6. Python Frameworks / Libraries  Respond to request (GET, POST, …)  DJANGO  Batch processing  Celery, RQ, Gearman  Web Sockets  Flask, Tornado, Twisted
  • 7. Vanilla Django  Built around Requests and Responses  Incompatible with WebSockets. Source: https://blog.heroku.com/in_deep_with_django_channels_the_future_of_real_time_apps_in_django
  • 8. Django Channels  Addition of Async Interface Server and Channels Layer (Asynchronous Server Gateway Interface)  Worker Processes able to handle Request / Response, WebSocket and Background Processes  Existing concepts of views still applies to Request & Response Source: https://blog.heroku.com/in_deep_with_django_channels_the_future_of_real_time_apps_in_django
  • 10. Why Django Channels?  Pros  Consolidate and centralize configuration and program code  Easier re-use  Asynchronous in nature but you still write synchronous code – no yields, monkey-patching etc.  In one big package, so improvements and directions can be aligned.  Cons  Celery more complete compared to what Channels has to offer  Channels Layer choices still limited (IPC, Redis)  Stuck in an Opinionated Framework
  • 11. Example app for Django Channels  Borrowed code from https://github.com/jacobian/chann els-example/  Covers:  Traditional Request Response (TemplateViews)  Batch (fake email sending)  WebSockets
  • 12. Getting Started  pip install channels  pip install asgi_redis  settings.py CHANNEL_LAYERS = { "default": { "BACKEND": "asgi_redis.RedisChannelLayer", "CONFIG": { "hosts": [‘redis://localhost:6379’], }, "ROUTING": "main.routing.default_routing", } }
  • 13. Routing routing.py from channels.routing import route from . import consumers from . import batch channel_routing = [ route('send-invite', batch.send_invite), ] chat_routing = [ route('websocket.connect', consumers.ws_connect), route('websocket.receive', consumers.ws_receive), route('websocket.disconnect', consumers.ws_disconnect), ] default_routing = channel_routing + chat_routing
  • 15. Excerpt of views.py class InviteView(TemplateView): template_name = "invite.html" def post(self, request, *args, **kwargs): context = self.get_context_data() REQUEST_DATA = request.POST email = REQUEST_DATA.get('email') if not email: context['error'] = "Email field not provided" return super(TemplateView, self).render_to_response(context) data = { 'email': email, 'message': u"Hi, %s, you're invited!! Check us out at http://www.solutionx.com.my for more info!" % email } Channel('send-invite', alias=settings.BATCH_CHANNEL_LAYER).send(data) context['message'] = "We're sending the invite for you!" return super(TemplateView, self).render_to_response(context)
  • 16. batch.py import logging import time logger = logging.getLogger('email') def send_invite(message): logger.info("We receive a request to send email to: " + message.get('email')) logger.info("Message: " + message.get('message')) time.sleep(10) logger.info("Email sent successfully!")
  • 17. Running the processes 1. redis-server 2. daphne main.asgi:channel_layer 3. python manage.py runworker
  • 18. Scaling 1. Add more workers 1. Redis sharding (seems to still require further testing) 2. Multiple Channel Layers
  • 19. Scaling 1. Add more workers - python manage.py runworker
  • 20. Scaling (2) 1. Redis sharding (still requires further testing)
  • 21. Redis Sharding CHANNEL_LAYERS = { "default": { "BACKEND": "asgi_redis.RedisChannelLayer", "CONFIG": { "hosts": ['redis://localhost:6379', 'redis://localhost:7777'], }, "ROUTING": "main.routing.default_routing", } }
  • 22. Running the processes (Sharding) 1. redis-server 2. redis-server --port 7777 3. daphne main.asgi_sharding:channel_layer 4. python manage.py runworker --settings channels_test.settings_sharding 5. python manage.py runworker --settings channels_test.settings_sharding
  • 23. Scaling (3) 1. Multiple Channel Layers
  • 24. Multiple Channel Layers CHANNEL_LAYERS = { "test": { "BACKEND": "asgi_redis.RedisChannelLayer", "CONFIG": { "hosts": [‘redis://localhost:6379’], }, "ROUTING": "main.routing.channel_routing", }, "chat": { "BACKEND": "asgi_redis.RedisChannelLayer", "CONFIG": { "hosts": [`redis://localhost:7777’], }, "ROUTING": "main.routing.chat_routing", }, }
  • 25. Running the processes (Multiple Channel Layers) 1. redis-server 2. redis-server --port 7777 3. daphne -b 0.0.0.0 -p 8000 main.asgi_test:channel_layer 4. python manage.py runworker --settings channels_test.settings_prod --layer test --only-channels http.request 5. python manage.py runworker --settings channels_test.settings_prod --layer test --only-channels send-invite 6. daphne -b 0.0.0.0 -p 8080 main.asgi_chat:channel_layer 7. python manage.py runworker --settings channels_test.settings_prod --layer chat
  • 26. Wrapping Up  New but promising  Hopefully makes writing complex web apps easier  References:  https://blog.heroku.com/in_deep_with_django_channe ls_the_future_of_real_time_apps_in_django  http://www.machinalis.com/blog/introduction-to- django-channels/  http://channels.readthedocs.io/en/latest/  https://github.com/andrewgodwin/channels
  • 27. Q&A Chew Kok Hoor Director kokhoor@solutionx.com.my iOS channels.io App (not related to Django Channels, name similarity purely co-incidental) http://channels.io Android