a

Django Channels

Realtime this time

by Bram Noordzij / @random_bits, Bob Voorneveld / @BobVoorneveld


INSTALLED_APPS = (
   ...
   'map',  # Our demo app
)
				    

INSTALLED_APPS = (
   ...
   'map',  # Our demo app
   'channels',
)
				    

Jacob Kaplan-Moss


# routing.py
from map import consumers

channel_routing = {

    'websocket.connect': consumers.ws_connect,
    "websocket.keepalive": consumers.websocket_keepalive,
    'websocket.receive': consumers.ws_receive,
    'websocket.disconnect': consumers.ws_disconnect,
				    

# consumers.py
from channels import Group
from channels.auth import channel_session_user_from_http
from channels.auth import channel_session_user

@channel_session_user_from_http
# adds session user to the message
def ws_connect(message):
	for marker in Marker.objects.all():
		message.reply_channel.send({'text': \
			json.dumps({marker_info...
	Group('notifications').add(message.reply_channel)
				    

@channel_session_user
def websocket_keepalive(message):
    logger.info('websocket_keepalive. message = %s', message)
    # Load every connection into one group.
    Group('notifications').add(message.reply_channel)
				    

@channel_session_user
def ws_receive(message):
    # Load the data from the incoming WebSocket message
    try:
        data = json.loads(message['text'])
	...
	# Update the location
    marker.location = GEOSGeometry('POINT(%s %s)' % (data...
    marker.save()
				    

@channel_session_user
def ws_disconnect(message):
    logger.info('websocket_disconnect. message = %s', message)
    # Remove connection from the group
    Group('notifications').discard(message.reply_channel)
				    

# signals.py
from channels import Group
from django.db.models.signals import post_save
from django.dispatch import receiver

def send_notification(notification):
    Group('notifications').send({'text': json.dumps(notification)})

@receiver(post_save, sender=Marker)
def marker_post_save(sender, instance, created, **kwargs):
    send_notification({
        'type': 'post_save',
        'created': created,
        'feature': instance.geojson_feature
    })
				    

Read the documentation! Django Channels Read the Docs

Read the documentation, its great!

Django Channels Read the Docs

Thanks! ![qrencode -s6 -o repo.png url](repo.png) https://github.com/bobvoorneveld/spindlechannels