【发布时间】:2014-07-04 18:30:58
【问题描述】:
我正在构建一个基于flask&pyhon 的小应用程序,我的主要功能是基于websockets。我发现我无法在 websockets 事件的事件处理程序中修改 sesssion 的值(我正在使用flask-socketio),因为flask 将其会话存储在客户端。因此,正如扩展程序的作者所推荐的那样,我安装了flask-kvsession 以将服务器端的会话存储在基于redis 的后端中。
我按照http://pythonhosted.org/Flask-KVSession/ 提供的说明进行操作,但问题仍然存在。所以我创建了一个小程序来告诉你我在说什么。
# main.py
from flask import Flask, session, render_template
from flask.ext.socketio import SocketIO
from pprint import pprint
import redis
from flask_kvsession import KVSessionExtension
from simplekv.memory.redisstore import RedisStore
store = RedisStore(redis.StrictRedis())
app = Flask(__name__)
app.debug = True
app.secret_key = 'secret!'
KVSessionExtension(store, app)
socketio = SocketIO(app)
@app.route('/')
def index():
pprint(session)
return render_template("client.html")
@socketio.on('connect')
def handle_connect(message):
session['debug'] = 'debug'
pprint(session)
if __name__ == "__main__":
socketio.run(app)
<!-- templates/client.html -->
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/
socket.io/0.9.16/socket.io.min.js"></script>
<script type="text/javascript">
var sock = io.connect('http:localhost:5000');
sock.emit('connect', {debug: 'debug'});
</script>
</body>
</html>
这是 werkzeug 调试服务器的输出:
* Running on http://127.0.0.1:5000/
* Restarting with reloader
<KVSession {}>
127.0.0.1 - - [2014-07-04 21:25:51] "GET / HTTP/1.1" 200 442 0.004452
<KVSession {'debug': 'debug'}>
<KVSession {}>
127.0.0.1 - - [2014-07-04 21:26:02] "GET / HTTP/1.1" 200 442 0.000923
<KVSession {'debug': 'debug'}>
我希望第二次访问该页面时会话的内容是'debug': 'debug',但事实并非如此。
这是我在运行此应用程序时在 redis 服务器上发生的情况:
127.0.0.1:6379> MONITOR
OK
1404498351.888321 [0 127.0.0.1:38129] "GET" "136931c509f674e3_53b6e25b"
1404498352.073011 [0 127.0.0.1:38129] "GET" "136931c509f674e3_53b6e25b"
1404498362.455320 [0 127.0.0.1:38129] "GET" "136931c509f674e3_53b6e25b"
1404498362.612346 [0 127.0.0.1:38129] "GET" "136931c509f674e3_53b6e25b"
如您所见,会话的值被访问了 4 次,但从未修改过。 那么,我应该怎么做才能修复这个错误呢?
【问题讨论】:
标签: python websocket flask redis socket.io