-1

I'm attempting to redirect to an external site (ex: google.com) via flask after a python script succeeds in the background. i'm not sure how to redirect and render a template at the same time .

Here's the flask code:


@app.route ("/result",methods=['POST','GET'])  
def result():
    if request.method == "POST":
        ip1=request.form.get('ip')
        output=subprocess.getstatusoutput(["ping -c 2 " +str(ip1)])
        out=output[1]
        ec=output[0]
        return render_template("home.html",out=output[1])
        sleep(3)                                            // Time given so that the output of ping command above gets printed in html page 
        return redirect ("http://www.google.com/",code=307) // Sample External site
 

The above code works till rendering the page "home.html" and prints the output from "ping" command , but doesn't redirect upon successful execution . Is there a way where we can get the redirect based on the exit code of a command's success or show a failure message on error exit code       
shreesh
  • 53
  • 6

1 Answers1

1

I believe that when you return the template at line (-3), your method finishes.

It seems to me that you want to send a redirect header to the client, but you already have sent some stuff. You cannot do it.

My idea: keep the return render_template part and perform the redirect later by javascript (check here)

Roberto
  • 86
  • 1
  • 7
  • thank you for your response . redirection by javascript does work, but is there a way the redirection can work only if the subprocess in flask app succeeds ? – shreesh Nov 22 '21 at 13:35
  • Flask redirection works by sending HTTP headers to the client. Therefore, it can work only if you don't need to write anything on the client. If this is the case, try: from flask import Flask,redirect return redirect("http://www.stackoverflow.com") – Roberto Nov 22 '21 at 14:54
  • i modified the code a bit , and redirection works as you mentioned :) . also is there a way where we can get the form inputs from one route to work on another route ? like for example -> ip1=request.form.get('ip') from route(/home) to another route (/redir) on flask ? – shreesh Nov 22 '21 at 17:04