DEV Community

Developer213
Developer213

Posted on • Edited on

Add files to GitHub


.py

import requests
import base64

# GitHub API details
base_url = 'https://github.thecompany.com/api/v3'
repo_owner = 'HID'
repo_name = 'ai_dags'
branch_name = 'dev'
personal_access_token = 'your_personal_access_token'

# Files to upload into the deployment folder
files_to_upload = {
    'deployment/model_name.py': 'local_path_to_model_name.py',
    'deployment/model_name_setup.py': 'local_path_to_model_name_setup.py'
}

sha = None  # Initialize sha outside the loop

for file_path, local_file_path in files_to_upload.items():
    try:
        # Read and encode the file
        with open(local_file_path, 'rb') as file:
            encoded_content = base64.b64encode(file.read()).decode('utf-8')

        headers = {
            'Authorization': f'token {personal_access_token}',
            'Accept': 'application/vnd.github.v3+json',
        }

        # Get the current file SHA (if it exists)
        get_url = f"{base_url}/repos/{repo_owner}/{repo_name}/contents/{file_path}?ref={branch_name}"
        response = requests.get(get_url, headers=headers)

        if response.status_code == 200:
            sha = response.json().get('sha')

        # Prepare the commit data
        commit_data = {
            "message": f"Uploading {file_path} from Jupyter Notebook",
            "content": encoded_content,
            "branch": branch_name,
        }
        if sha:
            commit_data["sha"] = sha

        # Upload the file
        put_url = f"{base_url}/repos/{repo_owner}/{repo_name}/contents/{file_path}"
        response = requests.put(put_url, json=commit_data, headers=headers)

        if response.status_code in [200, 201]:
            print(f"File '{file_path}' uploaded successfully.")
        else:
            print(f"Failed to upload '{file_path}'. Status code: {response.status_code}, Response: {response.text}")

    except Exception as e:
        print(f"An error occurred while uploading '{file_path}': {e}")

        # Reset sha after each upload
        sha = None
Enter fullscreen mode Exit fullscreen mode

Top comments (0)