简体   繁体   English

有没有办法从javascript更改python脚本中变量的值?

[英]Is there way to change the value of a variable in a python script from javascript?

I have a python script and apache web server running in a raspberry pi. 我在树莓派中运行python脚本和apache网络服务器。 I want to change the value of a variable in my python script from a web page using javascript. 我想使用JavaScript从网页更改python脚本中变量的值。 It is possible? 有可能的?

We can use socket. 我们可以使用套接字。 for easily using socket, we can use socket.io 为了轻松使用套接字,我们可以使用socket.io

Start.html Start.html

<!doctype html>
<html>
<head>
    <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.6/socket.io.min.js"></script>
</head>

<body>
    <h1>Socket.IO GPIO control</h1>
    <button id="btnGpio">Change GPIO</button>

    <script>
        var socket = io.connect('http://localhost:5000');
        var index = 0;
        socket.on('connect', function () {
            console.log('connected')

            document.getElementById('btnGpio').addEventListener('click', () => {
                index = index + 1;
                console.log('index', index)
                socket.emit('change_gpio', { status: (index % 2 == 0) })
            })
        });
    </script>
</body>
</html>

socket_server.py socket_server.py

from flask import Flask, render_template
from flask_socketio import SocketIO, emit

app = Flask(__name__)
@app.route("/")
def home():
    return render_template("Start.html")

socketio = SocketIO(app)

pin = True
@socketio.on('change_gpio')
def handle_my_custom_event(json):
    pin = json['status']
    print('pin = ' , pin)

@socketio.on('connect', namespace='/')
def test_connect():
    print('Connected')


if __name__ == '__main__':
    socketio.run(app)

Install library with pip 用pip安装库

pip install flask
pip install flask-socketio

Document: 文献:
https://flask-socketio.readthedocs.io/en/latest/ https://flask-socketio.readthedocs.io/en/latest/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM