【问题标题】:Execute python script -- Ajax and Flask执行python脚本——Ajax和Flask
【发布时间】:2016-09-30 04:20:59
【问题描述】:

如果不清楚或类似情况,我深表歉意。我对任何类型的网络编程都很陌生,所以请耐心等待。单击链接时,我想运行 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代码吗?我该怎么做呢?

非常感谢,我真的很迷茫并坚持下去。

【问题讨论】:

    标签: javascript python ajax flask


    【解决方案1】:

    这里有一些事情需要修复才能让事情正常工作(或者至少我理解你希望它们工作的方式)。

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

    @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。虽然,您确实应该改用subprocesshttps://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);
            }
        });
    }
    

    希望这足以让您继续前进。

    【讨论】:

    • 非常感谢您提供的信息,它真的很有用。这是我想解决的一般问题——在网站上动态显示传感器数据。似乎您完全删除了 python 脚本并将其替换为 cputemp() 中的行,这是正确的吗?这适用于这种特定情况,但我想知道在我想执行外部 Python 脚本的更一般情况下如何完成。我误解了这个吗?再次感谢,
    • 是的,我将逻辑从脚本移到了一个函数,该函数在客户端请求其各自的路由时执行。如果它是您无法控制的外部脚本,我仍然会使用subprocess 来运行该外部脚本并相应地使用其结果。但是,如果您可以完全控制决定将逻辑放在哪里,那么当您可以将其包含在您的 Flask 应用程序中时,我看不出将其分离到另一个脚本中的意义。或者,您可以将该脚本组织为具有特定功能的模块,您可以将这些功能导入应用程序。
    • 我会尝试这样做,非常感谢。这非常有帮助。你知道如何动态更新它吗?比如——传感器数据不断变化更新网页上的某个数字?
    • 我不知道确切的实现,但我会研究 Web 套接字,以了解您需要服务器将数据推送到客户端的情况。
    • @skex 您也可以每 5 秒或其他时间执行一次 ajax 调用。
    猜你喜欢
    • 1970-01-01
    • 2015-10-23
    • 2019-04-23
    • 1970-01-01
    • 1970-01-01
    • 2019-05-01
    • 2016-09-27
    • 1970-01-01
    • 2015-12-09
    相关资源
    最近更新 更多