【问题标题】:Can't modify the value of the session within event handlers for websockets events无法在 websockets 事件的事件处理程序中修改会话的值
【发布时间】: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


    【解决方案1】:

    如文档中所述,Flask-SocketIO 不会将会话写回会话存储,它只是将它们保存在内存中并可供套接字处理程序访问。

    如果您希望对服务器端会话的更改保持不变并可供常规 HTTP 客户端使用,您必须在进行这些更改后自己保存会话。我自己还没有测试过,但我认为这样可以:

    session.modified = True
    app.save_session(session, make_response('dummy'))
    

    请注意,save_session() 会得到一个虚拟响应。这只有在之前的常规 HTTP 调用中已经建立会话时才有效。显然,上面的代码不会创建新会话,因为响应将被丢弃并且永远不会到达客户端。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-28
      相关资源
      最近更新 更多