开发者

Python model object validation

I'm writing an interface to be used by two applications. This interface should use some DoSomethingRequest and DoSomethingResponse classes to do the communication.

Is there any library that does some model validation, for example like Django's Model?

I basically want to be able to say something like:

Object A must have a "text" property of type str(), a "number" property of type int(), an "items" property of type list(). In a DRY way.

I'm looking for something like the following, or better:

class MyEmbeddedModelClass(EmbeddedModel):
 开发者_运维百科   text = TextField(required = True)

class MyModel(Model):
    text = TextField(required = True)
    number = IntField(default = 0)
    items = ListField(EmbeddedModel)


a = MyModel()
a.text = "aaaa"
a.number = 1
a.items = [
    MyEmbeddedModelClass("bbbb"),
    MyEmbeddedModelClass("cccc"),
    MyEmbeddedModelClass("dddd")
]
a.validate()

I know I can write my own, but I'd rather use a library if available, I'm a bit new to this.


If you want to enforce interfaces, or use design-by-contract, then you probably want the zope.interface library. Despite the name, which reflects its origins in Zope, it's not actually tied to that framework at all and is quite usable outside.


I think decorators could be used for this. check this link

Combining Descriptors with Class Decorators for Validation

For a different approach check Duck typing


Because python is dynamic, the convention is to require an object to behave like an instance of a particular class rather than enforce a specific type.

Somewhere in your code, preferably at the point where you need to access those properties, but as early as possible assert that the object has those properties and further assert that those properties are what you expect them to be.

This raises an AssertionError exception if the object o, regardless of type, if it is missing the 'someattribute' attribute:

assert(hasattr(o, 'someattribute'))

Further, if o.someattribute is not a string:

assert(isinstance(o.someattribute, basestring))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜