Esempio n. 1
0
 def wrapper(*args, **kwargs):
     d = Deferred()
     try:
         d.resolve(func(*args, **kwargs))
     except Exception as e:
         d.reject(exception=e)
     return d.promise()
Esempio n. 2
0
    class CollectionSaveHelper(six.Iterator):

        def __init__(self, manager, new_collection):
            self.deferred = Deferred()
            self._manager = manager
            self.new_collection = new_collection
            self.old_collection = None
            self.items = iter(new_collection)

        def __next__(self):
            return next(self.items)

        def save(self):
            # read current state of collection (it`s items)
            # if collection exists - go to next step
            # otherwise create new collection
            self._manager.storage.read_collection(self.new_collection.id)\
                    .done(partial(self._collection_found))\
                    .fail(partial(self._collection_not_found))

            return self.deferred.promise()

        def _collection_found(self, old_collection):
            self.old_collection = self._manager.collection_factory.discover(old_collection)
            self._add_items()

        def _collection_not_found(self, exception):
            self._manager.storage.create_collection(self.new_collection.id)\
                    .done(partial(self._collection_created))\
                    .fail(self.deferred.reject)

        def _collection_created(self, collection_id):
            self.new_collection.id = collection_id
            # lie that old collection was just empty
            self._collection_found([])

        def _add_items(self):
            try:
                self._manager.add_item_to_collection(self.new_collection,
                        next(self)).done(self._item_added)\
                        .fail(self.deferred.reject)
            except StopIteration:
                self._del_items()

        def _item_added(self, item_id):
            try:
                del self.old_collection[item_id]
            except:
                pass
            self._add_items()

        def _del_items(self, deleted_item_id=None):
            try:
                self._manager.remove_item_from_collection(
                        self.new_collection, next(self.old_collection))\
                        .done(partial(self._del_items))\
                        .fail(self.deferred.reject)
            except StopIteration:
                self.deferred.resolve(self.new_collection.id)