Quantcast
Channel: Zammad - Community - Latest posts
Viewing all articles
Browse latest Browse all 6760

Export/Import Overviews using the rails console

$
0
0

Changed the code to make it work better:

import json
import requests
from requests.exceptions import HTTPError

# Function to load JSON data from a file
def load_json_from_file(file_path):
    try:
        with open(file_path, 'r') as file:
            json_data = json.load(file)
        return json_data
    except FileNotFoundError:
        print(f"Error: The file '{file_path}' was not found.")
        return None
    except json.JSONDecodeError:
        print(f"Error: The file '{file_path}' does not contain valid JSON.")
        return None

# Function to delete all overviews from the API endpoint
def delete_all_overviews(api_url, api_token):
    headers = {
        'Content-Type': 'application/json',
        'Authorization': f'Token token={api_token}'
    }
    
    try:
        response = requests.get(api_url, headers=headers, verify=False)
        response.raise_for_status()  # Raise an HTTPError if the HTTP request returned an unsuccessful status code
        overviews = response.json()
        
        for overview in overviews:
            delete_url = f"{api_url}/{overview['id']}"
            delete_response = requests.delete(delete_url, headers=headers, verify=False)
            delete_response.raise_for_status()  # Raise an HTTPError if the delete request returned an unsuccessful status code
            print(f"Overview with id {overview['id']} deleted successfully.")
            
    except HTTPError as http_err:
        print(f"HTTP error occurred while deleting overviews: {http_err}")
        if response.content:
            print(f"Response content: {response.content.decode()}")  # Print response content for more details
    except Exception as err:
        print(f"An error occurred while deleting overviews: {err}")

# Function to import a JSON object to the API endpoint
def import_json_to_api(json_data, api_url, api_token):
    headers = {
        'Content-Type': 'application/json',
        'Authorization': f'Token token={api_token}'
    }
    
    # If json_data is a list, iterate over each item and send it separately
    if isinstance(json_data, list):
        for item in json_data:
            try:
                response = requests.post(api_url, headers=headers, data=json.dumps(item), verify=False)
                response.raise_for_status()  # Raise an HTTPError if the HTTP request returned an unsuccessful status code
                print(f"JSON data imported successfully: {response.status_code}")
            except HTTPError as http_err:
                print(f"HTTP error occurred: {http_err}")  # HTTP error
                if response.content:
                    print(f"Response content: {response.content.decode()}")  # Print response content for more details
            except Exception as err:
                print(f"An error occurred: {err}")  # Other errors
    else:
        try:
            response = requests.post(api_url, headers=headers, data=json.dumps(json_data), verify=False)
            response.raise_for_status()  # Raise an HTTPError if the HTTP request returned an unsuccessful status code
            print(f"JSON data imported successfully: {response.status_code}")
        except HTTPError as http_err:
            print(f"HTTP error occurred: {http_err}")  # HTTP error
            if response.content:
                print(f"Response content: {response.content.decode()}")  # Print response content for more details
        except Exception as err:
            print(f"An error occurred: {err}")  # Other errors

# Load JSON data from file
def import_overview(json_filename, api_url, api_token):
    json_data = load_json_from_file(json_filename)

    if json_data:
        delete_all_overviews(api_url, api_token)  # Delete all existing overviews before importing
        import_json_to_api(json_data, api_url, api_token)

# Example usage
domain_url = 'https://example.com'  # Replace with your actual domain URL
api_endpoint = '/api/v1/overviews/'
api_url = f'{domain_url}{api_endpoint}'
api_token = 'your_api_token'  # Replace with your actual API token

# Load JSON data from file and import it
json_file_path = 'path_to_your_json_file.json'  # Replace with your actual JSON file path
import_overview(json_file_path, api_url, api_token)

This way, we first delete all existing overviews and then import all the overviews again

My suggestion is to always cleanly import all overviews


Viewing all articles
Browse latest Browse all 6760

Trending Articles