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
:
http://i.stack.imgur.com/sIFFJ.png
When I access http://127.0.0.1:5000/briefing/code
the result is http://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?
It is possible to run embed Python within a HTML document that can be executed at run time.
Use the <py-script> tag and then mention the Python code inside the tag. After that you can pass the Python file directly. It will create a widget.
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.
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 }}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With