Gissipi_453
Gissipi_453

Reputation: 1340

writing Flask console logs to an HTML template as and when it appears

I have a Flask App that runs 2 shell scripts and renders an HTML template index.html.

import subprocess
from flask import Flask, request, render_template  
  
app = Flask(__name__)        

@app.route('/result', methods =["POST"]) 
def process_html_input(): 
    if request.method == "POST": 
        git_url = request.form.get("giturl") 
        subprocess.call(['sh', 'installer_script1.sh']) 
        subprocess.call(['sh', 'installer_script2.sh']) 
    return render_template("index.html") 
    
if __name__=='__main__': 
    app.run() 

I want to print the content of the Python console as and when it appears (while the script is executing) to the same HTML template index.html -

<html lang="en">
  <body>
        
  </body>
</html>

I'm unable to write it, can someone help me with the python and HTML code ? I have tried this but unable to make it work.

Upvotes: 3

Views: 991

Answers (1)

Soroosh Khodami
Soroosh Khodami

Reputation: 1333

Check the following code that runs one command, try it, and if it worked you can put other commands as well.

Notes:

  • Yield is a generator function, it helps you to get the result of the subprocess.
  • Using -u switch when you want to run the shell in order to prevent output buffering.
import subprocess
from flask import Flask, request, render_template  
  
app = Flask(__name__)        

@app.route('/result', methods =["POST"]) 
def process_html_input(): 
    
    def inner():
        git_url = request.form.get("giturl") 
        command = ['sh', '-u installer_script1.sh'] # -u: avoid buffering the output 
        
        proc = subprocess.Popen(
            cmd,
            stdout=subprocess.PIPE,
        )
        
        for line in proc.stdout:
            yield highlight(line, BashLexer(), HtmlFormatter())
        
    env = Environment(loader=FileSystemLoader('app/templates'))
    tmpl = env.get_template('index.html')
    return Response(tmpl.generate(result=inner())) 
    
if __name__=='__main__': 
    app.run() 

Also, you can check and use the proposed solution of the following link:

HTTP streaming of command output in Python Flask

Upvotes: 2

Related Questions