Search code examples
pythonflaskflask-restful

Flask-RESTful can we call a method before get and post in Ressource?


I'm using Flask-RESTful in my app.

I would want to call a method before each Ressource post and get so my code is not duplicated.

So basically here is what I have:

class SomeClass(Resource):
    def __init__():
        # Some stuff

    def get(self, **kwargs):
        # some code

    def post(self, **kwargs):
        # the same code as in get method

I would like to have a method call before get and post so my code is not duplicated.

Is there any way I can achieve to do that ?


Solution

  • Try writing a decorator function and use it with your get() and post() methods. More info here.

    A decorator is more like a wrapper to your function, where your function is wrapped in a function that returns your function.

    Say, you want to do some validation before processing, you can write a decorator like this:

    from functools import wraps
    
    def validate(actual_method):
        @wraps(actual_method)  # preserves signature
        def wrapper(*args, **kwargs):
            # do your validation here
    
            return actual_method(*args, **kwargs)
    
        return wrapper
    

    then, using it in your code is as simple as:

    class SomeClass(Resource):
        def __init__():
            # Some stuff
    
        @validate
        def get(self, **kwargs):
            # some code
    
        @validate
        def post(self, **kwargs):
            # the same code as in get method