ChngFong Chia
ChngFong Chia

Reputation: 137

Passing variables to another route in Python Flask during Redirect

I have a function called upload_file_to_s3 that uploads file to my s3 bucket. When I make POST method I would like to upload the file to s3 as well as passing a variable (which is my filename for the file that I uploaded) to my first route "/home". However, I can't just pass the variable in "redirect" right?

Below is the illustration of what I'm trying to achieve:

@app.route("/home")
def home(variable_filename):
    *some functions here using the <variable_filename>*

    return render_template('home.html')

@app.route("/upload", methods=['POST'])
def upload():
    if request.method == "POST":
        f = request.files['file']
        f.save(os.path.join(UPLOAD_FOLDER, f.filename))
        upload_file_to_s3(f"uploads/{f.filename}", BUCKET)

        variable_filename = f.filename

        return redirect("/home",variable_filename)

Your help is much appreciated!

Upvotes: 0

Views: 64

Answers (1)

Ejaz
Ejaz

Reputation: 1632

Pass the variable as part of the url. Update the home route and function as below -

@app.route("/home/<string:variable_filename>")
def home(variable_filename):
    #*some functions here using the <variable_filename>*

    return render_template('home.html')

And further update your upload function's return statement as below -

return redirect("/home/{}".format(variable_filename))

Upvotes: 1

Related Questions