You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

93 lines
2.6 KiB
Python

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

"""
JSON 序列化配置
Flask 3.x 使用 JSONProvider 替代 JSONEncoder
支持通过配置文件控制序列化行为
"""
from datetime import datetime, date
from flask.json.provider import DefaultJSONProvider
class CustomJSONProvider(DefaultJSONProvider):
"""
自定义 JSON Provider (Flask 3.x)
功能:
- 处理 datetime 和 date 类型
- 支持配置文件控制序列化参数
"""
def __init__(self, app):
"""
初始化 JSON Provider
从 app.config 读取配置:
- JSON_ENSURE_ASCII: 是否转义非 ASCII 字符
- JSON_SORT_KEYS: 是否对字典 key 排序
- JSON_INDENT: 缩进空格数None 为不缩进)
- JSON_SEPARATORS: 分隔符元组
"""
super().__init__(app)
# 从配置读取设置
self._ensure_ascii = app.config.get('JSON_ENSURE_ASCII', False)
self._sort_keys = app.config.get('JSON_SORT_KEYS', False)
self._indent = app.config.get('JSON_INDENT', None)
self._separators = app.config.get('JSON_SEPARATORS', (',', ':'))
def default(self, obj):
"""
序列化自定义对象
Args:
obj: 要序列化的对象
Returns:
序列化后的 Python 基本类型
"""
# 处理 datetime 类型
if isinstance(obj, datetime):
return obj.strftime("%Y-%m-%d %H:%M:%S")
# 处理 date 类型
elif isinstance(obj, date):
return obj.strftime("%Y-%m-%d")
# 其他类型调用父类处理
return super().default(obj)
def dumps(self, obj, **kwargs):
"""
序列化为 JSON 字符串
合并配置文件和运行时参数
"""
# 使用配置文件的默认值
kwargs.setdefault('ensure_ascii', self._ensure_ascii)
kwargs.setdefault('sort_keys', self._sort_keys)
if self._indent is not None:
kwargs.setdefault('indent', self._indent)
kwargs.setdefault('separators', self._separators)
return super().dumps(obj, **kwargs)
def init_encoder(app):
"""
初始化 JSON 编码器
配置:
- 设置自定义 JSONProvider
- 从配置文件读取序列化参数
- 支持环境差异化配置
"""
# 设置自定义 Provider
app.json_provider_class = CustomJSONProvider
# 直接设置 app.json 的属性Flask 3.x 推荐方式)
app.json.ensure_ascii = app.config.get('JSON_ENSURE_ASCII', False)
app.json.sort_keys = app.config.get('JSON_SORT_KEYS', False)