def create(self, collection_id, parent_id, record, id_generator=None, unique_fields=None, id_field=DEFAULT_ID_FIELD, modified_field=DEFAULT_MODIFIED_FIELD, auth=None): """Create the specified `object` in this `collection_id` for this `parent_id`. Assign the id to the object, using the attribute :attr:`cliquet.resource.Model.id_field`. .. note:: This will update the collection timestamp. :raises: :exc:`cliquet.storage.exceptions.UnicityError` :param str collection_id: the collection id. :param str parent_id: the collection parent. :param dict record: the object to create. :returns: the newly created object. :rtype: dict """ obj = self.collection.serialize(record) obj.parent_id = parent_id setattr(obj, modified_field, datetime.datetime.utcnow()) try: Session.add(obj) Session.flush() except IntegrityError as e: logger.exception('Object %s for collection %s raised %s', record, self.collection, e) process_unicity_error(e, Session, self.collection, record) # TODO: store new timestamps date return self.collection.deserialize(obj)
def get_class(cls, session, error, collection, record): for subclass in cls.__subclasses__(): try: if cls.subclass_comparison(subclass, **cls.format_parameters(session=session, error=error)): return subclass.get_class(session, error, collection, record).process_error() except UnicityError as e: raise except Exception as e: # probably engine not yet binded: log error and return standard parent class logger.exception('Error while fetching Error subclass: %s. Parameters were: %s, %s, %s', e, session, error, collection) return cls(error, collection, record).process_error()
def ping(request): """Test that cache backend is operationnal. :param request: current request object :type request: :class:`~pyramid:pyramid.request.Request` :returns: ``True`` is everything is ok, ``False`` otherwise. :rtype: bool """ # No specific case for readonly mode because the cache should # continue to work in that mode. try: if random.random() < _HEARTBEAT_DELETE_RATE: backend.delete(_HEARTBEAT_KEY) else: backend.set(_HEARTBEAT_KEY, 'alive', _HEARTBEAT_TTL_SECONDS) return True except: logger.exception("Heartbeat Failure") return False
def attachments_ping(request): """Heartbeat view for the attachments backend. :returns: ``True`` if succeeds to write and delete, ``False`` otherwise. """ # Do nothing if server is readonly. if asbool(request.registry.settings.get('readonly', False)): return True status = False attachment = request.attachment try: location = attachment.save_file(StringIO(HEARTBEAT_CONTENT), HEARTBEAT_FILENAME, replace=True) attachment.delete(location) status = True except Exception as e: logger.exception(e) return status
def ping(request): """Test the permission backend is operationnal. :param request: current request object :type request: :class:`~pyramid:pyramid.request.Request` :returns: ``True`` is everything is ok, ``False`` otherwise. :rtype: bool """ try: if asbool(request.registry.settings.get('readonly')): # Do not try to write in readonly mode. backend.user_principals(__HEARTBEAT_KEY__) else: backend.add_user_principal(__HEARTBEAT_KEY__, 'alive') backend.remove_user_principal(__HEARTBEAT_KEY__, 'alive') except: logger.exception("Heartbeat Error") return False return True
def timestamp(self): """Return the current collection timestamp. :rtype: int """ try: return self.model.timestamp() except storage_exceptions.BackendError as e: is_readonly = self.request.registry.settings['readonly'] if not is_readonly: raise e # If the instance is configured to be readonly, and if the # collection is empty, the backend will try to bump the timestamp. # It fails if the configured db user has not write privileges. logger.exception(e) error_msg = ("Collection timestamp cannot be written. " "Records endpoint must be hit at least once from a " "writable instance.") raise http_error(HTTPServiceUnavailable(), errno=ERRORS.BACKEND, message=error_msg)
def ping(request): """Test that storage is operationnal. :param request: current request object :type request: :class:`~pyramid:pyramid.request.Request` :returns: ``True`` is everything is ok, ``False`` otherwise. :rtype: bool """ try: auth = request.headers.get("Authorization") if asbool(request.registry.settings.get("readonly")): # Do not try to write in readonly mode. backend.get_all(_HEARTBEAT_COLLECTION_ID, _HEART_PARENT_ID, auth=auth) else: if random.random() < _HEARTBEAT_DELETE_RATE: backend.delete_all(_HEARTBEAT_COLLECTION_ID, _HEART_PARENT_ID, auth=auth) else: backend.create(_HEARTBEAT_COLLECTION_ID, _HEART_PARENT_ID, _HEARTBEAT_RECORD, auth=auth) return True except: logger.exception("Heartbeat Error") return False
def wrapped(*args, **kwargs): try: return func(*args, **kwargs) except redis.RedisError as e: logger.exception(e) raise exceptions.BackendError(original=e)
def serialize(self, dict_, context=None): try: return self.__schema__.objectify(dict_, context) except AttributeError: logger.exception('Schema for collection %s has not been set', self.collection) raise Exception('Schema not set for model')
def deserialize(self): try: return self.__schema__.dictify(self) except AttributeError: logger.exception('Schema for collection %s has not been set', self.collection) raise Exception('Schema not set for model')