1

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?

1 Answer 1

7

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/

Sign up to request clarification or add additional context in comments.

1 Comment

do you have a python 3 solution too?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.