我想做的是类似于回应。重定向作为在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)

当前回答

Flask包含用于重定向到任何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)

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

重定向方法默认接受代码302。http状态代码列表。

其他回答

从Flask API文档(v. 2.0.x):

flask.redirect(location, code=302, Response=None) Returns a response object (a WSGI application) that, if called, redirects the client to the target location. Supported codes are 301, 302, 303, 305, and 307. 300 is not supported because it’s not a real redirect and 304 because it’s the answer for a request with a request with defined If-Modified-Since headers. New in version 0.6: The location can now be a unicode string that is encoded using the iri_to_uri() function. Parameters: location – the location the response should redirect to. code – the redirect status code. defaults to 302. Response (class) – a Response class to use when instantiating a response. The default is werkzeug.wrappers.Response if unspecified.

#!/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)

请查看文档中的示例。

为此,您可以简单地使用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,因为调试器输出在找出错误时很有帮助。

你必须返回一个重定向:

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)

请参阅有关flask文档的文档。code的默认值是302,因此code=302可以被省略或替换为其他重定向代码(301、302、303、305和307中的一个)。

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

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

在用户应获授权的情况下

首先让我们假设你有一条被保护的路由,你像这样保护它。

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用户得到一个unathecated的响应,那么它 到前端处理Unath错误..