在 Flask 中重定向到 URL

2025-02-28 08:23:00
admin
原创
61
摘要:问题描述:我正在尝试做Response.redirect与 C# 中等效的事情 - 即:重定向到特定的 URL - 我该怎么做呢?这是我的代码:import os from flask import Flask app = Flask(__name__) @app.route('/') def hello...

问题描述:

我正在尝试做Response.redirect与 C# 中等效的事情 - 即:重定向到特定的 URL - 我该怎么做呢?

这是我的代码:

import os
from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello():
    return 'Hello World!'

if __name__ == '__main__':
    # Bind to PORT if defined, otherwise default to 5000.
    port = int(os.environ.get('PORT', 5000))
    app.run(host='0.0.0.0', port=port)

解决方案 1:

您必须返回重定向:

import os
from flask import Flask,redirect

app = Flask(__name__)

@app.route('/')
def hello():
    return redirect("http://www.example.com", code=302)

if __name__ == '__main__':
    # Bind to PORT if defined, otherwise default to 5000.
    port = int(os.environ.get('PORT', 5000))
    app.run(host='0.0.0.0', port=port)

代码的默认值为 302,因此code=302可以省略或用其他重定向代码(301、302、303、305 和 307 中的一个)替换。

请参阅flask docs 上的文档。

解决方案 2:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
from flask import Flask, redirect, url_for

app = Flask(__name__)

@app.route('/')
def hello():
    return redirect(url_for('foo'))

@app.route('/foo')
def foo():
    return 'Hello Foo!'

if __name__ == '__main__':
    # Bind to PORT if defined, otherwise default to 5000.
    port = int(os.environ.get('PORT', 5000))
    app.run(host='0.0.0.0', port=port)

看一下文档中的示例。

解决方案 3:

来自Flask API 文档(v. 2.0.x):

flask.redirect (,,)location`code=302`Response=None

返回一个响应对象(WSGI 应用程序),如果调用该对象,则将客户端重定向到目标位置。支持的代​​码为 301、302、303、305 和 307。不支持 300,因为它不是真正的重定向;不支持 304,因为它是带有已定义 If-Modified-Since 标头的请求的答案。

0.6 版中的新功能:位置现在可以是使用 iri_to_uri() 函数编码的 unicode 字符串。

参数:

  • location– 响应应重定向到的位置。

  • code– 重定向状态代码。默认为 302。

  • Response(class) – 实例化响应时使用的 Response 类。如果未指定,则默认为 werkzeug.wrappers.Response。

解决方案 4:

我认为这个问题值得更新,只需与其他方法进行比较。

以下是在 Flask(0.12.2)中从一个 URL 重定向(3xx)到另一个 URL 的方法:

#!/usr/bin/env python

from flask import Flask, redirect

app = Flask(__name__)

@app.route("/")
def index():
    return redirect('/you_were_redirected')

@app.route("/you_were_redirected")
def redirected():
    return "You were redirected!"

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8000, debug=True)

官方文件在这里。

解决方案 5:

flask.redirect(location, code=302)

文档可以在这里找到。

解决方案 6:

Flask 包含redirect重定向到任意 URL 的功能。此外,你可以使用以下错误代码提前中止请求abort

from flask import abort, Flask, redirect, url_for

app = Flask(__name__)

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

@app.route('/hello'):
def world:
    abort(401)

默认情况下,每个错误代码都会显示黑白错误页面。

redirect方法默认采用代码 302。此处是http 状态代码的列表。

解决方案 7:

如果你只想重定向到一个没有任何状态代码或类似内容的 URL,你可以简单地说

from flask import Flask, redirect

app = Flask(__name__)

@app.route('/')
def redirect_to_link():
    # return redirect method, NOTE: replace google.com with the link u want
    return redirect('https://google.com')

以下是 Flask 文档的链接,了解更多解释

解决方案 8:

为此,您只需使用redirect包含在flask

from flask import Flask, redirect

app = Flask(__name__)

@app.route('/')
def hello():
    return redirect("https://www.exampleURL.com", code = 302)

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

另一个有用的提示(因为您是 flask 新手)是在初始化 flask 对象后添加,app.debug = True因为调试器输出在找出错误时会很有帮助。

解决方案 9:

有两种方法可以重定向到 Flask 中的 URL。

  1. 例如,您想在用户登录后将其重定向到另一条路线等。

  2. 您可能还希望将用户重定向到需要某些变量的路线,例如: @app.route('/post/<string:post_id>')

好吧,要实现案例#1的Flask重定向,很简单,只需执行以下操作:

from flask import Flask,redirect,render_template,url_for
app = Flask(__name__)


@app.route('/login')
def login():
    # if user credentials are valid, redirect to user dashboard
    if login == True:
       return redirect(url_for(app.dashboard))
    else:
       print("Login failed !, invalid credentials")
    return render_template('login.html',title="Home Page")


@app.route('/dashboard')
def dashboard():
    return render_template('dashboard.html',title="Dashboard")

要实现案例 #2 的 Flask 重定向,请执行以下操作

from flask import Flask,redirect,render_template,url_for
app = Flask(__name__)


@app.route('/home')
def home():
    # do some logic, example get post id
    if my_post_id:
       # **Note:** post_id is the variable name in the open_post route
       # We need to pass it as **post_id=my_post_id**
       return redirect(url_for(app.open_post,post_id=my_post_id))
    else:
       print("Post you are looking for does not exist")
    return render_template('index.html',title="Home Page")


@app.route('/post/<string:post_id>')
def open_post():
    return render_template('readPost.html',title="Read Post")

同样的事情也可以在视图中完成

<a href="{{url_for(app.open_post,post_id=my_post_id)}}"></a>

请注意:重定向时始终使用app.homeapp.something..(路由或视图函数名称),而不是使用。原因是,如果您出于某种原因redirect("/home")将路由示例从 修改为,那么您的代码将会中断,"/home"`"/index/page"`

解决方案 10:

你可以这样使用:

import os
from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello():
     # Redirect from here, replace your custom site url "www.google.com"
    return redirect("https://www.google.com", code=200)

if __name__ == '__main__':
    # Bind to PORT if defined, otherwise default to 5000.
    port = int(os.environ.get('PORT', 5000))
    app.run(host='0.0.0.0', port=port)

这是该代码的参考链接。

解决方案 11:

如何在 Flask 中重定向用户/请求

在 API 处理函数中抛出错误会将用户重定向到错误处理程序,该处理程序可以处理重定向。或者,您可以redirect像其他人所说的那样直接调用,但这是重定向未经授权用户的另一种方式。为了说明我的意思,我在下面提供了一个示例。

在需要授权用户的情况下

首先让我们假设您有一条受保护的路线,并且您像这样进行保护。

def handle_api_auth(func):
    """
    **handle_api_auth**
        wrapper to handle public api calls authentications

    :param func: a function to be wrapped
    :return: wrapped function
    """

    @functools.wraps(func)
    def auth_wrapper(*args, **kwargs):
        api_key: Optional[str] = request.headers.get('x-api-key')
        secret_token: Optional[str] = request.headers.get('x-secret-token')
        domain: Optional[str] = request.base_url
        if is_request_valid(api_key=api_key, secret=secret_token, domain=domain):
            return func(*args, **kwargs)
        # NOTE: throwing an Error Here will redirect your user to an error handler or alteratively you can just call redirect like everyone else is saying, but this is another way of redirecting unathorized users
        message: str = "request not authorized"
        raise UnAuthenticatedError(status=error_codes.un_auth_error_code, description=message)

    return auth_wrapper

is_request_valid的定义如下

@app_cache.cache.memoize(timeout=15 * 60, cache_none=False)  # timeout equals fifteen minutes // 900 seconds
def is_request_valid(api_key: str, secret: str, domain: str) -> bool:
    """
    **is_api_key_valid**
        validates api keys on behalf of client api calls

    :param api_key: str -> api_key to check
    :param secret: str -> secret token
    :param domain: str -> domain registered for the api_key and secret_token
    :return: bool -> True if api_key is valid
    """

    organization_id: str = config_instance.ORGANIZATION_ID
    # NOTE: lets assumy api_keys_view.get_api_key will return the api keys from some database somewhere
    response = api_keys_view.get_api_key(api_key=api_key, organization_id=organization_id)

    response_data, status_code = response
    response_dict = response_data.get_json()

    if not response_dict.get('status'):
        return False

    api_instance: dict = response_dict.get('payload')
    if not isinstance(api_instance, dict):
        return False

    domain: str = domain.lower().strip()
    # NOTE accessing the keys this way will throw ValueError if keys are not available which is what we want
    # Any Error which gets thrown Ridirects the Users from the path the user is on to an error handler.
    is_secret_valid: bool = hmac.compare_digest(api_instance['secret_token'], secret)
    is_domain_valid: bool = hmac.compare_digest(api_instance['domain'], domain)
    _request_valid: bool = is_secret_valid and is_domain_valid

    return not not api_instance.get('is_active') if _request_valid else False

像这样定义你的错误处理程序

from flask import Blueprint, jsonify, request, redirect
from werkzeug.exceptions Unauthorized

error_handler = BluePrint('error_handlers', __name__)

@error_handler.app_errorhandler(Unauthorized)
def handle_error(e : Unauthorized) -> tuple:
    """default unath handler"""
    return jsonify(dict(message=e.description)), e.code if request.headers.get('content-type') == 'application/json' else redirect('/login')

处理其他错误相同,并注意,如果请求

不是 json,用户会被重定向到登录页面,如果 json 向用户发送了未登录的响应,那么就由前端来处理 Unath 错误。

相关推荐
  政府信创国产化的10大政策解读一、信创国产化的背景与意义信创国产化,即信息技术应用创新国产化,是当前中国信息技术领域的一个重要发展方向。其核心在于通过自主研发和创新,实现信息技术应用的自主可控,减少对外部技术的依赖,并规避潜在的技术制裁和风险。随着全球信息技术竞争的加剧,以及某些国家对中国在科技领域的打压,信创国产化显...
工程项目管理   2941  
  为什么项目管理通常仍然耗时且低效?您是否还在反复更新电子表格、淹没在便利贴中并参加每周更新会议?这确实是耗费时间和精力。借助软件工具的帮助,您可以一目了然地全面了解您的项目。如今,国内外有足够多优秀的项目管理软件可以帮助您掌控每个项目。什么是项目管理软件?项目管理软件是广泛行业用于项目规划、资源分配和调度的软件。它使项...
项目管理软件   1803  
  PLM(产品生命周期管理)系统在企业的产品研发、生产与管理过程中扮演着至关重要的角色。然而,在实际运行中,资源冲突是经常会遇到的难题。资源冲突可能导致项目进度延迟、成本增加以及产品质量下降等一系列问题,严重影响企业的效益与竞争力。因此,如何有效应对PLM系统中的资源冲突,成为众多企业关注的焦点。接下来,我们将详细探讨5...
plm项目管理系统   31  
  敏捷项目管理与产品生命周期管理(PLM)的融合,正成为企业在复杂多变的市场环境中提升研发效率、增强竞争力的关键举措。随着技术的飞速发展和市场需求的快速更迭,传统的研发流程面临着诸多挑战,而将敏捷项目管理理念融入PLM,有望在2025年实现研发流程的深度优化,为企业创造更大的价值。理解敏捷项目管理与PLM的核心概念敏捷项...
plm项目   31  
  模块化设计在现代产品开发中扮演着至关重要的角色,它能够提升产品开发效率、降低成本、增强产品的可维护性与可扩展性。而产品生命周期管理(PLM)系统作为整合产品全生命周期信息的关键平台,对模块化设计有着强大的支持能力。随着技术的不断发展,到 2025 年,PLM 系统在支持模块化设计方面将有一系列令人瞩目的技术实践。数字化...
plm软件   28  
热门文章
项目管理软件有哪些?
曾咪二维码

扫码咨询,免费领取项目管理大礼包!

云禅道AD
禅道项目管理软件

云端的项目管理软件

尊享禅道项目软件收费版功能

无需维护,随时随地协同办公

内置subversion和git源码管理

每天备份,随时转为私有部署

免费试用