README_UTILS.md 2.3 KB

工具模块使用说明

数据处理工具

to_json(data)

  • 功能:将 Python 对象转换为 JSON 字符串
  • 参数:
    • data: 需要转换的 Python 对象
  • 返回:JSON 格式的字符串

    from app.utils import to_json
    
    data = {'key': 'value'}
    json_str = to_json(data)
    

数据验证工具

is_email(email)

  • 功能:验证邮箱格式
  • 参数:
    • email: 需要验证的邮箱地址
  • 返回:布尔值,True 表示格式正确

    from app.utils import is_email
    
    is_valid = is_email('test@example.com')
    

is_valid_ip(ip)

  • 功能:验证 IP 地址格式
  • 参数:
    • ip: 需要验证的 IP 地址
  • 返回:布尔值,True 表示格式正确

    from app.utils import is_valid_ip
    
    is_valid = is_valid_ip('192.168.1.1')
    

文件操作工具

get_file_size(file_path)

  • 功能:获取文件大小
  • 参数:
    • file_path: 文件路径
  • 返回:文件大小(字节)

    from app.utils import get_file_size
    
    size = get_file_size('test.txt')
    

日期时间工具

get_current_time()

  • 功能:获取当前时间
  • 返回:当前时间的 datetime 对象

    from app.utils import get_current_time
    
    now = get_current_time()
    

format_date(date, fmt='%Y-%m-%d %H:%M:%S')

  • 功能:格式化日期时间
  • 参数:
    • date: 需要格式化的日期时间
    • fmt: 格式化字符串(可选,默认'%Y-%m-%d %H:%M:%S')
  • 返回:格式化后的字符串

    from app.utils import format_date
    
    now = get_current_time()
    formatted = format_date(now)
    

parse_date(date_str, fmt='%Y-%m-%d %H:%M:%S')

  • 功能:解析字符串为日期时间
  • 参数:
    • date_str: 日期时间字符串
    • fmt: 格式化字符串(可选,默认'%Y-%m-%d %H:%M:%S')
  • 返回:解析后的 datetime 对象

    from app.utils import parse_date
    
    dt = parse_date('2023-01-01 12:00:00')
    

get_timestamp()

  • 功能:获取当前时间戳
  • 返回:当前时间的时间戳(秒)

    from app.utils import get_timestamp
    
    ts = get_timestamp()
    

使用建议

  1. 建议通过from app.utils import ...的方式按需导入工具方法
  2. 所有工具方法都经过单元测试,可以直接使用
  3. 如果遇到问题,请检查相关参数是否正确
  4. 日期时间工具使用时请注意时区问题