运行嵌入在HTML上的Python脚本

iva*_*ncz 3 html python flask

我正在尝试运行嵌入了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)
Run Code Online (Sandbox Code Playgroud)

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?

bak*_*kal 7

您正在做很多事情,我看到问题的第一篇文章花了我一段时间才弄清楚您要做什么。

您似乎需要掌握的想法是,首先需要在Python中准备模型(例如,字符串,对象,字典等以及所需的数据),然后将其注入模板中渲染(而不是打印出您想在HTML输出中看到的内容)

如果要将a的输出显示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)
Run Code Online (Sandbox Code Playgroud)

subprocess.html

#!/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)
Run Code Online (Sandbox Code Playgroud)

在上面的模板中,{{ subprocess_output }}在将结果HTML页面发送到浏览器之前,将替换为您从Flask视图传递的值。

如何传递一个以上的价值

你可以 render_template('page.html', value_1='something 1', value_2='something 2')

和模板:{{ value_1 }}{{ value_2}}

或者您可以传递一个名为eg的字典result

render_template('page.html, result={'value_1': 'something 1', 'value_2': 'something 2'})

而在模板{{ result.value_1 }}{{ result.value_2 }}