function load_database
Loads a JSON database file from a replica directory and returns its contents as a dictionary, with error handling for missing files or parsing failures.
/tf/active/vicechatdev/e-ink-llm/cloudtest/analyze_replica.py
19 - 32
simple
Purpose
This function is designed to safely load a replica database stored as a JSON file. It checks for file existence, handles encoding properly (UTF-8), and provides user-friendly error messages. Returns None if the file doesn't exist or if loading fails, making it suitable for applications that need to work with replica/backup database files.
Source Code
def load_database(replica_dir: Path) -> Dict[str, Any]:
"""Load the replica database"""
database_file = replica_dir / "replica_database.json"
if not database_file.exists():
print(f"❌ Database file not found: {database_file}")
return None
try:
with open(database_file, 'r', encoding='utf-8') as f:
return json.load(f)
except Exception as e:
print(f"❌ Failed to load database: {e}")
return None
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
replica_dir |
Path | - | positional_or_keyword |
Parameter Details
replica_dir: A Path object representing the directory containing the replica database. This directory should contain a file named 'replica_database.json'. The Path object should be from pathlib.Path and point to a valid directory location.
Return Value
Type: Dict[str, Any]
Returns a dictionary (Dict[str, Any]) containing the parsed JSON data from the replica database file. Returns None if the database file doesn't exist or if any exception occurs during loading (e.g., invalid JSON, permission errors, encoding issues). The dictionary structure depends on the content of the JSON file.
Dependencies
jsonpathlib
Required Imports
import json
from pathlib import Path
from typing import Dict, Any
Usage Example
from pathlib import Path
import json
from typing import Dict, Any
def load_database(replica_dir: Path) -> Dict[str, Any]:
"""Load the replica database"""
database_file = replica_dir / "replica_database.json"
if not database_file.exists():
print(f"❌ Database file not found: {database_file}")
return None
try:
with open(database_file, 'r', encoding='utf-8') as f:
return json.load(f)
except Exception as e:
print(f"❌ Failed to load database: {e}")
return None
# Usage
replica_path = Path('/path/to/replica')
db_data = load_database(replica_path)
if db_data is not None:
print(f"Database loaded successfully with {len(db_data)} entries")
# Process database data
else:
print("Failed to load database")
Best Practices
- Always check if the returned value is None before using it to avoid AttributeError
- Ensure the replica_dir parameter is a valid Path object, not a string
- The function expects a file named exactly 'replica_database.json' in the provided directory
- Error messages are printed to stdout; consider logging for production use
- The function uses UTF-8 encoding by default; ensure your JSON files are UTF-8 encoded
- Broad exception catching may hide specific errors; consider more granular error handling for production
- The function returns None on both file-not-found and parsing errors; check error messages to distinguish between failure types
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function load_database_schema 64.1% similar
-
function load_dataset 56.9% similar
-
function load_document_from_file 53.3% similar
-
function load_data 53.1% similar
-
function load_remarkable_config 52.9% similar