Search code examples
pythonfunctionpython-decoratorscherrypy

Using a custom python decorator accepting arguments with a cherrypy exposed endpoint


I am trying to monitor the latency of application using prometheus.There is a decorator function which calculates the time taken for a function to execute.Now as I wrap it with a cherrypy exposed endpoint there is no response from it.

I have also tried to use @cherrypy.tools.register('before_handler') over my decorator and then later attaching it as @cherrypy.tools.monitor_request() but it will through an argument exception as the decorator accepts a function.

def monitor_request(func):
    def inner1(*args, **kwargs):
        begin = time.time()
        func(*args, **kwargs)
        end = time.time()
        diff = end-begin
        REQUEST_LATENCY.labels(func.__name__).observe(diff)
        REQUEST_COUNT.labels(func.__name__).inc()
    return inner1


@cherrypy.expose
@monitor_request
def health1(self):
    """Give back health status"""
    return "is_healthy"

Solution

  • I was not returning the result of response from cherrypy end point which was the issue.The correct code should be.

        def inner1(*args, **kwargs):
            begin = time.time()
            x = func(*args, **kwargs)
            end = time.time()
            diff = end-begin
            REQUEST_LATENCY.labels(func.__name__).observe(diff)
            REQUEST_COUNT.labels(func.__name__).inc()
            return x
        return inner1