Nexus

Upload a gzip compressed file to a Nexus Raw repository

I needed to upload a gzipped file to our Nexus repository and was struggling to find the right configuration for the content type. This is the compression function:

def compress_file(input_file, output_file):
    """Comporess the SQL dump"""
    with open(input_file, 'rb') as f_in:
        with gzip.open(output_file, 'wb') as f_out:
            shutil.copyfileobj(f_in, f_out)
    return output_file

My original attempt for uploading the compressed file looked like below, but while Nexus stored the file without an error, the downloaded file was not a valid gzip file.

def upload_to_nexus(file_path, nexus_config):
    """
    Upload the compressed file to Nexus.
    :param file_path:
    :param nexus_config:
    :return:
    """
    """Open the compressed file in binary mode"""
    with open(file_path, 'rb') as f:
        # Define the headers and files for the request
        headers = {'Content-Type': 'application/gzip'}
        files = {'file': (file_path, f)}
        
        response = requests.put(nexus_config['url'],
                                auth=HTTPBasicAuth(nexus_config['user'], nexus_config['password']),
                                files=files, headers=headers)        
        return response

The original attempt used the files parameter files={'file': (filename, f)}, as it would be interpreted as a multipart file upload. Using the data=f parameter as shown below, was sending the file’s contents as raw binary data directly in the request body. This is useful when the server expects the body to contain just the file data, without any additional encoding or form fields. This way, Nexus accepted the upload and the download was also valid.

def upload_to_nexus(file_path, nexus_config):
    """
    Upload the SQL dump file to Nexus.
    :param file_path: Path to the SQL dump file.
    :param nexus_config: Nexus configuration details.
    :return: Response from the server.
    """
    with open(file_path, 'rb') as f:
        # Make the request to upload the file
        response = requests.put(nexus_config['url'],
                                auth=HTTPBasicAuth(nexus_config['user'], nexus_config['password']),
                                data=f)

        if response.status_code == 200:
            logging.info("Uploaded file successfully")
        else:
            logging.error(f"Failed to upload file. Status code: {response.status_code}, Response: {response.text}")
            
        return response