在jsonschema中进行Python编程格式检查。

huangapple go评论86阅读模式
英文:

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)

huangapple
  • 本文由 发表于 2023年7月3日 15:38:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/76602725.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定