django and real-time web
TRANSCRIPT
www.thorgate.euTHORGATE
PubSubPublish & Subscribe pattern Can use external services!
www.thorgate.euTHORGATE
# Create Pusher client pusher = Pusher( app_id='121933', key='f1ebb516981a3315e492', secret='SECRET' )
# ... and send the message! pusher.trigger('test_channel', 'showMessage', { 'message': message, })
Pusher server
www.thorgate.euTHORGATE
// Create Pusher client var pusher = new Pusher('f1ebb516981a3315e492');
// Subscribe to events on our channel var channel = pusher.subscribe('test_channel');
// And react to showMessage events channel.bind('showMessage', function(data) { alert(data.message); });
Pusher client
www.thorgate.euTHORGATE
$.post(SUBMIT_URL, { message: message, });
Messages from ClientsJust use AJAX requests – the
easiest way
www.thorgate.euTHORGATE
WebSockets• Standardized in 2011
• Fast, two-way connection
• Can use custom protocols
www.thorgate.euTHORGATE
WebSockets & Django
• asyncio and websockets library
• custom server process
www.thorgate.euTHORGATE
Server Code
@asyncio.coroutine def client_handler(websocket, uri): # Send a message yield from websocket.send("Hello world")
# Wait for a reply msg = yield from websocket.recv()
@asyncio.coroutine def client_handler(websocket, uri): # Send a message yield from websocket.send("Hello world")
# Wait for a reply msg = yield from websocket.recv()
www.thorgate.euTHORGATE
@asyncio.coroutine def client_handler(websocket, uri): # Send a message yield from websocket.send("Hello world")
# Read all messages while the socket is open while True: msg = yield from websocket.recv()
if msg is None: # Oops, the socket has closed return
# Fancy message processing print("got message:", msg)
Server Code
@asyncio.coroutine def client_handler(websocket, uri): # Send a message yield from websocket.send("Hello world")
# Read all messages while the socket is open while True: msg = yield from websocket.recv()
if msg is None: # Oops, the socket has closed return
# Fancy message processing print("got message:", msg)
www.thorgate.euTHORGATE
Client Code• Pure JS
• https://github.com/cScarlson/sawkit-client
www.thorgate.euTHORGATE
Client Code// Connect to the server $ws('ws://localhost:8080').ready(function($ws, ws) { // When connection is made, send a message $ws.emit('showMessage', { msg: 'WebSockets are fun!', });
// And react to incoming messages $ws.on('showMessage', function(data) { alert(data.message); }); });
www.thorgate.euTHORGATE
Conclusion• Django & real-time can play together!
• External services make it very easy
• Websockets, without external
service, is still pretty simple
Rivo Laks@RivoLaks
Demo: http://djangocon.thorgate.eu
Code: https://github.com/rivol/djangocon-
realtime
Thanks!