代码之家  ›  专栏  ›  技术社区  ›  ivanleoncz velhala

是否可以在HTML上嵌入和运行Python代码?

  •  5
  • ivanleoncz velhala  · 技术社区  · 9 年前

    我正在尝试运行一个嵌入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代码没有被解释。

    我如何运行 应用程序代码.py 同时,从中呈现HTML?

    1 回复  |  直到 4 年前
        1
  •  9
  •   Community CDub    8 年前

    你把很多事情搞混了,我看到问题的第一个帖子花了我一段时间才弄明白你想做什么。

    你似乎需要理解的是,你需要准备 模型 首先在Python中(例如,包含所需数据的字符串、对象、dict等),然后将其注入 样板 要呈现的内容(而不是打印出您希望在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}}

    或者你可以传递一个名为例如的dict。 result :

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

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