英文:
Programmatic (Python) format check in jsonschema
问题
我有一个模式,其中一个属性应该符合只能以编程方式检查的模式:
type: object
properties:
unit:
description: 此列的单位。必须符合FITS规范。
type: string
其中,“FITS符合性”可以通过一个小的Python代码片段来确保(在失败时引发异常):
import astropy.units as u
u.Unit(col["unit"], format=u.format.Fits)
似乎可以使用属性的自定义“format”属性来完成此操作:
type: object
properties:
unit:
description: 此列的单位。必须符合FITS规范。
type: string
format: fitsunit
然后,使用装饰器 jsonschema.FormatChecker.checks 来实现格式检查器。但是,我找不到如何编写这个检查器的方法。
英文:
I have a schema where a property should comply to a pattern that only can be checked programmatically:
type: object
properties:
unit:
description: Unit of this column. Must be FITS conform.
type: string
where "FITS conformity" can be ensured by a small Python snippet (which raises an exception on fail):
import astropy.units as u
u.Unit(col["unit"], format=u.format.Fits)
It seems that this could be done with a custom "format" attribute of the property:
type: object
properties:
unit:
description: Unit of this column. Must be FITS conform.
type: string
format: fitsunit
and then implement a format checker with the decorator jsonschema.FormatChecker.checks. However, I could not find out how to write this.
答案1
得分: 0
我终于自己找到了这个。装饰器用于一个简单的检查函数,该函数接受一个单一的参数:
from jsonschema import validate, Draft202012Validator
@Draft202012Validator.FORMAT_CHECKER.checks("fitsunit", ValueError)
def check_fitsunit(s):
import astropy.units as u
u.Unit(s, format=u.format.Fits)
return True
validate(my_file, my_schema, format_checker=Draft202012Validator.FORMAT_CHECKER)
英文:
I finally found this out myself. The decorator is used for a simple checker function, that takes one single argument:
from jsonschema import validate, Draft202012Validator
@Draft202012Validator.FORMAT_CHECKER.checks("fitsunit", ValueError)
def check_fitsunit(s):
import astropy.units as u
u.Unit(s, format=u.format.Fits)
return True
validate(my_file, my_schema, format_checker=Draft202012Validator.FORMAT_CHECKER)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论