我试图运行一个嵌入HTML代码的Python脚本,但它不起作用。我想要执行Python脚本,同时呈现将由脚本打印的HTML。
app.py
#!/usr/bin/python2.6
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/briefing')
def briefing():
return render_template('briefing.html')
@app.route('/briefing/code')
def app_code():
return render_template('app_code.py')
if __name__ == '__main__':
app.run(debug=True)app_code.py
http://i.stack.imgur.com/sIFFJ.png
当我访问http://127.0.0.1:5000/briefing/code时,结果是http://i.stack.imgur.com/iEKv2.png。
我知道正在发生的事情是,我将呈现为HTML,因此文件中的Python代码没有被解释。
如何在运行app_code.py的同时,从它呈现HTML?
发布于 2016-01-20 18:40:21
你把很多事情搞混了,我看到问题的第一篇文章花了我一段时间才弄清楚你想做什么。
您似乎需要理解的想法是,您需要首先用Python准备模型(例如,字符串、对象、数据集等),然后将其插入要呈现的模板中(而不是打印出您想在HTML输出中看到的内容)。
如果要将来自subprocess.call的输出显示到HTML页面中,请执行以下操作:
app.py
#!/usr/bin/python2.6
import subprocess
from flask import Flask, render_template
app = Flask(__name__)
def get_data():
"""
Return a string that is the output from subprocess
"""
# There is a link above on how to do this, but here's my attempt
# I think this will work for your Python 2.6
p = subprocess.Popen(["tree", "/your/path"], stdout=subprocess.PIPE)
out, err = p.communicate()
return out
@app.route('/')
def index():
return render_template('subprocess.html', subprocess_output=get_data())
if __name__ == '__main__':
app.run(debug=True)subprocess.html
<html>
<head>
<title>Subprocess result</title>
</head>
<body>
<h1>Subprocess Result</h1>
{{ subprocess_output }}
</body>
</html>在上面的模板中,在将生成的{{ subprocess_output }}页面发送到浏览器之前,将由您从Flask视图传递的值替换为HTML。
如何传递多个值
你可以选择render_template('page.html', value_1='something 1', value_2='something 2')
在模板中:{{ value_1 }}和{{ value_2}}
或者您可以传递一个名为“result”的迪克
render_template('page.html, result={'value_1': 'something 1', 'value_2': 'something 2'})
在模板{{ result.value_1 }}和{{ result.value_2 }}中
https://stackoverflow.com/questions/34907338
复制相似问题