Skip to content

Instantly share code, notes, and snippets.

View johngrantuk's full-sized avatar

John Grant johngrantuk

View GitHub Profile
@johngrantuk
johngrantuk / sensor.html
Created March 29, 2016 16:41
Django Channels Sensor template
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>{% block title %}Sensor Example{% endblock %}</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
{% load staticfiles%}
@johngrantuk
johngrantuk / views.py
Created March 29, 2016 16:39
Django Channels view
from django.shortcuts import render
def sensor(request):
return render(request, "sensor.html", {
'sensor': '99',
})
@johngrantuk
johngrantuk / consumers.py
Created March 29, 2016 16:25
Django Channels consumer disconnect
def ws_disconnect(message):
print("Someone left us...")
Group("sensor").discard(message.reply_channel)
@johngrantuk
johngrantuk / consumers.py
Created March 29, 2016 16:24
Django Channels ws_message consumer
def ws_message(message):
# ASGI WebSocket packet-received and send-packet message types
# both have a "text" key for their textual data.
print("Received!!" + message['text'])
@johngrantuk
johngrantuk / routing.py
Created March 29, 2016 16:21
Django Channels routing file
from sensor.consumers import ws_message, ws_connect, ws_disconnect
channel_routing = {
'websocket.connect': ws_connect,
'websocket.receive': ws_message,
'websocket.disconnect': ws_disconnect,
}
@johngrantuk
johngrantuk / asgi.py
Created March 29, 2016 16:11
Django Channel asgi file
import os
import channels.asgi
os.environ.setdefault(“DJANGO_SETTINGS_MODULE”, “sensor.settings”)
channel_layer = channels.asgi.get_channel_layer()
@johngrantuk
johngrantuk / settings.py
Created March 29, 2016 15:58
Django settings for Channels project
"""
Django settings for sensor project.
Generated by 'django-admin startproject' using Django 1.9.2.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
@johngrantuk
johngrantuk / consumers.py
Created March 29, 2016 15:10
Django Channel ws_connect consumer
from channels import Group
def ws_connect(message):
print("Someone connected.")
path = message['path'] # i.e. /sensor/
if path == b’/sensor/':
print("Adding new user to sensor group")
Group(“sensor").add(message.reply_channel) # Adds user to group for broadcast
message.reply_channel.send({ # Reply to individual directly