执行python脚本-Ajax和Flask [英] Execute python script -- Ajax and Flask

查看:70
本文介绍了执行python脚本-Ajax和Flask的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

烧瓶(Python)代码:

从烧瓶导入烧瓶中的

 ,render_templateapp = Flask(__ name__)@ app.route("/")def index():返回你好,世界!"@ app.route('/cgi-bin/cputemp.py',methods = ['GET','POST'])#这是需要放东西的地方,但是我不知道是什么.#未定义此路线,我得到405错误.我不知道#这里会发生什么-这只是python和我的目录#以为路由是针对用户可以访问的不同网页的.再次,我相信*这*是问题的根源.明显地#现在,它只是返回以下test()函数的HTML.@ app.route('/test',methods = ['GET','POST'])def test():返回render_template("test.html")如果__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()">单击以显示CPU温度</a></div></html> 

test.js

 函数cputemp2(){$ .ajax({输入:"POST",网址:"cgi-bin/cputemp.py",dataType:"html",成功:功能(msg){console.log(msg);#目前仅返回test.html的HTMLdocument.getElementById('swiss').innerHTML = msg;},});} 

cputemp.py

 #!/usr/bin/python进口CGI;导入cgitb;导入时间cgitb.enable()导入命令导入系统导入字符串打印内容类型:text/html \ n \ n";mytemp1 =命令.getoutput('/opt/vc/bin/vcgencmd measure_temp | cut -d"=" -f2 | cut -f1')输出="Pi CPU温度为:" + mytemp1打印输出 

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

非常感谢您,,我真的迷失了方向.

解决方案

这里需要修正一些问题,以使事情起作用(或者至少我了解您希望它们起作用).

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

  @ app.route('/cputemp',methods = ['GET','POST'])def cputemp():mytemp1 =命令.getoutput('/opt/vc/bin/vcgencmd measure_temp | cut -d"=" -f2 | cut -f1')返回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-模板

例如, cputemp.html 可以简单地是这样的:

 < p> Pi CPU温度为:{{temp}}</p> 

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

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

  function cputemp2(){$ .ajax({输入:"POST",网址:"/cputemp",dataType:"html",成功:function(msg){console.log(msg);$(#swiss").html(msg);},错误:功能(xhr,状态,错误){console.log(错误);}});} 

希望这足以使您前进.

I apologize if this is unclear or anything like that. I'm very very new to web programming of any kind, so please be patient. When a link is clicked, I want to run a python script and then display the results. What is currently happening is it's just returning the HTML page. I have an idea of why but no clue how to fix it. I believe the issue is with the Flask python code, but please any input is appreciated. I will comment the area I believe to be the problem

Flask (Python) code:

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

My question is -- I thought the AJAX code in the test.js file would be handling the call to the python script. All it does is execute the method below the route to that directory in my Flask code. So do I need to run the python code there? How do I do this?

Thank you so much, I'm really lost and stuck on this.

解决方案

There are a few things here that need to be fixed to get things working (or at least how I understand you want them to work).

If you're going to be using Flask, you don't need the route to point to a Python script. You can route to something like /cputemp and then run a function that returns the piece of HTML with the CPU temp that I presume you wanted to display.

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

Don't forget to import commands at the top. Although, you really should be using subprocess instead. https://docs.python.org/2/library/commands.html

The return there uses a Flask template to create the HTML fragment that you want to insert when the AJAX request is successful. http://flask.pocoo.org/docs/0.11/quickstart/#rendering-templates

For example, cputemp.html can simply be something like:

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

Note that I don't know whether that command being assigned to mytemp1 works. That's a separate issue from not being able to display the information you want.

Now for the AJAX part. I added an error handler to help debug further issues. Note that I changed the URL to match the route. Also, using innerHTML has security issues, and rather than concerning yourself with sanitizing what you set innerHTML to, use jQuery's html function. 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);
        }
    });
}

Hope this is enough to get you moving along.

这篇关于执行python脚本-Ajax和Flask的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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