【问题标题】:Integrating SimpleWebSocketServer with django and apache将 SimpleWebSocketServer 与 django 和 apache 集成
【发布时间】:2014-07-27 16:19:37
【问题描述】:

我在 mod_wsgi 中使用 django 和 apache。
我正在尝试这个模块:https://github.com/opiate/SimpleWebSocketServer 基本上我正在尝试将 websocket 服务器与我的 django 应用程序集成,因此我可以共享变量并与两个服务器进行数据库查询。

这是我使用这个库的代码:
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"

我使用thread,所以它不会阻塞其余代码。
如果我单独运行此代码,并在浏览器中创建一个 webSocket:

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();

一切正常。问题是如何将它集成到我的 django 代码中。 所以我把myserver.py 代码放在我项目的__init__.py 文件中。我创建了一个设置 WEB_SOCKET,我为其分配了 SimpleWebSocket 实例。它确实创建了对象(我已经在调试模式下检查过),但仍然没有事件,没有连接,什么都没有。这没用。为什么?
也许这个问题还有另一种解决方案?我需要一些简单的东西,比如这个模块,它必须能够与 django 集成。

【问题讨论】:

    标签: python django apache websocket integrate


    【解决方案1】:

    您只需要将项目的位置添加到 python 路径,这样您就可以在 os.environ 中设置项目设置的位置,然后就可以了。

    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()
    

    【讨论】:

      猜你喜欢
      • 2015-02-03
      • 2018-10-04
      • 2017-06-13
      • 1970-01-01
      • 2013-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多