繁体   English   中英

执行python脚本-Ajax和Flask

[英]Execute python script — Ajax and Flask

如果这不清楚或类似的事情,我深表歉意。 我对任何类型的Web编程都是非常陌生的,所以请耐心等待。 单击链接时,我要运行python脚本,然后显示结果。 当前正在发生的事情是它只是返回HTML页面。 我有一个为什么的想法 ,但不知道如何解决。 我相信问题出在Flask python代码上,但是请您多加投入。 我将评论我认为是问题的区域

Flask(Python)代码:

from flask import Flask, render_template
app = Flask(__name__)



@app.route("/")
def index():
    return "Hello, world!"

@app.route('/cgi-bin/cputemp.py', methods=['GET', 'POST'])
#this is where  need to put something, but I don't know what. 
#Without defining this route I was getting a 405 error. I have no idea
#what would go here -- this is just the directory to the python and I 
#thought the routes were for different web pages the user could access.
#Again, I believe *this* is the source of the problem. Obviously 
#right now it's just returning the HTML of the following test() function.


@app.route('/test', methods=['GET', 'POST'])
def test():
    return render_template("test.html")

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=5000, debug=True)

的test.html

<!DOCTYPE html>

<html>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>

<script src="/static/test.js"></script> 
<div id="swiss"><a href="javascript:cputemp2()">Click to display CPU Temp</a></div>

</html>

test.js

function cputemp2()
{
    $.ajax(
    {
        type: "POST",
        url: "cgi-bin/cputemp.py",
        dataType: "html",
        success: function(msg)
        {
        console.log(msg); # It's just returning the HTML of test.html currently
        document.getElementById('swiss').innerHTML = msg;
        },
    });
}    

cputemp.py

#!/usr/bin/python
import cgi;
import cgitb;
import time
cgitb.enable()
import commands
import sys
import string
print "Content-type: text/html\n\n";
mytemp1 = commands.getoutput('/opt/vc/bin/vcgencmd measure_temp | cut -d "=" -f2 | cut -f1')
output = "Pi CPU Temp is: " + mytemp1
print output

我的问题是-我认为test.js文件中的AJAX代码将处理对python脚本的调用。 它所做的就是在Flask代码中执行到该目录的路由下面的方法。 那我需要在那儿运行python代码吗? 我该怎么做呢?

非常感谢你,我真的失去了和粘贴在此。

为了使工作正常(或者至少我了解您希望它们正常工作),这里需要修复一些问题。

如果要使用Flask,则不需要指向Python脚本的路由。 您可以路由到/cputemp类的东西,然后运行一个函数,该函数以我想显示的CPU温度返回HTML片段。

@app.route('/cputemp', methods=['GET', 'POST'])
def cputemp():
    mytemp1 = commands.getoutput('/opt/vc/bin/vcgencmd measure_temp | cut -d "=" -f2 | cut -f1')
    return render_template("cputemp.html", temp=mytemp1)

不要忘记在顶部导入commands 虽然,您确实应该使用subprocess https://docs.python.org/2/library/commands.html

那里的返回使用Flask模板来创建您要在AJAX请求成功时插入的HTML片段。 http://flask.pocoo.org/docs/0.11/quickstart/#rendering-templates

例如, cputemp.html可以像这样:

<p>Pi CPU Temp is: {{ temp }}</p>

请注意,我不知道将该命令分配给mytemp1是否有效。 这是无法显示所需信息的另一个问题。

现在介绍AJAX部分。 我添加了一个错误处理程序以帮助调试其他问题。 请注意,我更改了URL以匹配路由。 同样,使用innerHTML安全问题,而不是让您自己担心自己设置的innerHTML设置问题,而是使用jQuery的html函数。 http://api.jquery.com/html/

function cputemp2() {
    $.ajax({
        type: "POST",
        url: "/cputemp",
        dataType: "html",
        success: function(msg) {
            console.log(msg);
            $("#swiss").html(msg);
        },
        error: function (xhr, status, error) {
            console.log(error);
        }
    });
}

希望这足以让您前进。

暂无
暂无

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

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