gpt4 book ai didi

python - 如何使用 Cerberus 返回自定义规则名称/错误代码?

转载 作者:行者123 更新时间:2023-11-30 21:55:20 27 4
gpt4 key购买 nike

正在验证 .csv 文件,我想以用户习惯的格式给出验证结果。要利用Cerberus ,我让用户在 .yaml 文件中定义验证规则。

schema.yaml

Rules:
Rule1:
maxlength: 10

Rule2:
allowed: ["MO", "TU", "WE", "TH", "FR", "SA", "SU"]

Rule3:
required: True

然后,我将这些规则映射到 CSV 文件中适用的列。

csv_fields.yaml

Fields:
1:
rules:
- Rule1
- Rule2

2:
rules:
- Rule2
- Rule3

3:
rules:
- Rule1
- Rule3

sample_file.csv

下面是一个包含三列的示例文件:first_nameday_of_weekis_owned

Peter, XX, True

要使用 Cerberus 进行验证,请交叉引用 csv_fields.yaml 文档的 rules 键中定义的 rules schema.yaml 文件中的规则。这很容易做到,因为 .yaml 文件在 Python 中以键值格式读取为字典。

我的问题

在上面的示例数据中,cerberus 抛出错误 'day_of_week': ['unallowed value XX'] 但用户不会知道什么规则触发了此错误。

我期待告诉用户的是,错误unallowed value XX是由Rule2触发的,因为用户知道Rule2而不是Cerberus 技术具体定义。

有没有办法实现这一点,即使这意味着以不同的方式定义 schema.yaml

我查看了 Cerberus Errors Section但似乎找不到办法做到这一点。

更新:

因此,我尝试将 meta 字段添加到 schema.yaml 中的规则定义

Rules:
Rule1:
maxlength: 10
meta: {'rule_name': "Rule1"}

但是当我测试时,我似乎无法从引发的错误中访问此元键,因为我在 document_error_tree 甚至 schema_error_tree 中找不到它。

最佳答案

我和你在同一个空间,我会告诉你我做了什么。

创建了一个自定义 error_handler 并在错误消息前面添加了人类可读的键。

from cerberus.errors import BasicErrorHandler

class CustomErrorHandler(BasicErrorHandler):
def __init__(self, schema):
self.custom_defined_schema = schema

def _format_message(self, field, error):
return self.custom_defined_schema[field].get('meta', {}).get('rule_name', field) + ': ' + super(CustomErrorHandler, self)._format_message(field, error)

val = Validator(schema, error_handler=CustomErrorHandler(schema))

这就是我所做的,希望对你有用。

关于python - 如何使用 Cerberus 返回自定义规则名称/错误代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56936542/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com