我正在为https://github.com/tariqdaouda/pyArango使用pyarango驱动程序( arangoDB ),但我无法理解字段验证是如何工作的。我已经设置了集合的字段,如github示例中所示:
import pyArango.Collection as COL
import pyArango.Validator as VAL
from pyArango.theExceptions import ValidationError
import types
class String_val(VAL.Validator) :
def validate(self, value) :
if type(value) is not types.StringType :
raise ValidationError("Field value must be a string")
return True
class Humans(COL.Collection) :
_validation = {
'on_save' : True,
'on_set' : True,
'allow_foreign_fields' : True # allow fields that are not part of the schema
}
_fields = {
'name' : Field(validators = [VAL.NotNull(), String_val()]),
'anything' : Field(),
'species' : Field(validators = [VAL.NotNull(), VAL.Length(5, 15), String_val()])
}
因此,当我试图将文档添加到“人工”集合中时,如果'name‘字段不是字符串,则会出现错误。但这似乎没那么容易。
我是这样将文档添加到集合中的:
myjson = json.loads(open('file.json').read())
collection_name = "Humans"
bindVars = {"doc": myjson, '@collection': collection_name}
aql = "For d in @doc INSERT d INTO @@collection LET newDoc = NEW RETURN newDoc"
queryResult = db.AQLQuery(aql, bindVars = bindVars, batchSize = 100)
因此,如果'name‘不是字符串,我实际上不会收到任何错误,并将其上传到集合中。
是否有人知道如何使用pyarango的内置验证来检查文档是否包含该集合的适当字段?
发布于 2016-07-21 23:19:15
我不认为您的验证器有什么问题,只是如果您使用AQL查询插入您的文档,pyArango无法在插入之前知道内容。
验证器只在以下情况下才能处理pyArango文档:
humans = db["Humans"]
doc = humans.createDocument()
doc["name"] = 101
这应该触发异常,因为您已经定义了:
'on_set': True
发布于 2016-03-16 04:45:21
ArangoDB作为文档存储本身不强制执行模式,驱动程序也不强制。如果需要模式验证,可以在驱动程序之上或ArangoDB内部使用Foxx服务(通过joi验证库)进行验证。
这样做的一个可能的解决方案是在应用程序中的驱动程序之上使用JSON模式及其python实现:
from jsonschema import validate
schema = {
"type" : "object",
"properties" : {
"name" : {"type" : "string"},
"species" : {"type" : "string"},
},
}
使用JSON的另一个实际示例是swagger.io,它还用于记录ArangoDB REST和ArangoDB Foxx服务。
发布于 2016-04-24 23:25:37
我还不知道我发布的代码到底出了什么问题,但现在看来可行了。但是,在读取json文件时,我必须使用将unicode转换为utf-8,否则它无法识别字符串。我知道ArangoDB本身并不强制执行方案,但我使用的是内置验证。对于那些对使用python的arangoDB内置验证感兴趣的人,请访问pyarango github。
https://stackoverflow.com/questions/35917310
复制