flask before request - add exception for specific route

前端 未结 3 976
忘掉有多难
忘掉有多难 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 21:56

    There are a couple of properties on the request object you can check, documented here, request.path is probably what you want. Can I suggest request.endpoint though, so you'll be covered should you decide to route your view to another url, or multiple urls

    @app.before_request
    def before_request():
        if 'logged_in' not in session and request.endpoint != 'login':
            return redirect(url_for('login'))
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-04 22:02

    Here's an implementation of the accepted answer with flask-login:

    @app.before_request
    def require_authorization():
        from flask import request
        from flask.ext.login import current_user
    
        if not (current_user.is_authenticated or request.endpoint == 'login'):
            return login_manager.unauthorized()
    
    0 讨论(0)
提交回复
热议问题