首页 > 解决方案 > 使用烧瓶/python重定向到外部链接的问题

问题描述

我正在做一个项目,对烧瓶比较陌生。我有一个输出数据框的 python 脚本,这一切都适用于我的 HTML 代码。我遇到的问题是我需要重新路由到外部链接。如果我输出指向诸如变量 =“www.google.com”之类的站点的链接,我的烧瓶代码可以正常工作,但它确实可以与变量 = 预测 ['Link'][0] 一起正常工作。我得到 http://127.0.0.1:5000/stringOutputofPrediction 而不是 http://stringOutputofPrediction 任何帮助将不胜感激,因为我已经把头撞在墙上几个小时了。这是我的html代码:

  <div class="inner">
       <h3>{{prediction['Episode'][0]}}</h3>
       <p>{{prediction['Description'][0]}}</p>
       <a href= "{{ url_for('go_outside_flask_method', variable = prediction['Link'][0]) }}" >Watch</a>
  </div>

烧瓶/Python脚本:

@app.route('/<string:variable>',)
def go_outside_flask_method(variable):
    variable = 'https://'+ variable
    return redirect(variable, code = 307)  

标签: pythonhtmlflask

解决方案


在这种情况下,我会做这样的事情

from flask import Flask, render_template, redirect, request


app = Flask(__name__)


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


@app.route('/redirect_to')
def redirect_to():
    link = request.args.get('link', '/')
    new_link = 'http://' + link
    return redirect(new_link), 301

请注意,我不希望link在我的链接中,我希望它在request.args我提取它并将客户端重定向到烧瓶应用程序之外的新链接的地方。此外,如果未提供链接,则我将重定向到该index页面。

HTML会是这样的

<html>
    <body>
        <a href="{{ url_for('redirect_to', link='google.com')}}">Redirect me to</a>
    </body>
</html>

Ps 你应该确保你variable = prediction['Link'][0])的确实是你所期望的,在到达后端路由stringOutputofPrediction时尝试调试。variable/linkredirect_to


推荐阅读