Flask SocketIO)需要在打开新选项卡时检测重复连接

Flask SocketI) need to detect duplicate connections on opening new tab

我需要在用户打开新标签页时检测重复会话。由于我将其用于调查,因此我没有任何用户数据。我正在处理匿名用户。

通过阅读文档和其他各种线程,我了解到我需要向客户端发送一个会话数据,该数据将是一个 uuid 并检查用户是否已经通过新连接的身份验证。

我的代码如下-

from flask import Flask, render_template, session
from flask_session import Session
from flask_socketio import SocketIO, send, emit
from flask_login import LoginManager, UserMixin, current_user, login_user, logout_user, AnonymousUserMixin
import time, json, uuid, os

app = Flask(__name__)
app.config['SECRET_KEY'] = 'top-secret!'
app.config['SESSION_TYPE'] = 'filesystem'
login_manager = LoginManager(app)
login_manager.init_app(app)
Session(app)
socketio = SocketIO(app, cors_allowed_origins="*", logger=True, manage_session=False)


class User(UserMixin, object):
    def __init__(self, id=None):
        self.id = id

@login_manager.user_loader
def load_user(user_id):
    return User.get(user_id)


time_now = 0
msg = "Hello User. Please wait other users to join. Survey will start once minimum users will join. Max waiting time " \
      "is 5 min "

# connected_msg_json = json.dumps(connected_msg, indent=4)
client_count = 0


@socketio.on('message')
def handle_message(msg):
    print("Connected with the client with data " + msg)


@socketio.on('connect')
def test_connect():
    print("Connected")
    f = open('data.json')
    data = json.load(f)
    minUserCount = data['minimumNoOfUser']
    global client_count, time_now
    if current_user.is_authenticated:
        pass
    else:
        client_count += 1
        login_user(User(id=uuid.uuid1()))
    if client_count == 0:
        time_now = int(time.time())

    print("Total no of connected client " + str(client_count))
    print("About to send the time when first user connected " + str(time_now))
    send(time_now)
    if client_count > minUserCount:
        send("Continue", broadcast=True)


@socketio.on('disconnect')
def test_disconnect():
    print('Client disconnected')
    logout_user()
    global client_count
    client_count -= 1
    print("Total no of connected client " + str(client_count))

由于我需要确保在唯一用户数最少时打开调查,所以我决定在连接时登录用户。如果用户已经通过身份验证,那么我相信这意味着它是通过选项卡建立的新连接。

现在我不确定我的代码是否正确但包不正确或两者都有。我已尝试解决该错误,但我仍然遇到此错误 -

ImportError: cannot import name 'ContextVar' from 'werkzeug.local' (/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/werkzeug/local.py)

这在我输入行时出现

app.config['SESSION_TYPE'] = 'filesystem'

否则我会收到关于未设置密钥的不同错误。

我的requirements.txt是:

Flask==2.0.2
Flask-Cors==3.0.10
Flask-SocketIO==4.3.1
gevent==21.8.0
gevent-websocket==0.10.1
greenlet==1.1.2
gunicorn==20.1.0
python-engineio==3.13.2
python-socketio==4.6.0
simple-websocket==0.5.0
websocket-client==1.2.1
websockets==10.1
Werkzeug==0.14.1

您需要将 werkzeug 更新到 2.0 +