91 lines
2.9 KiB
Python
91 lines
2.9 KiB
Python
#!/usr/bin/env python
|
|
# -*- coding: utf-8 -*-
|
|
# @Time : 2025/3/15 21:19
|
|
# @Author : AngesZhu
|
|
# @File : fixed_value_rules.py
|
|
# @Desc : 校验字段是否在固定列表中
|
|
from typing import Any, List, Optional
|
|
import random
|
|
|
|
|
|
# 自定义异常类
|
|
class FixedValueError(Exception):
|
|
"""固定值相关异常"""
|
|
|
|
def __init__(self, message: str, field: Optional[str] = None, details: Optional[Dict[str, Any]] = None):
|
|
self.message = message
|
|
self.field = field
|
|
self.details = details or {}
|
|
super().__init__(f"{message} (Field: {field}, Details: {details})")
|
|
|
|
|
|
class EmptyListError(FixedValueError):
|
|
"""固定值列表为空异常"""
|
|
pass
|
|
|
|
|
|
class ValueNotInListError(FixedValueError):
|
|
"""字段值不在固定列表中异常"""
|
|
pass
|
|
|
|
|
|
# 1. 在固定值内随机返回一个内容
|
|
def generate_from_fixed_values(fixed_values: List[Any], field: Optional[str] = None) -> Any:
|
|
"""
|
|
在固定值内随机返回一个内容
|
|
:param fixed_values: 固定值列表
|
|
:param field: 字段名称(用于错误信息)
|
|
:return: 随机选择的值
|
|
:raises EmptyListError: 如果固定值列表为空
|
|
"""
|
|
try:
|
|
if not fixed_values:
|
|
raise EmptyListError("固定值列表不能为空", field, {"fixed_values": fixed_values})
|
|
return random.choice(fixed_values)
|
|
except Exception as e:
|
|
raise FixedValueError(f"生成随机值失败: {str(e)}", field, {"fixed_values": fixed_values}) from e
|
|
|
|
|
|
# 2. 校验字段是否在固定列表中
|
|
def validate_in_fixed_values(value: Any, fixed_values: List[Any], field: Optional[str] = None) -> bool:
|
|
"""
|
|
校验字段是否在固定列表中
|
|
:param value: 字段值
|
|
:param fixed_values: 固定值列表
|
|
:param field: 字段名称(用于错误信息)
|
|
:return: 是否通过校验
|
|
:raises ValueNotInListError: 如果字段值不在固定列表中
|
|
"""
|
|
try:
|
|
if value not in fixed_values:
|
|
raise ValueNotInListError(
|
|
f"值 '{value}' 不在固定列表中",
|
|
field,
|
|
{"value": value, "fixed_values": fixed_values}
|
|
)
|
|
return True
|
|
except Exception as e:
|
|
raise FixedValueError(f"校验失败: {str(e)}", field, {"value": value, "fixed_values": fixed_values}) from e
|
|
|
|
|
|
# 使用示例
|
|
if __name__ == "__main__":
|
|
# 示例固定值列表
|
|
roles = ["admin", "user", "guest"]
|
|
|
|
# 1. 生成随机值
|
|
try:
|
|
random_role = generate_from_fixed_values(roles, "role")
|
|
print(f"生成的随机角色: {random_role}")
|
|
except FixedValueError as e:
|
|
print(f"生成失败: {str(e)}")
|
|
|
|
# 2. 校验字段是否在固定列表中
|
|
test_values = ["admin", "manager", "user"]
|
|
for value in test_values:
|
|
try:
|
|
validate_in_fixed_values(value, roles, "role")
|
|
print(f"值 '{value}' 在固定列表中")
|
|
except FixedValueError as e:
|
|
print(f"校验失败: {str(e)}")
|