首页 > 解决方案 > 如何在 Flask Python 中渲染模板然后重定向到外部 URL

问题描述

我正在尝试使用 render_template 将用户重定向到带有加载微调器的网页,然后使用flaskPython 将它们重定向到外部 URL。

我已经编写了下面的代码,它只等待 3 秒然后重定向到youtube.com.

from flask import Flask, redirect, render_template
from time import sleep

app = Flask(__name__)


@app.route('/')
def redirect_to_url():
    render_template('loading_spinner.html')
    sleep(3)
    return redirect("https://youtube.com")


if __name__ == "__main__":
    app.run(debug=True)

有没有人对如何实现这一目标有任何想法?

标签: pythonflask

解决方案


您可以在 javascript 中使用超时。这是示例 loding_spinner.html

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <title>Title</title>
</head>
<body>
Hello
</body>
<script>
   function myFunction() {
   location.replace("https://youtube.com")
   }

   setTimeout(function(){ myFunction(); }, 3000);
</script>
</html>

蟒蛇代码

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def redirect_to_url():
  return render_template('loading_spinner.html')


if __name__ == "__main__":
  app.run(debug=True)

推荐阅读