2

I use django and apache with mod_wsgi.
I'm trying this module: https://github.com/opiate/SimpleWebSocketServer Basically I'm trying to integrate websocket server with my django app, so I can share variables and do db queries with both servers.

this is my code using this library:
myserver.py:

from SimpleWebSocketServer import WebSocket, SimpleWebSocketServer
import thread
class socket(WebSocket):
    def handleMessage(self):
        if self.data is None:
            self.data = ''
        print self.data
        # echo message back to client
        self.sendMessage(str(self.data))

    def handleConnected(self):
        print self.address, 'connected'
        #print self.request
        #print self.server.connections

    def handleClose(self):
        print self.address, 'closed'

server = SimpleWebSocketServer('',8001,socket)
#server.serveforever()
thread.start_new_thread(server.serveforever,())
print "done"

I use thread so it wont block the rest of the code.
If I run this code alone, and create a webSocket in the browser:

javascript:

var socket;
function startSocket(){
    socket= new WebSocket("ws://localhost:8001");
    socket.onopen= function(evt) {test.innerHTML+="connected\n";};
    socket.onclose = function(evt) {test.innerHTML+="disconnected\n"};
    socket.onmessage = function(evt) { alert(evt.data);};
    socket.onerror = function(evt) {alert("error");};
}
startSocket();

everything is working fine. the problem is how to integrate it in my django code. So I put myserver.py code in the __init__.py file of my project. I've created a setting WEB_SOCKET, to which I assign the SimpleWebSocket instance. it does create the object (I've checked in debug mode), but still- no events, no connection, no nothing. it does not work. why?
And perhaps there's another solution to this problem? I need something easy and simple, like this module, and it must be able to integrate with django.

Nilesh
  • 20,521
  • 16
  • 92
  • 148
user3599803
  • 6,435
  • 17
  • 69
  • 130

1 Answers1

0

You just need to add the location of your project to the python path so you can setup in the os.environ the location of your project settings and that would do it.

import sys,os
sys.path.append('path_to_my_dango_project')
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings')

from app.models import *
...
obj=Model()
..
obj.save()
land
  • 15
  • 4