从 JavaScript 函数运行 Python 脚本 [英] Run Python scripts from JavaScript functions

查看:31
本文介绍了从 JavaScript 函数运行 Python 脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们需要运行 Python 代码,该代码将从 JavaScript 中控制 Raspberry Pi 3 的 GPIO.(JavaScript 正在监听数据库的变化,当发生变化时,函数被触发,它应该运行 Python 代码.

(此代码不起作用,就像会弹出警报消息,但 python 代码没有运行,否则应该打开 LED.我做错了什么?)>

index.html 文件

函数 runPython(){$.ajax({类型:POST",url: "/home/pi/Desktop/Web/led.py",数据 :{},成功:callbackFunc});}函数 callbackFunc(response){警报(工作");}

led.py 文件

将 RPi.GPIO 导入为 GPIO导入时间mGPIO.setmode(GPIO.BCM)GPIO.setwarnings(False)GPIO.setup(18, GPIO.OUT)打印LED 亮"GPIO.output(18, GPIO.HIGH)时间.睡眠(10)打印LED 关闭"GPIO.output(18,GPIO.LOW)

解决方案

您的代码不起作用,因为您无法直接从浏览器访问和运行服务器上的脚本,您只能使用 ajax,因此ajax中的url应该是服务器的url,你必须发送data.

在您的服务器(即您的 Raspberry Pi)上,您需要有一个 http(web) 服务器.服务器将处理来自您的 javascript 的 post 请求并相应地控制 GPIO.像其他提到的一样,您可以使用 Flask 网络开发框架来创建一个网络服务器来处理请求,或者我经常使用 http.server 这是python标准的一部分库来为像这样的简单应用程序创建我自己的 GET 和 POST 请求处理程序.

这是一种使用 http.server 的方法,其中 do_GET 方法创建一个网页并在将浏览器指向服务器/RPi IP/URL 时运行 javascript,和'do_POST'方法处理ajax发送的post数据来控制GPIO.

web_gpio.py(Python 3 语法)

导入时间将 RPi.GPIO 导入为 GPIO从 http.server 导入 BaseHTTPRequestHandler, HTTPServerhost_name = '192.168.0.115' # 将此更改为您的树莓派 IP 地址主机端口 = 8000类 MyHandler(BaseHTTPRequestHandler):"""用于读取数据的 BaseHTTPRequestHander 的特殊实现从和控制 Raspberry Pi 的 GPIO"""def do_HEAD(self):self.send_response(200)self.send_header('内容类型', 'text/html')self.end_headers()def_redirect(自我,路径):self.send_response(303)self.send_header('内容类型', 'text/html')self.send_header('位置', 路径)self.end_headers()def do_GET(self):html = '''<身体><p>此网页打开,然后在 2 秒后关闭 LED</p><script src="http://code.jquery.com/jquery-1.12.4.min.js"></script><脚本>函数 setLED(){{$.ajax({类型:POST",url: "http://%s:%s",数据:开",成功:功能(响应){警报(LED 触发")}});}}设置LED();'''self.do_HEAD()html=html % (self.server.server_name, self.server.server_port)self.wfile.write(html.encode("utf-8"))def do_POST(self):# 获取帖子数据content_length = int(self.headers['Content-Length'])post_data = self.rfile.read(content_length).decode("utf-8")如果 post_data == "on":GPIO.setmode(GPIO.BCM)GPIO.setwarnings(False)GPIO.setup(18, GPIO.OUT)GPIO.output(18, GPIO.HIGH)时间.sleep(2)GPIO.output(18, GPIO.LOW)self._redirect('/')如果 __name__ == '__main__':http_server = HTTPServer((host_name, host_port), MyHandler)print("在 %s 上运行服务器:%s" % (host_name, host_port))http_server.serve_forever()

在服务器上运行python脚本:

python3 web_gpio.py

启动浏览器并将浏览器指向服务器/RPi ip(在我的示例中,它是 192.168.0.115:8000)或运行 curl 命令从另一个模拟 GET 请求的终端会话.

curl http://192.168.0.115:8000

希望这个例子能让您了解如何使用简单的 Web 服务器控制服务器上的某些内容.

We need to run a Python code which will control the GPIO of Raspberry Pi 3 from within the JavaScript. (JavaScript is listening for changes on database and when changes are made, function gets triggered and it should run the Python Code.

(This code is not working, like the alert message will pop-up but the python code isn't running which otherwise should turn the LED on. What am i doing wrong?)

index.html file

function runPython()
{
    $.ajax({
    type: "POST", 
    url: "/home/pi/Desktop/Web/led.py",
    data :{},
    success: callbackFunc
    });
}

function callbackFunc(response)
{
    alert("working");
}

led.py file

import RPi.GPIO as GPIO
import timemGPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(18, GPIO.OUT)
print "LED on"
GPIO.output(18, GPIO.HIGH)
time.sleep(10)
print "LED off"
GPIO.output(18,GPIO.LOW)

解决方案

You code is not working because you can't access and run script on server directly from a browser, you can only pass the data to the server using ajax, therefore the url in the ajax should be the server url, and you have to send the data.

On your server (i.e. your Raspberry Pi), you need to have a http(web) server. The server will handle the post request coming from your javascript and control the GPIO accordingly. Like other mentioned, you can use Flask web development framework to create a web server for handling the request(s), or alternatively I often uses http.server which is part of python standard library to create my own GET and POST request handlers for simple applications like this one.

Here is an approach of using http.server where do_GET method create a web page and run the javascript when pointing the browser to the server/RPi IP/URL, and 'do_POST' method handle the post data sent by the ajax to control the GPIO.

web_gpio.py (in Python 3 syntax)

import time
import RPi.GPIO as GPIO
from http.server import BaseHTTPRequestHandler, HTTPServer


host_name = '192.168.0.115'    # Change this to your Raspberry Pi IP address
host_port = 8000


class MyHandler(BaseHTTPRequestHandler):
    """ 
    A special implementation of BaseHTTPRequestHander for reading data 
    from and control GPIO of a Raspberry Pi
    """

    def do_HEAD(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()

    def _redirect(self, path):
        self.send_response(303)
        self.send_header('Content-type', 'text/html')
        self.send_header('Location', path)
        self.end_headers()

    def do_GET(self):
        html = '''
        <html>
        <body>
        <p>this webpage turn on and then turn off LED after 2 seconds</p>
        <script src="http://code.jquery.com/jquery-1.12.4.min.js"></script>
        <script>
          function setLED()
            {{
              $.ajax({
              type: "POST",
              url: "http://%s:%s",
              data :"on",
              success: function(response) {
                alert("LED triggered")
              }
            });
          }}
          setLED();
        </script>
        </body>
        </html>
        '''
        self.do_HEAD()
        html=html % (self.server.server_name, self.server.server_port)
        self.wfile.write(html.encode("utf-8"))

    def do_POST(self):
        # Get the post data
        content_length = int(self.headers['Content-Length'])
        post_data = self.rfile.read(content_length).decode("utf-8")
        if post_data == "on":
            GPIO.setmode(GPIO.BCM)
            GPIO.setwarnings(False)
            GPIO.setup(18, GPIO.OUT)
            GPIO.output(18, GPIO.HIGH)
            time.sleep(2)
            GPIO.output(18, GPIO.LOW)
        self._redirect('/')


if __name__ == '__main__':

    http_server = HTTPServer((host_name, host_port), MyHandler)
    print("Running server on %s:%s" % (host_name, host_port))
    http_server.serve_forever()

Run the python script on the server:

python3 web_gpio.py

Either launch your browser and point the browser to the server/RPi ip (in my example, it is 192.168.0.115:8000) or run curl command form another terminal session to simulate the GET request.

curl http://192.168.0.115:8000

Hope this example would give you the idea on how to control something on your server using a simple web server.

这篇关于从 JavaScript 函数运行 Python 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆