librelist archives

« back to archive

accessing request object within custom decorator

accessing request object within custom decorator

From:
Cornelius Kölbel
Date:
2014-12-18 @ 12:23
Hi,

this question may not be explicitly flask specific, but it came up with
my flask project.

I am writing a flask app and I'd like to do some sanity checks for a
bunch of endpoints.
In some scenarios I am using the before_request function which works
fine and makes sense. But in this case not all endpoints of the
blueprint are supposed to get checked.
So I thought I could use a decorator.

Roughly I created a decorator like this:

class check_user_or_serial_in_request(object):
    """
    Decorator to check user and serial in a request.
    If the request does not contain a serial number (serial) or a user
    (user) it will throw a ParameterError.
    """

    def __init__(self, params=None):
        self.params = params

    def __call__(self, func):
        @functools.wraps(func)
        def check_request_wrapper(*args, **kwds):
            user = self.params.get("user")
            serial = self.params.get("serial")
            if not serial and not user:
                raise ParameterError("You need to specify a serial or a user.")
            f_result = func(*args, **kwds)
            return f_result

        return check_request_wrapper

I thought to use it this way:

@validate_blueprint.route('/check', methods=['POST'])
@check_user_or_serial_in_request(request.values)
def check():
    user = get_user_from_param(request.values)
    serial = getParam(request.values, "serial")
    password = getParam(request.values, "password")

    return send_result(True)

But I get a RuntimeError('working outside of request context').

I guess that the decorator is parsed before the code actually runs and
thus I can not access the request.values outside of the request context.
How would you recommend accessing the request object from within a
decorator?
Is it possible at all without importing the request from flask from
within the decorator, to avoid dependencies to flask in my decorator module?

Thanks a lot and kind regards
Cornelius

Re: [flask] accessing request object within custom decorator

From:
Daniel Neuhäuser
Date:
2014-12-18 @ 14:47
> I guess that the decorator is parsed before the code actually runs and 
thus I can not access the request.values outside of the request context.
Indeed.

> How would you recommend accessing the request object from within a decorator?
Importing it.

> Is it possible at all without importing the request from flask from 
within the decorator, to avoid dependencies to flask in my decorator 
module?
No.