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.
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
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!")