'Create a decorator that will check if the function will run successfully or throws error?

I have to create a decorator for a event in django and store all args, kwargs, status, etc in django model. So far I am able to store args, kwargs and traceback, but challenge is,the event might also fail, so i have to save the status as well ie. success or failed. How do I do that using a decorator?

import inspect
import traceback

def dump_args(func):

    def wrapper(*args, **kwargs):
        func_args = inspect.signature(func).bind(*args, **kwargs).arguments
        func_args_str = ", ".join(map("{0[0]} = {0[1]!r}".format, func_args.items()))
        print(f"{func.__module__}.{func.__qualname__} ( {func_args_str} )")
        return func(*args, **kwargs)

    return wrapper

@dump_args
def test(event, profile=None, loan_request=None, approved_loan=None,
             loan_tranche=None, lead=None, limit_revision=None,
             event_kwargs=None, use_atomic=False):

    try:
        #some event will run
        pass
    except:
        #if event fails
        var = traceback.format_exc()
        print(var)



test(1, 2, 3, 4, 5, d=6, g=12.9)

What I now want is how can get status = Success if the function runs successfully and status = Fail if it fails?



Solution 1:[1]

Maybe something like this would be reasonable if generic.

import inspect
import traceback

def dump_args(func, event):

    def wrapper(*args, **kwargs):
        try:
            func_args = inspect.signature(func).bind(*args, **kwargs).arguments
            func_args_str = ", ".join(map("{0[0]} = {0[1]!r}".format, func_args.items()))
            print(f"{func.__module__}.{func.__qualname__} ( {func_args_str} )")
            func_res = func(*args, **kwargs)
            event.success()
        except:
            var = traceback.format_exc()
            event.fail(var)
            print(var)
        finally:
            return func_res

    return wrapper

@dump_args
def test(event, profile=None, loan_request=None, approved_loan=None,
         loan_tranche=None, lead=None, limit_revision=None,
         event_kwargs=None, use_atomic=False):
    do_something_that_fails()


        

test(1, 2, 3, 4, 5, d=6, g=12.9)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 grishatsu