Login

Convert a Couchdb document into a Python object

Author:
davej
Posted:
November 29, 2008
Language:
Python
Version:
1.0
Score:
0 (after 0 ratings)

Originally posted by Leah Culver on her blog.

This allows you to convert a CouchDB document into a python object and work on CouchDB fields as if they were properties of a python object.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import couchdb
import settings
import type

class CouchObject(object):
    '''
        Convert between a CouchDB document and Python object. 
        Create Python objects while maintaining a schema-free database.
        Define object properties without storing null fields.
    '''

    @property
    def id(self):
        return self._id
    
    @property
    def rev(self):
        return self._rev

    def all_fields(self):
        # return a list of expected fields
        raise NotImplementedError("all_fields must return a list of all fields for %s" % self.__class__)

    def __init__(self, **kwargs):

        self.server = couchdb.Server(settings.COUCHDB_HOST)
        self.db = self.server[settings.COUCHDB_NAME]

        # create object properties for all desired fields
        for field_name in self.all_fields():
            # check if field exists in document
            if field_name in kwargs and kwargs[field_name] is not None:
                value = kwargs[field_name]
            else:
                value = None
            setattr(self, field_name, value)

    def to_dict(self):
        # dictionary from properties
        data_dict = {}
        for field_name in self.all_fields():
            value = getattr(self, field_name)
            if value is not None: # don't store null fields!
                data_dict[field_name] = value
        return data_dict     

    def save(self):
        self.db.update([self.to_dict()])
        return self
    
    def delete(self):
        del self.db[self._id]


## example from baconfile
class Item(CouchObject):
    """
        A file system item - a folder or a file.

        url:       /leah/code/python/hello.py/
        path:      1/code/python/hello.py
        directory: 1/code/python
    """

    def all_fields(self):
        return [
            '_id',
            '_rev',
            'directory',
            'name', 
            'user_id', 
            'is_folder', 
            'time_modified',
            'description',
            'content_type',
            'size'
        ]

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

hakanw (on December 23, 2008):

Nice, but looks very inefficient: why does every instance need its own connection to the server?

#

Please login first before commenting.