如何从 Flask 函数内部访问 flask-websocket 会话

huangapple go评论74阅读模式
英文:

How do I access flask-websocket sessions from inside flask functions

问题

以下是您提供的代码的翻译部分:

# 从flask导入必要的模块
from flask import Flask, session, render_template, url_for, redirect
from flask_socketio import SocketIO, join_room

# 创建Flask应用程序
app = Flask(__name__)

# 创建一个字典来存储游戏板信息
boards = {}

# 创建SocketIO对象
socketio = SocketIO(app)

# 设置应用程序的秘密密钥
app.secret_key = "temporary"

# 定义首页路由
@app.route('/')
def index():
    return render_template('wait.html')

# 定义foo路由
@app.route('/dir')
def foo():
    if "name" in session:  # 当会话中存在"name"时
        pass  # 这只是一个填充语句
    else:
        return redirect(url_for("index"))  # 这一行会导致不断地在"index"和"foo"之间跳转

# 定义SocketIO事件处理函数
@socketio.on('log')
def connection(request):
    if "name" not in session:
        join_room('waiting')  # 在实际代码中,用户会等待另一个人
        session['name'] = 'craig'
        socketio.emit('redirect', url_for('foo'), room='waiting')
    else:
        pass

# 如果是主模块,运行SocketIO应用程序
if __name__ == '__main__':
   socketio.run(app, port=5000, debug=True)

HTML部分不需要翻译,因为它没有中文内容。如果您需要进一步的帮助或有其他问题,请随时提出。

英文:

As the title states I'm having issues with accessing flask-websocket sessions from the flask functions. I have realised they are different and probably stored differently and tried to solve this using the flask-session library to no avail.

I have made some boilerplate code illustrating my problem.

from flask import Flask, session,render_template,url_for,redirect
from flask_socketio import SocketIO,join_room
app = Flask(__name__)
boards = {}
socketio = SocketIO(app)
app.secret_key = "temporary"
@app.route('/')
def index():
    return render_template('wait.html')
@app.route('/dir')
def foo():
    if "name" in session:#fails here as session is <SecureCookieSession {}> instead of {'name' : 'craig}
        pass #just a filler
    else:
        return redirect(url_for("index"))#this line will cause to repetitively go back and forward from index to foo
@socketio.on('log')
def connection(request):
    if "name" not in session:
        join_room('waiting')#in my actual code the user waits for another person
        session['name'] = 'craig'
        socketio.emit('redirect', url_for('foo'),room= 'waiting')
    else:
        pass

if __name__ == '__main__':  
   socketio.run(app ,port=5000, debug=True)

and the html:

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
	</head>
	<body>
        Waiting...
		<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js"></script>
		<script>
		const socket = io();
		socket.emit("log", { data: "connection" });
		socket.on('redirect', (dest) => {
			window.location = dest;
		});
		</script>
	</body>
</html>

答案1

得分: 0

flask-session 原来有解决方案,我只是在最初尝试时使用不当,忘记了这两行代码:

Session(app)
socketio = SocketIO(app, manage_session=False)  # 我没有使用 manage_session

我还使用了

session.modified = True

虽然我不确定是否绝对必要

这是更新后的服务器代码:

from flask import Flask, session, render_template, url_for, redirect
from flask_socketio import SocketIO, join_room
from flask_session import Session

app = Flask(__name__)
app.config['SECRET_KEY'] = 'temporary'
app.config['SESSION_TYPE'] = 'filesystem'
Session(app)
socketio = SocketIO(app, manage_session=False)

@app.route('/')
def index():
    return render_template('wait.html')

@app.route('/dir')
def foo():
    if "name" in session:
        name = session['name']
        return f"Hello, {name}!"
    else:
        return redirect(url_for("index"))

@socketio.on('log')
def connection(request):
    print(session)
    if "name" not in session:
        join_room('waiting')
        session['name'] = 'craig'
        session.modified = True
        socketio.emit('redirect', url_for('foo'), room='waiting')
    else:
        session.clear()

if __name__ == '__main__':
   socketio.run(app, port=5200, debug=True)
英文:

Turn's out flask-session did have the soloution, I was just using it wrong forgetting these two lines of code when I initially tried:

Session(app)
socketio = SocketIO(app, manage_session=False)# I did not have the manage_session

I also used

session.modified = True

though I'm not sure it is strictly necessary

Here is the updated server code:

from flask import Flask, session, render_template, url_for, redirect
from flask_socketio import SocketIO, join_room
from flask_session import Session

app = Flask(__name__)
app.config['SECRET_KEY'] = 'temporary'
app.config['SESSION_TYPE'] = 'filesystem'
Session(app)
socketio = SocketIO(app, manage_session=False)

@app.route('/')
def index():
    return render_template('wait.html')

@app.route('/dir')
def foo():
    if "name" in session:
        name = session['name']
        return f"Hello, {name}!"
    else:
        return redirect(url_for("index"))

@socketio.on('log')
def connection(request):
    print(session)
    if "name" not in session:
        join_room('waiting')
        session['name'] = 'craig'
        session.modified = True
        socketio.emit('redirect', url_for('foo'), room='waiting')
    else:
        session.clear()

if __name__ == '__main__':  
   socketio.run(app, port=5200, debug=True)

huangapple
  • 本文由 发表于 2023年6月19日 18:48:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/76505895.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定