Question

I am trying to write chat application, here are some desing thoughts:
Django doing main website serving.
Sockjs-tornado serves chat and between them I would like to setup redis.

When sockjs-tornado receives message in chat, it processes it and sends to other connected clients and also puts it in redis, so Django can save this message in persistent database. I know I should use pubsub functionallity of redis. I know how to setup it in tornado (brukva library), but how can I subscribe to redis' channel in django? So I can receive message in django and save it to database? Do you have any ideas?

Was it helpful?

Solution

i'm not know how sockjs use, but this example illustrate how to save in django model
#in tornado

import brukva  
import tornado.web  
import tornado.websocket

c = brukva.Client()  
c.connect()

class MessagesHandler(tornado.websoket.WebsocketHandler):

    def open(self):
        #....

    def handle_request(self, response):
        pass

    def on_message(self, message):
        #....
        c.publish(self.channel, json.dumps({
            "sender": self.sender_name,
            "text": message,
        }))

        http_client = tornado.httpclient.AsyncHTTPClient()
        request = tornado.httpclient.HTTPRequest(
              '/to/django_project/url/chat_save_base/',

                method="POST",
                body=urllib.urlencode({
                "message": message.encode("utf-8"),
                "sender": self.sender.name,
            })
        http_client.fetch(request, self.handle_request)  

#in django_url

url(r'/to/django_project/url/chat_save_base/','app.my_view')

#my_view

from django.views.decorators.csrf import csrf_exempt  
from messages.models import Message

@csrf_exempt
def my_view(request):  
    message_text = request.POST.get("message")  
    sender = User.objects.get(id=request.POST.get("sender_id"))  

    message = Message()
    message.text = message_text
    message.sender_id = sender_id    
    message.save()

source for additional info: http://habrahabr.ru/post/160123/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top