morepath的json模式支持
more.jsonschema的Python项目详细描述
more.json schema:morepath的json模式支持
这个包为JSON Schema提供了更多路径集成, 用jsonschema:
实现json模式可以在http api中自动执行用户输入验证。
模式
json模式需要加载到python dict中 (您可以使用json.load()):
user_schema={'type':'object','properties':{'name':{'type':'string','minLength':3},'age':{'type':'integer','minimum':10}},'required':['name','age']}
如果要在python中定义json模式,可以使用jsl作为例子。
验证
more.jsonschema集成有助于 在将请求主体发布到视图时对其进行验证。 首先,我们必须为模式创建一个加载程序:
frommore.jsonschemaimportloaderuser_schema_load=loader(user_schema)
我们可以使用此加载程序处理post请求,例如:
@App.json(model=User,request_method='POST',load=user_schema_load)defuser_post(self,request,json):# json is now a validated and normalized dict of whatever got# POST onto this view that you can use to update# self
自定义验证器
默认情况下,more.jsonschema使用Draft4Validator。 但是您也可以使用Draft3Validator,创建自己的验证器 或扩展现有的验证器。把验证器交给 loader:
fromjsonschemaimportDraft3Validatorfrommore.jsonschemaimportloaderuser_schema_load=loader(user_schema,validator=Draft3Validator)
有关创建或扩展验证程序类的详细信息 你可以在jsonschema documentation中找到。
错误处理
如果验证由于验证错误而失败(必需字段是 缺少,或者字段的数据类型不正确(例如) 显示某种错误消息。由创建的load函数 more.jsonschema引发more.jsonschema.ValidationError异常 以防出错。
此异常对象有一个带有验证错误的errors属性。 必须为其定义异常视图,否则验证错误为 作为“500内部服务器错误”返回给API用户。
此包提供默认的异常视图实现。如果你分类 您的应用程序来自more.jsonschema.JsonSchemaApp,然后您将获得一个默认值 ValidationError的错误视图,状态代码为422,但有错误 消息:
frommore.jsonschemaimportJsonSchemaAppclassApp(JsonSchemaApp):pass
现在你的应用程序有了合理的内置错误处理。
更改
0.1(2017-03-17)
- 首次公开发行。