小编Seb*_*lde的帖子

Flask,Python和Socket.io:多线程应用程序给我"RuntimeError:在请求上下文之外工作"

我一直在使用Flask,Python和Flask-Socket.io库开发应用程序.我emit遇到的问题是由于某些上下文问题,以下代码将无法正确执行

RuntimeError: working outside of request context
Run Code Online (Sandbox Code Playgroud)

我现在只为整个程序编写一个python文件.这是我的代码(test.py):

from threading import Thread
from flask import Flask, render_template, session, request, jsonify, current_app, copy_current_request_context
from flask.ext.socketio import *

app = Flask(__name__)
app.debug = True
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)

def somefunction():
    # some tasks
    someotherfunction()

def someotherfunction():
    # some other tasks
    emit('anEvent', jsondata, namespace='/test') # here occurs the error

@socketio.on('connect', namespace='/test')
def setupconnect():
    global someThread
    someThread = Thread(target=somefunction)
    someThread.daemon = True …
Run Code Online (Sandbox Code Playgroud)

python sockets multithreading flask socket.io

12
推荐指数
2
解决办法
3888
查看次数

在Flask Socket.io中禁用记录器

我有一个使用Flask和FlaskSocket.IO 2.8.4的应用程序。当我初始化SocketIO时,我正在使用

#[...]

logging.basicConfig(level=logging.DEBUG,format='[%(asctime)s][%(levelname)s] - %(funcName)s: %(message)s')
logger = logging.getLogger(__name__)
handler = logging.FileHandler(__builtin__.config['dir']['log_file_handler'])
handler.setLevel(logging.DEBUG)
formatter = logging.Formatter('[%(asctime)s][%(levelname)s] - %(funcName)s: %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)

# Setting up flask external plugins
socketio = SocketIO(app, logger = False)

#[...]

if __name__ == '__main__':
socketio.run(app, port=8000)
Run Code Online (Sandbox Code Playgroud)

无论如何,我的日志中的输出有很多emit,receive和以下handle_event行:

[2017-04-19 05:17:02,172][INFO] - receive: 1139f764dbe64a1ba6e1c8d95228400c: Received packet MESSAGE data 2/telescope,["AskForTimeEvent"]
[2017-04-19 05:17:02,173][INFO] - _handle_event: received event "AskForTimeEvent" from 1139f764dbe64a1ba6e1c8d95228400c [/telescope]
[2017-04-19 05:17:02,173][INFO] - emit: emitting event "clockEvent" to all [/telescope]
[2017-04-19 05:17:02,174][INFO] …
Run Code Online (Sandbox Code Playgroud)

python flask flask-socketio

3
推荐指数
1
解决办法
2429
查看次数