flask before request - add exception for specific route

前端 未结 3 1002
忘掉有多难
忘掉有多难 2020-12-04 20:56

In the before_request() function (below), I want to redirect the user to /login if they are not yet logged in. Is there a special variable that wil

3条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-04 22:01

    You can use a decorator. Here's an example that shows how to check an API key before specific requests:

    from functools import wraps
    
    def require_api_key(api_method):
        @wraps(api_method)
    
        def check_api_key(*args, **kwargs):
            apikey = request.headers.get('ApiKey')
            if apikey and apikey == SECRET_KEY:
                return api_method(*args, **kwargs)
            else:
                abort(401)
    
        return check_api_key
    

    And you can use it with:

    @require_api_key
    

提交回复
热议问题