1. Marat Khabibullin
  2. wtforms


wtforms / wtforms / ext / mongoengine / document_update.py

#Author: Marat Khabibullin <maratfm@gmail.com>
from mongoengine.document import Document

def _get_list(f):
    def _wrapper(o, n):
        if o and not isinstance(o, (list, tuple)):
            raise TypeError('Must be list or tuple')
        return f(o, n) or o
    return _wrapper

def update(self, **kwargs):
    Update method that updates current instance in memory and make
    query to MongoDb.
    transforms = {
        'set': lambda o, n: n,
        'unset': lambda o, n: None,
        'inc': lambda o, n: o + n,
        'dec': lambda o, n: o - n,
        'push': _get_list(lambda o, n: not o and [n] or o.appned(n)),
        'push_all': _get_list(lambda o, n: not o and n or o.extend(n)),
        'pull': _get_list(lambda o, n: n in o and o.remove(n)),
        'pull_all': _get_list(lambda o, n: reduce(lambda x, y: y in o and o.remove(y), n, False)),

    self.commit = kwargs.pop('commit', True)

    for key, value in kwargs.iteritems():
        parts = key.split('__')
        old = getattr(self, parts[1])
        value = transforms[parts[0]](old, value)
        setattr(self, parts[1], value)

    if self.commit:
        return self.__class__.objects(id=self.id).update_one(**kwargs)

Document.update = update