无法将按钮事件传递给外部python程序
我需要分离我的python Flask web应用程序和通过socketio进行通信的运行代码。我能够将消息从外部python程序发送到web,但无法从web获取python程序检测到的事件。实际上,我希望当用户按下网页上的按钮时,外部python代码打印到hello world消息的终端。在这个html的控制台中,我肯定看到“按钮按下” 这是我单独运行的程序,按下按钮时不会向终端打印任何内容:无法将按钮事件传递给外部python程序,python,socket.io,flask-socketio,Python,Socket.io,Flask Socketio,我需要分离我的python Flask web应用程序和通过socketio进行通信的运行代码。我能够将消息从外部python程序发送到web,但无法从web获取python程序检测到的事件。实际上,我希望当用户按下网页上的按钮时,外部python代码打印到hello world消息的终端。在这个html的控制台中,我肯定看到“按钮按下” 这是我单独运行的程序,按下按钮时不会向终端打印任何内容: from flask_socketio import SocketIO socketio = So
from flask_socketio import SocketIO
socketio = SocketIO(message_queue='redis://', host='0.0.0.0')
def my_function_handler(data):
print("Hello World")
if __name__ == '__main__':
while True:
socketio.on_event('my event', my_function_handler)
有人能告诉我哪里出了问题吗?非常感谢 您正在尝试执行不受支持的操作。外部进程只能发出,而不是收件人。如果您需要在外部进程中发射和接收,那么我建议您将Socket.IO服务器完全移动到此进程。根据Miguel的回答,显然socketIO中不支持此行为,因此如果有人感兴趣,我将发布我对该问题的特定解决方案。我花了很多时间在谷歌上搜索,堆积如山,通常从兔子洞里掉下来。我最终做的是,由于我已经在使用redis,我只是用它在进程之间传递消息。这种方法有很多缺点,但它很好地满足了我的需要,所以下面是我所做的。对于index.html:
<html>
<head>
<title>Listener</title>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.4.8/socket.io.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function() {
var socket = io.connect();
$('#mybutton').on('click', function() {
socket.emit('button event');
});
});
</script>
<button id="mybutton">Push Me!</button>
</body>
</html>
单独运行过程:
import redis
r = redis.Redis("localhost")
if __name__ == '__main__':
while True:
if r.get('button') == 'pressed':
print("Button pressed!")
r.set('button', 'not pressed')
<html>
<head>
<title>Listener</title>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.4.8/socket.io.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function() {
var socket = io.connect();
$('#mybutton').on('click', function() {
socket.emit('button event');
});
});
</script>
<button id="mybutton">Push Me!</button>
</body>
</html>
from flask import Flask, render_template
from flask_socketio import SocketIO
import redis
app = Flask(__name__)
app.config['SECRET_KEY'] = 'froggy'
app.debug = True
socketio = SocketIO(app, message_queue='redis://')
r = redis.Redis("localhost")
r.set('button', 'not pressed')
@app.route("/")
def index():
return render_template("index.html")
@socketio.on('button event')
def handleMessage():
r.set('button', 'pressed')
if __name__ == '__main__':
socketio.run(app, host='0.0.0.0')
import redis
r = redis.Redis("localhost")
if __name__ == '__main__':
while True:
if r.get('button') == 'pressed':
print("Button pressed!")
r.set('button', 'not pressed')