Compress result with deflate algorithm if the client ask for it.

def compress(func):
    """Compress result with deflate algorithm if the client ask for it."""
    def wrapper(*args, **kwargs):
        """Wrapper that take one function and return the compressed result."""
        ret = func(*args, **kwargs)
        logger.debug('Receive {} {} request with header: {}'.format(
            request.method,
            request.url,
            ['{}: {}'.format(h, request.headers.get(h)) for h in request.headers.keys()]
        ))
        if 'deflate' in request.headers.get('Accept-Encoding', ''):
            response.headers['Content-Encoding'] = 'deflate'
            ret = deflate_compress(ret)
        else:
            response.headers['Content-Encoding'] = 'identity'
        return ret

    def deflate_compress(data, compress_level=6):
        """Compress given data using the DEFLATE algorithm"""
        # Init compression
        zobj = zlib.compressobj(compress_level,
                                zlib.DEFLATED,
                                zlib.MAX_WBITS,
                                zlib.DEF_MEM_LEVEL,
                                zlib.Z_DEFAULT_STRATEGY)

        # Return compressed object
        return zobj.compress(b(data)) + zobj.flush()

    return wrapper