Become a sponsor

数据字典
数据字典用于管理系统中的枚举值和配置项,如状态、类型、性别等。通过字典编码统一管理,前端可通过 useDictStore 获取字典选项,避免硬编码。后端读取工具位于 src/utils/dict_util.py,内置进程内 TTL 缓存。
src/modules/dictionary/
├── dict/ # 字典类型(分组)
│ ├── models.py
│ ├── schemas.py
│ ├── repository.py
│ └── service.py
└── dict_item/ # 字典项(具体值)
├── models.py
├── schemas.py
├── repository.py
└── service.py# src/modules/dictionary/dict/models.py
# ============================================================
# 字典模型
# ============================================================
class Dict(base_model, base_db):
"""字典模型类"""
# ============================================================
# 表名配置
# ============================================================
__tablename__ = DB_PREFIX + "dict"
__table_comment__ = "数据字典表"
# ============================================================
# 字段定义
# ============================================================
# 字典名称
name = Column(String(150), nullable=False, index=True, comment="字典名称")
# 字典编码
code = Column(String(150), nullable=False, index=True, comment="字典编码")
# 字典排序
sort = Column(Integer, default=0, server_default=text('0'), comment="字典排序")
# 字典备注
note = Column(String(255), nullable=True, comment="字典备注")
# ============================================================
# 内置方法
# ============================================================
def __str__(self):
"""返回字典ID作为字符串表示"""
return "字典{}".format(self.id)# src/modules/dictionary/dict_item/models.py
# ============================================================
# 字典项模型
# ============================================================
class DictItem(base_model, base_db):
"""字典项模型类"""
# ============================================================
# 表名配置
# ============================================================
__tablename__ = DB_PREFIX + "dict_item"
__table_comment__ = "字典项表"
# ============================================================
# 字段定义
# ============================================================
# 字典项名称
name = Column(String(150), nullable=False, index=True, comment="字典项名称")
# 字典项值
value = Column(String(150), nullable=False, comment="字典项值")
# 字典ID
dict_id = Column(Integer, default=0, server_default=text('0'), index=True, comment="字典ID")
# 字典项排序
sort = Column(Integer, default=0, server_default=text('0'), comment="字典项顺序")
# 字典项备注
note = Column(String(255), nullable=True, comment="字典项备注")
# ============================================================
# 内置方法
# ============================================================
def __str__(self):
"""返回字典项ID作为字符串表示"""
return "字典项{}".format(self.id)# 通过字典编码获取字典项列表
from modules.dictionary.dict_item import service as dict_item_service
# 获取状态字典
status_list = await dict_item_service.get_by_dict_code("sys_status")
# 返回: [{"label": "正常", "value": "1"}, {"label": "停用", "value": "2"}]项目提供 dict_util 工具(src/utils/dict_util.py),内置进程内 TTL 缓存。由于字典数据几乎不变,且读写均落在同步 service 路径(无法使用请求级异步 Redis),因此采用进程内缓存而非 Redis 缓存:
from utils.dict_util import get_dict_items, get_dict_map, get_dict_label
# 获取字典项列表(自动缓存,TTL 60秒兜底)
items = get_dict_items("sys_status")
# 返回: [{"label": "正常", "value": "1", "sort": 0}, {"label": "停用", "value": "2", "sort": 1}]
# 获取 {value: label} 映射
status_map = get_dict_map("sys_status")
# 返回: {"1": "正常", "2": "停用"}
# 单值翻译(value 自动转字符串匹配)
label = get_dict_label("sys_status", 1, default="未知")
# 返回: "正常"缓存实现细节:
# 进程内字典缓存:{code: (过期时间戳, 字典项列表)}
_dict_cache: dict = {}
_CACHE_TTL = 60 # 秒
def get_dict_items(code):
"""按字典编码读取字典项列表,字典不存在返回空列表"""
now = time.time()
hit = _dict_cache.get(code)
if hit and hit[0] > now:
return hit[1]
items = _load_dict_items(code)
_dict_cache[code] = (now + _CACHE_TTL, items)
return items
def invalidate_dict(code):
"""清除指定字典编码的缓存(字典/字典项增删改时由 service 主动调用)"""
if code:
_dict_cache.pop(code, None)
def invalidate_dicts_by_ids(dict_ids):
"""按字典ID批量清除缓存:字典项变更后据 dict_id 反查 code 再失效"""value 类型
字典项的 value 字段为字符串类型,get_dict_label() 内部会自动将查询值转为字符串匹配。前端使用时注意类型转换。
前端通过 useDictStore 获取字典数据:
import { useDictStore } from '@/store/dict'
const dictStore = useDictStore()
// 获取字典选项
const statusOptions = dictStore.getDict('sys_status')
// [{label: "正常", value: "1"}, {label: "停用", value: "2"}]
// 在 el-select 中使用
<el-select v-model="form.status">
<el-option
v-for="item in statusOptions"
:key="item.value"
:label="item.label"
:value="item.value"
/>
</el-select>| 字典编码 | 说明 | 字典项 |
|---|---|---|
sys_status | 系统状态 | 正常(1)、停用(2) |
sys_gender | 性别 | 男(1)、女(2) |
operation_type | 操作类型 | 新增(1)、修改(2)、删除(3) 等 |
menu_type | 菜单类型 | 菜单(0)、节点(1) |
数据字典模块具备以下特点:
1. 两级结构:字典类型(分组)+ 字典项(具体值),清晰管理
2. 进程内缓存:dict_util 内置 TTL 缓存(60秒兜底),变更时主动失效
3. 前端集成:useDictStore 统一管理,el-select 直接绑定
4. 值为字符串:字典项 value 统一为字符串,get_dict_label 自动转字符串匹配
5. 避免硬编码:枚举值统一走字典,修改无需改代码
6. 三种取值:get_dict_items(列表)、get_dict_map(映射)、get_dict_label(单值翻译)