1. 标准库是什么? #

模块 项目用途
datetime 时间创建、格式化、加减
json 配置、API 序列化
os / sys getenv、命令行参数、sys.exit
logging 生产日志(替代 print)
collections Counter 计数、defaultdict 分组
re 手机号、邮箱等格式校验
functools lru_cache、wraps
typing 类型注解(IDE 提示)
secrets / uuid token、唯一 ID
random 仅测试数据(不能用于密码/token)

2. datetime #

# 导入 datetime 相关类
from datetime import datetime, timedelta, timezone

# 获取当前本地时间
now = datetime.now()
# 字符串解析为 datetime 对象
dt = datetime.strptime("2025-05-21", "%Y-%m-%d")
# datetime 格式化为字符串
now.strftime("%Y-%m-%d %H:%M:%S")
# 当前时间加 7 天
deadline = now + timedelta(days=7)
# 获取 UTC 时间,存库常用
utc = datetime.now(timezone.utc)

3. json #

函数 方向 典型场景
dumps / loads 对象 ↔ 字符串 API 响应体、Redis 存字符串
dump / load 对象 ↔ 文件 读写 config.json
# 导入 json 模块
import json

# 准备一个Python对象
obj = {"name": "小明", "age": 18}

# Python 对象序列化为 JSON 字符串
json_str = json.dumps(obj, ensure_ascii=False)
print(json_str)

# 一个示例 JSON 字符串
s = '{"name": "小明", "age": 18}'

# JSON 字符串反序列化为 Python 对象
py_obj = json.loads(s)
print(py_obj)

# 从 JSON 文件读取
with open("config.json", encoding="utf-8") as f:
    config = json.load(f)
    print(config)

4. os、sys、logging #

# 导入 os、sys、logging 模块
import os, sys, logging

# 读取环境变量,不存在时用空字符串
os.getenv("DATABASE_URL", "")
# len(sys.argv)  脚本参数;sys.exit(1) 异常退出

# 配置日志级别
logging.basicConfig(level=logging.INFO)
# 获取当前模块的 logger
logger = logging.getLogger(__name__)
logger.info("ok")
# 记录错误并附带异常堆栈
logger.error("fail", exc_info=True)

5. collections #

# 导入 Counter 和 defaultdict
from collections import Counter, defaultdict

# 统计元素出现次数
Counter(["a", "b", "a"])
# 创建默认值为 list 的字典,用于分组
groups = defaultdict(list)
users = [{"name": "Alice", "city": "Beijing"}, {"name": "Bob", "city": "Shanghai"}, {"name": "Charlie", "city": "Beijing"}]
# 按城市分组用户
for u in users:
    groups[u["city"]].append(u)
print(groups)

6. re #

# 导入 re 模块
import re

# 示例数据
phone = "13812345678"
email = "test@example.com"
text = "这是    一个   有   多个空白   的文本。"

# 从开头匹配 11 位数字(手机号)
match_result = re.match(r"^\d{11}$", phone)
if match_result:
    print(f"手机号匹配成功: {match_result.group()}")
else:
    print("手机号匹配失败")

# 搜索邮箱中的 @ 及后续字符
search_result = re.search(r"@\w+", email)
if search_result:
    print(f"邮箱@及后续: {search_result.group()}")
else:
    print("未找到邮箱@及后续字符串")

# 将多个空白字符替换为单个空格
replaced_text = re.sub(r"\s+", " ", text)
print(f"替换空白后的文本: {replaced_text}")

7. functools #

# 导入 functools 模块,用于函数工具,比如缓存和装饰器编写
import functools

# 缓存函数结果,最多缓存 128 个,避免重复加载配置,提升性能
@functools.lru_cache(maxsize=128)
def load_config(key: str):
    """
    根据给定的 key 加载配置,如果已缓存则直接返回缓存内容。
    参数:
        key (str): 配置项的键名。
    返回:
        配置的值(这里只是示例,实际应从配置文件或数据库加载)。
    """
    # 假设从某个配置字典中读取配置
    config_dict = {
        'database_url': 'mysql://user:pass@localhost/db',
        'timeout': 30,
        'retry': 3,
        # 可扩展更多配置项
    }
    # 从配置字典取值,不存在返回 None
    return config_dict.get(key, None)

# 自定义装饰器示例
def my_decorator(func):
    """
    一个自定义装饰器示例,装饰任意函数并输出调用信息。
    """
    # 写装饰器时保留原函数的 __name__ 和 __doc__
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        """
        包装函数,调用原始函数并可在调用前后添加自定义逻辑。
        """
        print(f'即将调用函数 {func.__name__},参数为: args={args}, kwargs={kwargs}')
        # 调用原函数并获取返回值
        result = func(*args, **kwargs)
        print(f'函数 {func.__name__} 调用完毕,结果为: {result}')
        return result
    # 返回包装后的函数
    return wrapper

8. typing #

# 类型注解:参数为 int,返回 dict 或 None(Python 3.10+)
def get_user(id: int) -> dict | None: ...
# 参数为 dict 列表,返回 str 列表
def names(users: list[dict]) -> list[str]: ...

9. 安全与 ID #

# 导入 secrets 和 uuid 模块
import secrets, uuid
# 生成安全的 URL 安全 token(会话、重置链接)
print(secrets.token_urlsafe(32))
# 生成 UUID 字符串(业务主键、订单号)
print(str(uuid.uuid4()))

10. 项目开发要点 #

11. 总结 #