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

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

问题描述

我们需要运行一个Python代码,该代码将从JavaScript中控制Raspberry Pi 3的GPIO. (JavaScript正在侦听数据库中的更改,并且在进行更改时,将触发函数,并且该函数应运行Python代码.

(此代码无法正常工作,例如会弹出警报消息,但python代码未运行,否则应打开LED指示灯.我在做什么错了?)

index.html文件

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

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

led.py文件

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)

解决方案

您的代码无法正常工作,因为您无法直接从浏览器访问并在服务器上运行脚本,只能使用,因此ajax中的url应该是服务器网址,并且您必须发送data.

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

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

web_gpio.py(使用Python 3语法)

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()

在服务器上运行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天全站免登陆