我正在做 Flask URL 重定向
问题:如何让 Flask URLs 重定向, 从本地localhost 到online 也能有效果?例如让线上的 WinSCP 中做同样的事情
大多数网上的演示都是在本地运行http://127.0.0.1:5000/
中运行的 py 脚本
from flask import Flask, redirect, url_for
app = Flask(__name__)
@app.route("/")
def index():
return "hello world!"
@app.route("/english/start")
def go_to_DK_page():
return redirect("http://192.168.0.206:8080/english/product_dk.html")
if __name__ == "__main__":
app.run(debug=True)
因此我希望将其在线上也有一样效果,匹如,将下面的 .html 发布到 WinSCP (或如果还有其他方法也请跟我说)
<script type=module src=main_joy_01_12.js>script><my-header>my-header>fix title/contaxt
this is the data extract from mysql: Nordic85678
script>
from flask import Flask, redirect, url_for
app = Flask(__name__)
@app.route("/")
def index():
return "hello world!"
@app.route("/english/start")
def go_to_DK_page():
return redirect("http://192.168.0.206:8080/english/product_dk.html")
if __name__ == "__main__":
app.run(debug=True)
script>
<my-footer>my-footer>
首先,您需要将您的网络配置为公共网络,这样您的虚拟机就能与外界通信。
其次,在代码中,您需要将app.run()中的参数host改为0.0.0.0,这样可以允许外界访问您的Flask服务。
示例代码:
if __name__ == "__main__":
app.run(debug=True, host='0.0.0.0')
最后,您需要将路由重定向的URL更改为您的公网IP地址,这样外界才能访问到重定向的页面。
示例代码:
@app.route("/english/start")
def go_to_DK_page():
return redirect("http://your_public_ip:8080/english/product_dk.html")
此外,如果您要在线上部署,建议使用类似gunicorn这样的生产级Web服务器来部署您的Flask应用程序。
我自己常用两种方案,能对您的思路有帮助的话请采纳:
requests
这类的http请求库把网页内容请求下来@app.route("/english/start")
def go_to_DK_page():
mData = requests.get('http://192.168.0.206:8080/english/product_dk.html').text
# 然后直接把这个mData和普通文本一样返回给网页即可
return mData
谢谢各位的解惑,我希望用一天的时间去研究哪种方式更适配我的情况,那再进行结题,选最优解这样,请稍微等等,如果后续也有大神想补充也非常欢迎
根据你的描述,这是一个后端应用与前端静态文件结合的 Web 项目。
对于这种情况,在 Flask 后端中使用 redirect()
进行 HTTP 3xx 重定向是不恰当的。因此我们需要使用反向代理程序,这通常是 Nginx 和 Apache,如果你愿意体验新事物,Caddy 作为后起之秀也是个不错的选择。
以 Nginx 为例:
首先定义一个 location,通过 proxy_pass 方法指向后端的 Flask 应用,并命名为 @flask
:
location @flask {
proxy_pass http://127.0.0.1:5000; # 5000 is the listening port of your Flask app
}
随后使用 try_files
方法,先检测本地的对应路径下有没有名称相符的文件:
location / {
try_files $uri $uri/ @flask;
}
最后,别忘了在 server
块中加入 root
、index
还有其他的必要信息。然后就可以愉快地启动 Nginx 了。
现在假设你完成了配置,并且它其中主要的一部分看起来是这样的:
server {
listen 80;
index index.html;
root /data/wwwroot/your_site; # where your static file is located, e.g.in this case your product_dk.html is at "/data/wwwroot/your_site/english/product_dk.html"
# ... other config ...
location @flask {
proxy_pass http://127.0.0.1:5000;
}
location / {
try_files $uri $uri/ @flask;
}
# ... other config ...
}
http://localhost/english/product_dk.html
,页面应该正常显示。http://localhost/
,你将看到 hello world!
。很高兴能够帮到你!如果你遇到了任何问题,欢迎留言沟通!