Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
Django and this thing called Channels
Search
Sponsored
·
Ship Features Fearlessly
Turn features on and off without deploys. Used by thousands of Ruby developers.
→
Andrew Godwin
March 09, 2016
Programming
780
1
Share
Django and this thing called Channels
A talk I gave at Python SF Meetup, March 2016.
Andrew Godwin
March 09, 2016
More Decks by Andrew Godwin
See All by Andrew Godwin
Reconciling Everything
andrewgodwin
1
380
Django Through The Years
andrewgodwin
0
300
Writing Maintainable Software At Scale
andrewgodwin
0
510
A Newcomer's Guide To Airflow's Architecture
andrewgodwin
0
400
Async, Python, and the Future
andrewgodwin
2
720
How To Break Django: With Async
andrewgodwin
1
790
Taking Django's ORM Async
andrewgodwin
0
790
The Long Road To Asynchrony
andrewgodwin
0
750
The Scientist & The Engineer
andrewgodwin
1
830
Other Decks in Programming
See All in Programming
今こそ押さえておきたい アマゾンウェブサービス(AWS)の データベースの基礎 おもクラ #6版
satoshi256kbyte
1
240
Kubernetes上でAgentを動かすための最新動向と押さえるべき概念まとめ
sotamaki0421
3
480
Linux Kernelの1文字のミスで 権限昇格ができた話
rqda
0
2.3k
Coding at the Speed of Thought: The New Era of Symfony Docker
dunglas
0
4.8k
Vibe NLP for Applied NLP
inesmontani
PRO
0
310
Redox OS でのネームスペース管理と chroot の実現
isanethen
0
570
L’IA au service des devs : Anatomie d'un assistant de Code Review
toham
0
220
How Swift's Type System Guides AI Agents
koher
0
210
ドメインイベントでビジネスロジックを解きほぐす #phpcon_odawara
kajitack
2
130
アーキテクチャモダナイゼーションとは何か
nwiizo
17
4.8k
事業会社でのセキュリティ長期インターンについて
masachikaura
0
240
飯MCP
yusukebe
0
500
Featured
See All Featured
実際に使うSQLの書き方 徹底解説 / pgcon21j-tutorial
soudai
PRO
199
73k
GitHub's CSS Performance
jonrohan
1032
470k
SEO for Brand Visibility & Recognition
aleyda
0
4.5k
Discover your Explorer Soul
emna__ayadi
2
1.1k
HDC tutorial
michielstock
1
610
Responsive Adventures: Dirty Tricks From The Dark Corners of Front-End
smashingmag
254
22k
Test your architecture with Archunit
thirion
1
2.2k
No one is an island. Learnings from fostering a developers community.
thoeni
21
3.7k
Visual Storytelling: How to be a Superhuman Communicator
reverentgeek
2
500
A brief & incomplete history of UX Design for the World Wide Web: 1989–2019
jct
1
350
Testing 201, or: Great Expectations
jmmastey
46
8.1k
Statistics for Hackers
jakevdp
799
230k
Transcript
Andrew Godwin @andrewgodwin DJANGO and this thing called CHANNELS
Andrew Godwin Hi, I'm Django core developer Senior Software Engineer
at Likes complaining about networking
The Problem First: The Solution Then: The Future Finally:
The Problem WSGI ain't so bad
Browser HTTP Webserver Django WSGI View Handler
Browser WebSocket Webserver Django ???? ??? ????
Very hard to deadlock/cause errors Seems "Django-ish" DESIGN GOALS Scales
decently All works inside runserver
Browser WebSocket Webserver Django Channels Consumers Routing
Browser HTTP Webserver Django Channels Consumer Ch. Routing View URL
dispatch
The Solution A Series Of Channels
An ordered, first-in-first-out, at-most once queue with expiry and delivery
to only one listening consumer. Identified by a unique unicode name. WHAT IS A CHANNEL?
Producers Consumers Channel
There are standard channel names: STANDARDS Clients have unique response
channels: http.request websocket.connect websocket.receive !http.response.jaS4kSDj !websocket.send.Qwek120d
There are standard message formats: STANDARDS - HTTP request -
WebSocket close - HTTP response chunk But you can make your own channel names and formats too.
But how do we do this without making Django asynchronous?
Channels are network-transparent, and protocol termination is separate from business
logic process 1 process 2 protocol server worker server channels client socket
Async/cooperative code, but none of yours process 1 process 2
protocol server worker server channels client socket Your logic running synchronously worker server
For runserver, we run them as threads thread 1 thread
2 protocol server worker server channels client socket worker server thread 3 process 1
A view receives a request and sends a single response.
WHAT IS A CONSUMER? A consumer receives a message and sends zero or more messages.
EXAMPLE This echoes messages back: def ws_message(message): text = message.content['text']
reply = "You said: %s" % text message.reply_channel.send({ 'text': reply, })
EXAMPLE This notifies clients of new blog posts: def newpost(message):
for client in client_list: Channel(client).send({ 'text': message.content['id'], })
EXAMPLE But Channels has a better solution for that: #
Channel "websocket.connect" def connect(message): Group('liveblog').add( message.reply_channel) # Channel "new-liveblog" def newpost(message): Group('liveblog').send({ 'text': message.content['id'], })
EXAMPLE And you can send to channels from anywhere: class
LiveblogPost(models.Model): ... def save(self): ... Channel('new-liveblog').send({ 'id': str(self.id), })
EXAMPLE You can offload processing from views: def upload_image(request): ...
Channel('thumbnail').send({ 'id': str(image.id), }) return render(...)
EXAMPLE All the routing is set up like URLs: from
.consumers import ws_connect routing = { 'websocket.connect': ws_connect, 'websocket.receive': 'a.b.receive', 'thumbnail': 'images.consumers.thumb', }
EXAMPLE The HTTP channel just goes to the view system
by default. routing = { # This is actually the default 'http.request': 'channels.asgi.ViewConsumer', }
The Future What does it all mean?
WSGI
WSGI 2?
ASGI channels.readthedocs.org/en/latest/asgi.html
channel_layer.send(channel, message) channel_layer.receive_many(channels) + message standards + extensions (groups, stats)
Daphne HTTP/WebSocket ASGI server asgiref Memory layer, conformance suite, WSGI
adapters asgi_redis Redis-based channel layer
Raw ASGI app example: while True: channel, message = layer.receive_many(
["http.request"], block = True, ) if channel is None: continue layer.send( message['reply_channel'], { 'content': 'Hello World!', 'status': 200, } )
Django 1.10
Django 1.10 And 1.8, 1.9 as a third-party app
It's all optional. No need to change anything if you
don't want to use channels.
pip install channels channels.readthedocs.org
Thanks. Andrew Godwin @andrewgodwin