up stuff
This commit is contained in:
parent
656c3fd414
commit
1c17b57d8a
37 changed files with 2818 additions and 469 deletions
0
oedb/utils/__init__.py
Normal file
0
oedb/utils/__init__.py
Normal file
38
oedb/utils/db.py
Normal file
38
oedb/utils/db.py
Normal file
|
@ -0,0 +1,38 @@
|
|||
"""
|
||||
Database utility functions for the OpenEventDatabase.
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import psycopg2
|
||||
import psycopg2.extras
|
||||
from oedb.utils.logging import logger
|
||||
|
||||
def db_connect():
|
||||
"""
|
||||
Connect to the PostgreSQL database using environment variables.
|
||||
|
||||
Returns:
|
||||
psycopg2.connection: A connection to the database.
|
||||
"""
|
||||
return psycopg2.connect(
|
||||
dbname=os.getenv("DB_NAME", "oedb"),
|
||||
host=os.getenv("DB_HOST", ""),
|
||||
password=os.getenv("POSTGRES_PASSWORD", None),
|
||||
user=os.getenv("DB_USER", ""))
|
||||
|
||||
def check_db_connection():
|
||||
"""
|
||||
Check if the database is accessible.
|
||||
|
||||
Returns:
|
||||
bool: True if the database is accessible, False otherwise.
|
||||
"""
|
||||
try:
|
||||
conn = db_connect()
|
||||
conn.close()
|
||||
logger.success("Successfully connected to PostgreSQL database")
|
||||
return True
|
||||
except psycopg2.OperationalError as e:
|
||||
logger.error(f"Failed to connect to PostgreSQL database: {e}")
|
||||
return False
|
64
oedb/utils/logging.py
Normal file
64
oedb/utils/logging.py
Normal file
|
@ -0,0 +1,64 @@
|
|||
"""
|
||||
Logging utilities for the OpenEventDatabase.
|
||||
Provides colored logging functionality based on message type.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import sys
|
||||
|
||||
# ANSI color codes for terminal output
|
||||
COLORS = {
|
||||
'RESET': '\033[0m',
|
||||
'RED': '\033[31m', # Error
|
||||
'GREEN': '\033[32m', # Success
|
||||
'YELLOW': '\033[33m', # Warning
|
||||
'BLUE': '\033[34m', # Info
|
||||
'MAGENTA': '\033[35m', # Debug
|
||||
}
|
||||
|
||||
class ColoredLogger:
|
||||
"""
|
||||
A logger that outputs colored messages based on the log level.
|
||||
"""
|
||||
def __init__(self, name="OEDB"):
|
||||
self.logger = logging.getLogger(name)
|
||||
self.logger.setLevel(logging.INFO)
|
||||
|
||||
# Create console handler
|
||||
console_handler = logging.StreamHandler(sys.stdout)
|
||||
console_handler.setLevel(logging.INFO)
|
||||
|
||||
# Create formatter
|
||||
formatter = logging.Formatter('%(asctime)s [%(name)s] [%(levelname)s] %(message)s')
|
||||
console_handler.setFormatter(formatter)
|
||||
|
||||
# Add handler to logger
|
||||
self.logger.addHandler(console_handler)
|
||||
|
||||
def info(self, message):
|
||||
"""Log an info message (blue)"""
|
||||
print(f"{COLORS['BLUE']}INFO: {message}{COLORS['RESET']}")
|
||||
self.logger.info(message)
|
||||
|
||||
def success(self, message):
|
||||
"""Log a success message (green)"""
|
||||
print(f"{COLORS['GREEN']}SUCCESS: {message}{COLORS['RESET']}")
|
||||
self.logger.info(f"SUCCESS: {message}")
|
||||
|
||||
def warning(self, message):
|
||||
"""Log a warning message (yellow)"""
|
||||
print(f"{COLORS['YELLOW']}WARNING: {message}{COLORS['RESET']}")
|
||||
self.logger.warning(message)
|
||||
|
||||
def error(self, message):
|
||||
"""Log an error message (red)"""
|
||||
print(f"{COLORS['RED']}ERROR: {message}{COLORS['RESET']}")
|
||||
self.logger.error(message)
|
||||
|
||||
def debug(self, message):
|
||||
"""Log a debug message (magenta)"""
|
||||
print(f"{COLORS['MAGENTA']}DEBUG: {message}{COLORS['RESET']}")
|
||||
self.logger.debug(message)
|
||||
|
||||
# Create a global logger instance
|
||||
logger = ColoredLogger()
|
32
oedb/utils/serialization.py
Normal file
32
oedb/utils/serialization.py
Normal file
|
@ -0,0 +1,32 @@
|
|||
"""
|
||||
Serialization utilities for the OpenEventDatabase.
|
||||
Provides JSON serialization functionality for event data.
|
||||
"""
|
||||
|
||||
import json
|
||||
from datetime import datetime
|
||||
|
||||
class EventEncoder(json.JSONEncoder):
|
||||
"""
|
||||
Custom JSON encoder for event data.
|
||||
Handles datetime objects by converting them to ISO format strings.
|
||||
"""
|
||||
def default(self, o):
|
||||
if isinstance(o, datetime):
|
||||
return o.isoformat()
|
||||
try:
|
||||
return super().default(o)
|
||||
except TypeError:
|
||||
return str(o)
|
||||
|
||||
def dumps(data):
|
||||
"""
|
||||
Serialize data to JSON using the EventEncoder.
|
||||
|
||||
Args:
|
||||
data: The data to serialize.
|
||||
|
||||
Returns:
|
||||
str: The JSON string representation of the data.
|
||||
"""
|
||||
return json.dumps(data, cls=EventEncoder, sort_keys=True, ensure_ascii=False)
|
Loading…
Add table
Add a link
Reference in a new issue