首页 > 解决方案 > 将 Flask 路由重定向到外部 URL

问题描述

我有以下路由,它应该将用户重定向到外部 URL(我在这里使用 Apple 的 URL 作为示例) -

import flask
from flask import Flask, jsonify, Response, render_template
import pymongo
from pymongo import MongoClient
from bson import ObjectId, json_util
import json

cluster = pymongo.MongoClient("mongodb+srv://USERNAME:PASSWORD@cluster0.mpjcg.mongodb.net/<dbname>?retryWrites=true&w=majority")
db = cluster["simply_recipe"]
collection = db["recipes_collection"]

app = Flask(__name__)

# This route returns the team's index page
@app.route("/")
def home():
    return render_template('index.html')

# This route returns heesung's plot page of the team's website
@app.route("/heesung")
def heesung():
    return redirect("http://www.apple.com")

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

问题:当我导航到我的终端时,
我不断收到"GET /heesung/ HTTP/1.1" 404 -localhost/heesung

注意:
我知道还有其他类似性质的问题,对于那些,我已经按照步骤操作,但它们是旧帖子,所以我想知道 Flask 是否改变了任何东西。我找不到任何确定的文件。

标签: flaskredirect

解决方案


return redirect("http://www.apple.com")这与线路无关。

GET /heesung/ HTTP/1.1" 404当我导航到我的 localhost/heesung 时,我的终端中不断出现-

该终端输出表明您正在点击/heesung/(带有斜杠)。

使用装饰器:

@app.route("/heesung")
  • 请求/heesung将成功
  • 请求/heesung/遗嘱 404。

而是使用装饰器:

@app.route("/heesung/")
  • 请求/heesung/将成功
  • 请求/heesung将发出“308 永久重定向”到/heesung/

选择最适合您的用例的。


推荐阅读