我正在尝试在 openshift.com 服务器(应该支持它们)上实现 websockets。
openshift.com 为我提供了一个 WSGI,所以我将我cherrypy
的嵌入其中,以便我的wsgi.py
脚本定义一个application
对象。此外,cherrypy
还有一个 websocket 工具,由ws4py
.
这是一个在 OpenShift 中的 WSGI 下工作的最小化 Cherrypy 应用程序,它也应该使用 websockets!
import cherrypy
from ws4py.server.cherrypyserver import WebSocketPlugin, WebSocketTool
from ws4py.websocket import EchoWebSocket
import atexit
import logging
# see http://tools.cherrypy.org/wiki/ModWSGI
cherrypy.config.update({'environment': 'embedded'})
if cherrypy.__version__.startswith('3.0') and cherrypy.engine.state == 0:
cherrypy.engine.start(blocking=False)
atexit.register(cherrypy.engine.stop)
class Root(object):
def index(self): return 'I work!'
def ws(self): print('THIS IS NEVER PRINTED :(')
index.exposed=True
ws.exposed=True
# registering the websocket
conf={'/ws':{'tools.websocket.on': True,'tools.websocket.handler_cls': EchoWebSocket}}
WebSocketPlugin(cherrypy.engine).subscribe()
cherrypy.tools.websocket = WebSocketTool()
#show stacktraces in console (for some reason this is not default in cherrypy+WSGI)
logger = logging.getLogger()
logger.setLevel(logging.INFO)
stream = logging.StreamHandler()
stream.setLevel(logging.INFO)
logger.addHandler(stream)
application = cherrypy.Application(Root(), script_name='', config=conf)
一切都很好,除了当我创建一个 websocket(连接到ws://myserver:8000/ws
)时,这是我得到的堆栈跟踪:
cherrypy/_cplogging.py, 214, HTTP Traceback (most recent call last):
File "cherrypy/_cprequest.py", line 661, in respond
self.hooks.run('before_request_body')
File "cherrypy/_cprequest.py", line 114, in run
raise exc
File "cherrypy/_cprequest.py", line 104, in run
hook()
File "cherrypy/_cprequest.py", line 63, in __call__
return self.callback(**self.kwargs)
File "ws4py/server/cherrypyserver.py", line 200, in upgrade
ws_conn = get_connection(request.rfile.rfile)
AttributeError: 'mod_wsgi.Input' object has no attribute 'rfile'
(我从文件名中手动删除了绝对路径) PS:我使用python3.3
, cherrypy==3.5.0
, ws4py==0.3.4
.
我不清楚:
- 如果这是在 WSGI 环境中,cherrypy 和 ws4py 之间缺乏兼容性。
- 如果在 WSGI 环境中是 ws4py 的问题
- 如果是因为 Openshift websockets 的端口与 http 不同
PPS:这是一个完整的 OpenShift 项目,您可以自己运行并尝试:https ://github.com/spocchio/wsgi-cherrypy-ws4py