Flask、Python和Socket.io:在断开与threading.Timer的连接时获取“RuntimeError:在请求上下文之外工作”

2024-05-17 07:16:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试编写一个简单的服务器,在一分钟的不活动后断开用户的连接。 我找到了一个简单的方法来使用threading.Timer(每次有活动时重新启动计时器)

在计时器中使用断开连接时,我收到RuntimeError。 尝试使用app.app_上下文和app.test_请求_上下文,但我不知道如何使用它们以及在何处使用它们,或者根本不起作用

服务器代码:

from flask import Flask, request
from flask_socketio import SocketIO, emit, disconnect
from threading import Timer

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
sio = SocketIO(app)
clients = {}


class Client:
    def __init__(self, user, sid, client_time):
        self.user = user
        self.sid = sid
        self.client_time = client_time
        self.activity_timer = Timer(10, self.disc_after_60)
        self.start_timer()

    def disc_after_60(self):
        disconnect(self.sid)
        del clients[self.user]

    def start_timer(self):
        if self.activity_timer.is_alive():
            self.activity_timer.cancel()
            self.activity_timer.start()
        else:
            self.activity_timer.start()


@sio.on('register')
def handle_register(client_user, client_time):
    clients[client_user] = Client(client_user, request.sid, client_time)
    emit('message', ("SERVER", f"{client_user} has joined the server!"), broadcast=True)

客户端我只是使用寄存器连接

完整错误消息:

Exception in thread Thread-8:
Traceback (most recent call last):
  File "C:\Users\idshi\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner
    self.run()
  File "C:\Users\idshi\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 1254, in run
    self.function(*self.args, **self.kwargs)
  File "C:\Users\idshi\PycharmProjects\PyChat excersize\Server\fsserver.py", line 24, in disc_after_60
    disconnect(self.sid)
  File "C:\Users\idshi\AppData\Local\Programs\Python\Python38-32\lib\site-packages\flask_socketio\__init__.py", line 919, in disconnect
    socketio = flask.current_app.extensions['socketio']
  File "C:\Users\idshi\AppData\Local\Programs\Python\Python38-32\lib\site-packages\werkzeug\local.py", line 348, in __getattr__
    return getattr(self._get_current_object(), name)
  File "C:\Users\idshi\AppData\Local\Programs\Python\Python38-32\lib\site-packages\werkzeug\local.py", line 307, in _get_current_object
    return self.__local()
  File "C:\Users\idshi\AppData\Local\Programs\Python\Python38-32\lib\site-packages\flask\globals.py", line 52, in _find_app
    raise RuntimeError(_app_ctx_err_msg)
RuntimeError: Working outside of application context.

This typically means that you attempted to use functionality that needed
to interface with the current application object in some way. To solve
this, set up an application context with app.app_context().  See the
documentation for more information.

如果有人能帮我,我会很高兴的。提前谢谢


Tags: inpyselfclientapplocallineusers
1条回答
网友
1楼 · 发布于 2024-05-17 07:16:35

需要在安装应用程序上下文的情况下调用disconnect()函数,因为这是了解应用程序实例的唯一方法

试试这个:

    def disc_after_60(self):
        with app.app_context():
            disconnect(sid=self.sid, namespace='/')
        del clients[self.user]

相关问题 更多 >