Common Python Utility Interfaces: Validation, HTTP, File I/O, JSON, DateTime, Encryption, SQLite, Image Processing, Error Handling, and Config Loading
This article presents a collection of reusable Python utility interfaces—including data validation, HTTP request handling, file read/write, JSON parsing, date‑time formatting, symmetric encryption, SQLite persistence, image resizing, exception handling, and configuration loading—each illustrated with concise code examples to improve code readability and testability.
1. Data Validation Interface
class DataValidator:
@staticmethod
def validate_email(email):
# 使用正则表达式验证邮箱格式
import re
pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
return bool(re.match(pattern, email))2. HTTP Request Wrapper
import requests
class HTTPClient:
@staticmethod
def get(url, params=None):
response = requests.get(url, params=params)
return response.json()3. File Read/Write Interface
class FileHandler:
@staticmethod
def write_to_file(filename, content):
with open(filename, 'w') as file:
file.write(content)
@staticmethod
def read_from_file(filename):
with open(filename, 'r') as file:
return file.read()4. JSON Parser Interface
import json
class JSONParser:
@staticmethod
def parse(json_string):
return json.loads(json_string)
@staticmethod
def stringify(data):
return json.dumps(data)5. DateTime Utility Interface
from datetime import datetime
class DateTimeUtils:
@staticmethod
def format_datetime(dt=datetime.now()):
return dt.strftime('%Y-%m-%d %H:%M:%S')6. Data Encryption/Decryption Interface
from cryptography.fernet import Fernet
class Crypto:
def __init__(self, key):
self.key = key
self.cipher_suite = Fernet(key)
def encrypt(self, data):
return self.cipher_suite.encrypt(data.encode())
def decrypt(self, token):
return self.cipher_suite.decrypt(token).decode()7. SQLite Persistence Interface
import sqlite3
class Database:
def __init__(self, db_name='data.db'):
self.conn = sqlite3.connect(db_name)
self.cursor = self.conn.cursor()
def execute(self, query, data=None):
if data:
self.cursor.execute(query, data)
else:
self.cursor.execute(query)
self.conn.commit()
def fetch_all(self, query):
self.cursor.execute(query)
return self.cursor.fetchall()8. Image Processing Interface
from PIL import Image
class ImageProcessor:
@staticmethod
def resize_image(image_path, size=(100, 100)):
img = Image.open(image_path)
img_resized = img.resize(size)
img_resized.save('resized_' + image_path)9. Exception Handling Interface
class ErrorHandler:
@staticmethod
def handle_exception(func):
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as e:
print(f"Error occurred: {e}")
return wrapper10. Configuration Loading Interface
import yaml
class ConfigLoader:
@staticmethod
def load_config(config_file='config.yaml'):
with open(config_file, 'r') as file:
return yaml.safe_load(file)These interfaces simplify code structure, enhance readability, and make testing easier; integrating them into a project allows straightforward extension or modification without affecting other components.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.