Home

I've Lost My Mind @ 2010-03-13 23:27:00
Filed under: Code  Tech  Python 
Heh. I like MongoDB but I don't know why I wrote this ....

class _MongoSaveable(object):
    """
    Simple mongodb saveable object. Saves all attributes.

    You can force saves using a shortcut like so:
       >>> save = lambda s: s.__mongo_save__(COLLECTION)
       >>> save(my_instance)
    """

    _id = None
    _dirty = False

    def __setattr__(self, name, value):
        """
        TRY TO CATCH ME RIDN DIRTY *money money money*

        :Parameters:
           - `name`: key name
           - `value`: data to store
        """
        self.__dict__['_dirty'] = True
        self.__dict__[name] = value

    def __mongo_save__(self, collection):
       """
       Insert or Update data.

       :Parameters:
          - `collection`: the collection to associate with
       """
       if not self._dirty:
           return None
       result = {}
       for x in dir(self):
           if (not x.startswith('_') and
               not callable(getattr(self, x)) and
               x not in ("id", "dirty")):
               result[x] = getattr(self, x)
       if self._id:
           collection.save(result)
       else:
           saved_data = collection.find_one(result)
           if saved_data:
               self._id = saved_data["_id"]
           else:
               self._id = collection.insert(result)
       self._dirty = False

    dirty = property(lambda s: s._dirty)
    id = property(lambda s: s._id)


# PSUEDO EXAMPLE!!!!

import pymongo

from myapp import Example

# Connection stuff
DB = pymongo.Connection().my_database
COLLECTION = DB.my_collection

# Save shortcut
save = lambda s: s.__mongo_save__(COLLECTION)


class DataExample(Example, _MongoSaveable):
    def __init__(self, weight):
        self.weight = weight

    def calculate_status(self):
        if self.weight > 175:
            self.status = "lose wight"
        else:
            self.status = "doin fine"

ex = DataExample(150)
ex.calculate_status()
save(ex)
print ex.id # 4b9c6398bdcf5f4053000000
ex.goal_weight = 160
save(ex) 
print ex.id # 4b9c6398bdcf5f4053000000

 digg it   seed it   del.icio.us   ma.gnolia
Tags:       Log in to post comments.


 
A Django joint.
© 2007-2009 Steve 'Ashcrow' Milner | Studio7designs | Arbutus Photography