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
Andrew Godwin
March 09, 2016
Programming
1
750
Django and this thing called Channels
A talk I gave at Python SF Meetup, March 2016.
Andrew Godwin
March 09, 2016
Tweet
Share
More Decks by Andrew Godwin
See All by Andrew Godwin
Reconciling Everything
andrewgodwin
1
340
Django Through The Years
andrewgodwin
0
240
Writing Maintainable Software At Scale
andrewgodwin
0
470
A Newcomer's Guide To Airflow's Architecture
andrewgodwin
0
370
Async, Python, and the Future
andrewgodwin
2
690
How To Break Django: With Async
andrewgodwin
1
750
Taking Django's ORM Async
andrewgodwin
0
750
The Long Road To Asynchrony
andrewgodwin
0
690
The Scientist & The Engineer
andrewgodwin
1
790
Other Decks in Programming
See All in Programming
SidekiqでAIに商品説明を生成させてみた
akinko_0915
0
130
AI駆動開発カンファレンスAutumn2025 _AI駆動開発にはAI駆動品質保証
autifyhq
0
160
What’s Fair is FAIR: A Decentralised Future for WordPress Distribution
rmccue
0
170
KoogではじめるAIエージェント開発
hiroaki404
1
480
CSC509 Lecture 10
javiergs
PRO
0
170
仕様がそのままテストになる!Javaで始める振る舞い駆動開発
ohmori_yusuke
8
3.9k
퇴근 후 1억이 거래되는 서비스 만들기 | 내가 AI를 사용하는 방법
maryang
2
560
AsyncSequenceとAsyncStreamのプロポーザルを全部読む!!
s_shimotori
1
280
MCPサーバー「モディフィウス」で変更容易性の向上をスケールする / modifius
minodriven
8
1.5k
Kotlinで実装するCPU/GPU 「協調的」パフォーマンス管理
matuyuhi
0
400
Designing Repeatable Edits: The Architecture of . in Vim
satorunooshie
0
360
Building AI with AI
inesmontani
PRO
0
170
Featured
See All Featured
Optimising Largest Contentful Paint
csswizardry
37
3.5k
Context Engineering - Making Every Token Count
addyosmani
9
380
Chrome DevTools: State of the Union 2024 - Debugging React & Beyond
addyosmani
9
970
Bash Introduction
62gerente
615
210k
Leading Effective Engineering Teams in the AI Era
addyosmani
9
1.1k
10 Git Anti Patterns You Should be Aware of
lemiorhan
PRO
658
61k
Learning to Love Humans: Emotional Interface Design
aarron
274
41k
The MySQL Ecosystem @ GitHub 2015
samlambert
251
13k
Practical Tips for Bootstrapping Information Extraction Pipelines
honnibal
24
1.6k
Evolution of real-time – Irina Nazarova, EuRuKo, 2024
irinanazarova
9
1k
Sharpening the Axe: The Primacy of Toolmaking
bcantrill
46
2.6k
The World Runs on Bad Software
bkeepers
PRO
72
12k
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