SlideShare a Scribd company logo
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

Learn REST API with Python
Learn REST API with PythonLearn REST API with Python
Learn REST API with Python
Larry Cai
 

What's hot (20)

Learn REST API with Python
Learn REST API with PythonLearn REST API with Python
Learn REST API with Python
 
Huawei AC6508 Wireless Access Controller Datasheet.pdf
Huawei AC6508 Wireless Access Controller Datasheet.pdfHuawei AC6508 Wireless Access Controller Datasheet.pdf
Huawei AC6508 Wireless Access Controller Datasheet.pdf
 
Everything You Need to Know About HCL Notes 14
Everything You Need to Know About HCL Notes 14Everything You Need to Know About HCL Notes 14
Everything You Need to Know About HCL Notes 14
 
API for Beginners
API for BeginnersAPI for Beginners
API for Beginners
 
HTTP/3 for everyone
HTTP/3 for everyoneHTTP/3 for everyone
HTTP/3 for everyone
 
HTTP
HTTPHTTP
HTTP
 
HTML5 Real Time and WebSocket Code Lab (SFHTML5, GTUGSF)
HTML5 Real Time and WebSocket Code Lab (SFHTML5, GTUGSF)HTML5 Real Time and WebSocket Code Lab (SFHTML5, GTUGSF)
HTML5 Real Time and WebSocket Code Lab (SFHTML5, GTUGSF)
 
django Forms in a Web API World
django Forms in a Web API Worlddjango Forms in a Web API World
django Forms in a Web API World
 
Get Hands-On with NGINX and QUIC+HTTP/3
Get Hands-On with NGINX and QUIC+HTTP/3Get Hands-On with NGINX and QUIC+HTTP/3
Get Hands-On with NGINX and QUIC+HTTP/3
 
Kamailio - Secure Communication
Kamailio - Secure CommunicationKamailio - Secure Communication
Kamailio - Secure Communication
 
Using NGINX as an Effective and Highly Available Content Cache
Using NGINX as an Effective and Highly Available Content CacheUsing NGINX as an Effective and Highly Available Content Cache
Using NGINX as an Effective and Highly Available Content Cache
 
Primeiros passos com a API do Zabbix - Webinar JLCP
Primeiros passos com a API do Zabbix - Webinar JLCPPrimeiros passos com a API do Zabbix - Webinar JLCP
Primeiros passos com a API do Zabbix - Webinar JLCP
 
HTTP Presentation
HTTP Presentation HTTP Presentation
HTTP Presentation
 
Http Introduction
Http IntroductionHttp Introduction
Http Introduction
 
HTTP fundamentals for developers
HTTP fundamentals for developersHTTP fundamentals for developers
HTTP fundamentals for developers
 
Advanced Git Tutorial
Advanced Git TutorialAdvanced Git Tutorial
Advanced Git Tutorial
 
Scaling WebRTC applications with Janus
Scaling WebRTC applications with JanusScaling WebRTC applications with Janus
Scaling WebRTC applications with Janus
 
Simulcast/SVC @ IIT-RTC 2019
Simulcast/SVC @ IIT-RTC 2019Simulcast/SVC @ IIT-RTC 2019
Simulcast/SVC @ IIT-RTC 2019
 
Git
GitGit
Git
 
HTTP/3
HTTP/3HTTP/3
HTTP/3
 

Viewers also liked

Viewers also liked (8)

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
 
Weave Your Microservices with Istio
Weave Your Microservices with IstioWeave Your Microservices with Istio
Weave Your Microservices with 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
 
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

State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
Bhaskar Mitra
 

Recently uploaded (20)

Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
Le nuove frontiere dell'AI nell'RPA con UiPath Autopilot™
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
Ransomware Mallox [EN].pdf
Ransomware         Mallox       [EN].pdfRansomware         Mallox       [EN].pdf
Ransomware Mallox [EN].pdf
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
Quantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsQuantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIs
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
КАТЕРИНА АБЗЯТОВА «Ефективне планування тестування ключові аспекти та практ...
КАТЕРИНА АБЗЯТОВА  «Ефективне планування тестування  ключові аспекти та практ...КАТЕРИНА АБЗЯТОВА  «Ефективне планування тестування  ключові аспекти та практ...
КАТЕРИНА АБЗЯТОВА «Ефективне планування тестування ключові аспекти та практ...
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 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