5

I'm trying to run a Python script with HTML code embedded and it's not working. I'm want to execute a Python script and at the same time render the HTML which will be printed by the script.

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:

https://i.stack.imgur.com/sIFFJ.png

When I access http://127.0.0.1:5000/briefing/code the result is https://i.stack.imgur.com/iEKv2.png.

I know that what is happening is that I'm rendering as HTML and therefore the Python code inside of the file is not being interpreted.

How can I run the app_code.py and at the same time, render the HTML from it?

ivanleoncz
  • 9,070
  • 7
  • 57
  • 49

1 Answers1

9

You are mixing up a lot of things, I saw the first post of the question took me a while to figure out what you are trying to do.

The idea that you seem to need to grasp is that, you'll need to prepare the model in Python first (e.g. a string, an object, a dict etc with the data you want), and then inject it into a template to be rendered (as opposed to printing out what you want to see in the HTML output)

If you want to display the output from a subprocess.call into an HTML page, here's what you should do:

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>

In the above template, {{ subprocess_output }} will be replaced by the value you pass from your Flask view before the resulting HTML page is sent to the browser.

How to pass more than one value

You can either render_template('page.html', value_1='something 1', value_2='something 2')

and in the template: {{ value_1 }} and {{ value_2}}

Or you can pass a dict called e.g. result:

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

and in the template {{ result.value_1 }} and {{ result.value_2 }}

Community
  • 1
  • 1
bakkal
  • 54,350
  • 12
  • 131
  • 107