Sab*_*sla 7 python redirect flask
所以我在 Flask 上运行了这个 python 页面。它工作得很好,直到我想要重定向。
@app.route("/last_visit")
def check_last_watered():
templateData = template(text = water.get_last_watered())
return render_template('main.html', **templateData)
return redirect(url_for('new_page')) #with a delay here of 3 secs
Run Code Online (Sandbox Code Playgroud)
该网站工作正常,但不重定向,我不知道如何延迟整个事情。想法...请:-)
如果您需要渲染模板并在三秒后重定向,您可以传递refresh
时间和url
需要重定向的 URL。
@app.route('/error/', methods=['GET'])
def error():
return render_template('error.html'), {"Refresh": "1; url=https://google.com"}
Run Code Online (Sandbox Code Playgroud)
好吧,您的函数只返回渲染的模板,而永远不会到达重定向语句。如果您想显示页面并在延迟后执行重定向,请在模板中使用 javascript 重定向:
\n@app.route("/last_visit")\ndef check_last_watered():\n templateData = template(text = water.get_last_watered())\n templateData['redirect_url'] = url_for('new_page')\n return render_template('main.html', **templateData)\n
Run Code Online (Sandbox Code Playgroud)\n然后在你的main.html
:
<script>\n setTimeout(function(){\n window.location.href = '{{redirect_url}}';\n }, 2000);\n</script>\n
Run Code Online (Sandbox Code Playgroud)\n更新:另外,看看 Adri\xc3\xa1n 的替代(可能更好)方法,您可以在其中返回Refresh
头以及渲染的模板响应。