【发布时间】: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