I’ve spend some time to create a construct in python which allows me to transparently map an CouchDB (or any other document based database) document to a Class. For example a User class or later called Model should give access trough class attributes to the fields of the document. For that i had to manipulate getattr whit the help of a decorator. I had to deal with several issues till i got the perfect construct. StackOverflow helped me to find the way in this and this post.
This is a good example to understand how decorators in Python do work. The code here does simply demonstrate how the decorator works.
# should later connect to a read remote datasource class Connector(object): data = {"emailAddress":"jackbauer@ctu.org", "lastName":"Bauer"} def readvar(self, var): return self.data[var] # This is the Decorator class DocumentDB(object): def __init__(self,connector): self.connector = connector def __call__(self, *args, **kargs): _c = self.connector # _c needs to be set to make the connector accessible for Transparent Attribute class TransparentAttribute(args[0]): def __getattr__(self, attrname): try: return _c.readvar(attrname) except: # If the field does not exist at the datasource, return the attribute from the object return getattr(args[0], attrname) return TransparentAttribute c = Connector() @DocumentDB(c) class User(object): username = "JackBauer" def doSomething(self): print "I'am Jack bauer" def doSomethingElse(self): pass u = User() u.doSomething() print u.emailAddress # Field from the Datasource print u.lastName # Field from the Datasource print u.username |
There was another way suggested on Stackoverflow to use Metaclasses. My personal opinion in this case is to use the decorator. Metaclasses does make sense if you work with databases in a classical sense where the fields are all known. Documents my be slightly different from each other. So their form would have to get interpreted on each attribute access or either the attributes are dynamically mapped.
Feelfree to comment this example!
Tagged: CouchDB, DB, Decorators, howto, python, StackoverFlow

