我有以下主文件。
from flask import Flask, render_template, request
from flask_socketio import SocketIO, emit, send
import gpio_control
from gevent import monkey
monkey.patch_all()
simplyfishy = Flask(__name__)
simplyfishy.config['SECRET_KEY'] = 'ARG'
socketio = SocketIO(simplyfishy, async_mode='gevent')
@simplyfishy.route('/')
def index():
return render_template('home.html')
@socketio.on('message')
def handle_message(message):
emit(message, {'data': 'main!'})
if __name__ == '__main__':
socketio.run(simplyfishy, host='0.0.0.0')
这是gpio_control文件
import RPi.GPIO as GPIO
from pushbullet import Pushbullet
from flask_socketio import emit
# Set the GPIO mode to Broadcom
GPIO.setmode(GPIO.BCM)
# Create a dictionary for sensors ans their status
float_switches = {
24: {'name': 'Float Switch 1', 'state': GPIO.LOW},
25: {'name': 'Float Switch 2', 'state': GPIO.LOW}
}
# Setup float switches
for float_switch in float_switches:
GPIO.setup(float_switch, GPIO.IN, pull_up_down=GPIO.PUD_UP)
# Define callback function for event detection
def floatsw(channel):
from __main__ import simplyfishy
with simplyfishy.app_context():
if GPIO.input(channel):
print(float_switches[channel]['name'] + " deactivated!")
emit('float_sw', {'data': 'deactivated!'})
else:
print(float_switches[channel]['name'] + " activated!")
# pb.push_note("Simply Fishy", "Sump water level is low")
emit('float_sw', {'data': 'activated!'})
GPIO.add_event_detect(24, GPIO.BOTH, callback=floatsw, bouncetime=1000)
GPIO.add_event_detect(25, GPIO.BOTH, callback=floatsw, bouncetime=1000)
我想做的是,正如你所看到的,我想向 flask 页面发送更新,显示开关是实时激活还是停用。然而,当我触发 float 开关时,我得到以下信息
Float Switch 1 activated!
Traceback (most recent call last):
File "/home/pi/simplyfishy/gpio_control.py", line 61, in floatsw
emit('float_sw', {'data': 'activated!'})
File "/home/pi/.local/lib/python2.7/site-packages/flask_socketio/__init__.py", line 688, in emit
namespace = flask.request.namespace
File "/home/pi/.local/lib/python2.7/site-packages/werkzeug/local.py", line 347, in __getattr__
return getattr(self._get_current_object(), name)
File "/home/pi/.local/lib/python2.7/site-packages/werkzeug/local.py", line 306, in _get_current_object
return self.__local()
File "/home/pi/.local/lib/python2.7/site-packages/flask/globals.py", line 37, in _lookup_req_object
raise RuntimeError(_request_ctx_err_msg)
RuntimeError: Working outside of request context.
我用谷歌搜索并查看了其他示例,但我似乎无法找出问题所在。我认为主文件中的 @socketio.on('message') 甚至不需要,但也许是这样,我需要从 gpio_control 中触发它才能将其发送到页面?我觉得我错过了流程或一些简单的东西。非常感谢您的帮助!
编辑:以下代码已更新并修复了错误消息的发生。然而这样做我确实有一个循环依赖。我相信是由于以下错误消息。
导入错误:无法在控制台中导入名称 simplefishy。从谷歌向我展示的内容中,这将是循环依赖问题。
最佳答案
问题是两个emit()
调用您的floatsw()
函数没有获得足够的信息,因此它们尝试从请求上下文中获取丢失的数据。由于该函数是在没有请求上下文的情况下调用的,因此您会收到错误。
缺少的两个信息是发出的接收者和 namespace 。您似乎没有为此应用程序使用自定义命名空间,因此您可以通过添加 namespace='/'
来解决缺少的命名空间。作为这两个发出的参数。
对于收件人,可以添加broadcast=True
发送到所有连接的客户端,或者使用 room=<sid>
,其中<sid>
是要将消息发送到的客户端的 session ID。您还可以使用您在此处创建的任何自定义房间的名称。
总而言之,避免错误的快速而肮脏的方法是按如下方式更改发射:
def floatsw(channel):
with simplyfishy.app_context():
if GPIO.input(channel):
print(float_switches[channel]['name'] + " deactivated!")
emit('float_sw', {'data': 'deactivated!'}, namespace='/', broadcast=True)
else:
print(float_switches[channel]['name'] + " activated!")
# pb.push_note("Simply Fishy", "Sump water level is low")
emit('float_sw', {'data': 'activated!'}, namespace='/', broadcast=True)
然后,您可能需要制定一种策略来避免广播并仅针对特定客户。
编辑:将应用程序上下文添加到示例中。
关于python - Flask + Flask_SocketIO = 运行时错误 : Working outside of request context,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49725857/