utils.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. """
  2. 工具函数模块
  3. 提供常用的辅助函数
  4. """
  5. import json
  6. import os
  7. from datetime import datetime
  8. from typing import Any, Dict, List
  9. def load_config(config_path: str) -> Dict[str, Any]:
  10. """
  11. 加载配置文件
  12. Args:
  13. config_path: 配置文件路径
  14. Returns:
  15. 配置字典
  16. """
  17. # TODO: 支持多种配置文件格式
  18. with open(config_path, 'r') as f:
  19. return json.load(f)
  20. def save_config(config: Dict[str, Any], config_path: str) -> None:
  21. """
  22. 保存配置到文件
  23. Args:
  24. config: 配置字典
  25. config_path: 配置文件路径
  26. """
  27. with open(config_path, 'w') as f:
  28. json.dump(config, f, indent=2)
  29. def get_timestamp() -> str:
  30. """
  31. 获取当前时间戳
  32. Returns:
  33. ISO格式的时间戳字符串
  34. """
  35. return datetime.now().isoformat()
  36. def ensure_dir(directory: str) -> None:
  37. """
  38. 确保目录存在,不存在则创建
  39. Args:
  40. directory: 目录路径
  41. """
  42. if not os.path.exists(directory):
  43. os.makedirs(directory)
  44. def format_size(size_bytes: int) -> str:
  45. """
  46. 格式化文件大小
  47. Args:
  48. size_bytes: 字节数
  49. Returns:
  50. 格式化后的大小字符串
  51. """
  52. # TODO: 优化格式化逻辑
  53. for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
  54. if size_bytes < 1024.0:
  55. return f"{size_bytes:.2f} {unit}"
  56. size_bytes /= 1024.0
  57. return f"{size_bytes:.2f} PB"
  58. def validate_email(email: str) -> bool:
  59. """
  60. 验证邮箱地址格式
  61. Args:
  62. email: 邮箱地址
  63. Returns:
  64. 是否有效
  65. """
  66. import re
  67. pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
  68. return re.match(pattern, email) is not None