如何将Ajax与CherryPy一起使用以运行python脚本从Web界面SSH到Raspberry Pi Zero中

问题描述 投票:0回答:1

我正在尝试制作一个Web界面来远程控制GoPro。到目前为止,我已经准备好将Raspberry Pi 3B用作网络服务器,该服务器通过USB连接到Pi Zero,该USB通过WiFi连接到GoPro。因此,每当我从Pi 3B SSH进入Pi Zero时,都可以控制GoPro。所以现在,我想用CherryPy和Ajax创建一个Web服务器,以便当连接到与Pi 3B(Web服务器)相同的WiFi网络时,可以创建一个Web界面来控制GoPro。

我一直在阅读CherryPy documentation,以尝试了解如何将Ajax与CherryPy一起使用。我以前可以使用更基本的CherryPy方法(没有Ajax)来实现它,但是它使它转到了另一个网页上,为此,我希望它保留在同一网页上,这就是为什么我使用Ajax。我之前从未真正使用过Ajax,所以我很陌生,我基本上会尽力在CherryPy文档上复制该示例,但这没有用,所以如果我在这里缺少一些简单的内容,请原谅我。

这是HTML页面代码:

<html>
<head>
    <script src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function(){
        $("#takePhotos").click(function(e){
            $.post("/take", {"count": $("input[name='count']").val()})
            .done(alert("Running Take Photos!"));
            })
            e.preventDefault();
        });    
    </script>
</head>
<body>
    <input type="text" value="" name="count"/>
    <button id="takePhotos">Take Photos</button>
</body>

这是Web服务器的python代码:

import cherrypy
import os, os.path
import GoPro as gp
import requests


class RaspiServer(object):
    @cherrypy.expose
    def index(self):
    return open('index.html')

@cherrypy.expose
class GPWebService(object):
@cherrypy.tools.accept(media="text/plain")
def GET(self,count):
    print("running")

def POST(self,count):
    print("running")
    gp.connect("pi", "raspberrypizero.local", "raspberry")
    gp.takePhotos(count)
    return count


if __name__ == '__main__':
conf = {
    '/': {
        'tools.sessions.on': True,
        'tools.staticdir.root': os.path.abspath(os.getcwd())

    },
    '/takePhotos':{
        'request.dispatch': cherrypy.dispatch.MethodDispatcher(),
        'tools.response_headers.on': True,
        'tools.response_headers.headers': [('Content_Type', 'text/plain')]

    },
    '/static':{
        'tools.staticdir.on': True,
        'tools.staticdir.dir': "./public"
    }
}
cherrypy.config.update({'server.socket_host': '0.0.0.0'})
webapp = RaspiServer()
webapp.takePhotos = GPWebService()
cherrypy.quickstart(webapp, '/', conf)

我面临的问题是,每当我在输入字段中输入值并单击按钮时,就会显示警告,提示“正在运行拍照!”。并且在控制台中,我可以看到Web服务器已收到请求,但是python脚本未在“ POST”方法中运行。我想发生的是执行POST方法,并执行两个python方法“ connect”和“ takePhotos”(目前未发生)。

非常感谢!

python ajax raspberry-pi
1个回答
0
投票

[整天都在学习和了解有关Ajax的知识之后,我终于弄清楚了答案,它像我想的那样愚蠢而简单。

在index.html文件的第7行,我不得不将$.post("/take")更改为$.post("/takePhotos")

© www.soinside.com 2019 - 2024. All rights reserved.