【问题标题】:Python/Flask - Make "/index" redirect to "/"Python/Flask - 使“/index”重定向到“/”
【发布时间】:2021-08-09 00:51:27
【问题描述】:

我有一个包含两个网址的索引页面:

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

当我转到https://localhost/ 时,它工作正常,但https://localhost/index 也是有效的。我希望 https://localhost/index 始终重定向到 https://localhost/ 而不必执行以下操作:

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

@app.route('/index')
def index_redirect():
    return redirect(url_for('index'))

【问题讨论】:

  • 我不明白。如果第一个示例有效(并且确实有效),那么问题是什么?
  • 您能解释一下“重定向”是什么意思吗? HTTP 术语有一个特定的含义,返回 301 或 302 状态码并返回一个新的location,但听起来这不是你想要的,那么,你想要什么?

标签: python flask url-routing


【解决方案1】:

当您说“不必做这样的事情”时 - 这正是您需要做的。如果第一个示例不可接受,您只需将浏览器重定向到有效的 URL。

如果您不想访问服务器两次,我想您可以使用 Javascript 的 history.replaceState() 来更改 URL 并摆脱 /index。但这不是您可以在 Flask 中执行的操作。

【讨论】:

    【解决方案2】:

    我认为flask.redirect 是您正在寻找的。​​p>

    可以找到flask.redirect的官方文档here

    您也可以在服务器级别处理此问题。以下是uwsgi 的示例 和nginx

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-26
      • 1970-01-01
      • 1970-01-01
      • 2020-11-20
      • 1970-01-01
      • 2018-02-04
      • 1970-01-01
      • 2022-12-11
      相关资源
      最近更新 更多