Python Redirect (with Delay)
Solution 1:
Well, your function just returns a rendered template and never reaches the redirect statement. If you want to show a page AND then do a redirect after a delay, use a javascript redirect in your template:
@app.route("/last_visit")defcheck_last_watered():
templateData = template(text = water.get_last_watered())
templateData['redirect_url'] = url_for('new_page')
return render_template('main.html', **templateData)
Then in your main.html
:
<script>setTimeout(function(){
window.location.href = '{{redirect_url}}';
}, 2000);
</script>
UPDATE: Also, have a look at an alternative (and possibly better) way by Adrián, where you can return a Refresh
header along with your rendered template response.
Solution 2:
If you need to render a template and redirect after three seconds you can pass refresh
as time and url
with the URL you need to redirect.
@app.route('/error/', methods=['GET'])deferror():
return render_template('error.html'), {"Refresh": "1; url=https://google.com"}
Solution 3:
You could use a return
statement and return a string format.
As the <redirect url>
you could set any URL from available to your back-end.
This solution is similar to dmitrybelyakov's, but it's a quick fix without having to deal with new, small html templates.
return f"<html><body><p>You will be redirected in 3 seconds</p><script>var timer = setTimeout(function() {{window.location='{ <redirect url> }'}}, 3000);</script></body></html>"
Example:
Lets say you want to submit a form and have a run time issue that requires you to do this redirect after a certain time.
@app.route('/')defyour_func():
form = FormFunc()
if form.validate_on_submit():
# do something
wait_time = 3000
seconds = wait_time / 1000
redirect_url = 'https://www.example.com/'# if the validation is successful, forward to redirect page, wait 3 seconds, redirect to specified urlreturnf"<html><body><p>You will be redirected in { seconds } seconds</p><script>var timer = setTimeout(function() {{window.location='{ redirect url }'}}, { wait_time });</script></body></html>"# if the validation is not successful, reload the formreturn render_template('formPage.html', form=form)
Post a Comment for "Python Redirect (with Delay)"