I developed a flask app which runs a mathematical optimization script (PuLP
+ Python) for user provided data input. Since the computation takes quite a while, I want to display the optimizer's print statements constantly (without refreshing) on my webpage.
Based on this solution I managed to run a subprocess
with my .py
script. Within this script, the print()
statement does what it should, however I can only see the output in the command line. By using flash()
I managed to display the output, yet it gets rendered only once the computation has finished and the page is reloaded. I try to output the print()
statements in realtime within my HTML. Is there a way to achieve this?
Thanks!
Excerpt from routes.py
:
@app.route('/optimize', methods=['GET', 'POST'])
def solve():
path = os.path.join(app.root_path, 'optimization', 'assets')
file = "test.py"
execute(file, path)
return redirect(url_for('home'))
The execute(file,path)
function:
import os
import subprocess as sub
def execute(command, directory):
# change directory to execute the command
os.chdir(directory)
proc = sub.Popen(['python','-u', command], stdout=sub.PIPE, universal_newlines=True) # Python 2: bufsize=1
for stdout_line in proc.stdout:
print(stdout_line.rstrip() + '\n')
flash(stdout_line.rstrip(), 'python_print')
proc.stdout.close()
return_code = proc.wait()
if return_code:
raise sub.CalledProcessError(return_code, command)
And finally my HTML
which is rendered in the home
route:
{% with prints = get_flashed_messages(category_filter=["python_print"]) %}
{% if prints %}
<div class="content-section">
<h3>Solver Status</h3>
<ul>
{%- for message in prints %}
<li>{{ message }}</li>
{% endfor -%}
</ul>
</div>
{% endif %}
{% endwith %}