sqlalchemy.orm.exc.NoResultFound

Here are the examples of the python api sqlalchemy.orm.exc.NoResultFound taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

199 Examples 7

Example 1

Project: pytorctl
Source File: SQLSupport.py
View license
  def _update_rank_history(self, idlist):
    plog("INFO", "Consensus change... Updating rank history")
    for idhex in idlist:
      if idhex not in self.consensus.routers: continue
      rc = self.consensus.routers[idhex]
      if rc.down: continue
      try:
        r = Router.query.options(eagerload('bw_history')).filter_by(
                                    idhex=idhex).with_labels().one()
        bwh = BwHistory(router=r, rank=rc.list_rank, bw=rc.bw,
                        desc_bw=rc.desc_bw, pub_time=r.published)
        r.bw_history.append(bwh)
        #tc_session.add(bwh)
        tc_session.add(r)
      except sqlalchemy.orm.exc.NoResultFound:
        plog("WARN", "No descriptor found for consenus router "+str(idhex))

    plog("INFO", "Consensus history updated.")
    tc_session.commit()

Example 2

Project: pytorctl
Source File: SQLSupport.py
View license
  def _update_rank_history(self, idlist):
    plog("INFO", "Consensus change... Updating rank history")
    for idhex in idlist:
      if idhex not in self.consensus.routers: continue
      rc = self.consensus.routers[idhex]
      if rc.down: continue
      try:
        r = Router.query.options(eagerload('bw_history')).filter_by(
                                    idhex=idhex).with_labels().one()
        bwh = BwHistory(router=r, rank=rc.list_rank, bw=rc.bw,
                        desc_bw=rc.desc_bw, pub_time=r.published)
        r.bw_history.append(bwh)
        #tc_session.add(bwh)
        tc_session.add(r)
      except sqlalchemy.orm.exc.NoResultFound:
        plog("WARN", "No descriptor found for consenus router "+str(idhex))

    plog("INFO", "Consensus history updated.")
    tc_session.commit()

Example 3

Project: Limnoria
Source File: plugin.py
View license
        def get_alias(self, channel, name):
            name = callbacks.canonicalName(name, preserve_spaces=True)
            if minisix.PY2 and isinstance(name, str):
                name = name.decode('utf8')
            try:
                return self.get_db(channel).query(SQLAlchemyAlias.alias) \
                        .filter(SQLAlchemyAlias.name == name).one()[0]
            except sqlalchemy.orm.exc.NoResultFound:
                return None

Example 4

Project: Limnoria
Source File: plugin.py
View license
        def lock_aka(self, channel, name, by):
            name = callbacks.canonicalName(name, preserve_spaces=True)
            if minisix.PY2 and isinstance(name, str):
                name = name.decode('utf8')
            db = self.get_db(channel)
            try:
                aka = db.query(SQLAlchemyAlias) \
                        .filter(SQLAlchemyAlias.name == name).one()
            except sqlalchemy.orm.exc.NoResultFound:
                raise AkaError(_('This Aka does not exist.'))
            if aka.locked:
                raise AkaError(_('This Aka is already locked.'))
            aka.locked = True
            aka.locked_by = by
            aka.locked_at = datetime.datetime.now()
            db.commit()

Example 5

Project: Limnoria
Source File: plugin.py
View license
        def unlock_aka(self, channel, name, by):
            name = callbacks.canonicalName(name, preserve_spaces=True)
            if minisix.PY2 and isinstance(name, str):
                name = name.decode('utf8')
            db = self.get_db(channel)
            try:
                aka = db.query(SQLAlchemyAlias) \
                        .filter(SQLAlchemyAlias.name == name).one()
            except sqlalchemy.orm.exc.NoResultFound:
                raise AkaError(_('This Aka does not exist.'))
            if not aka.locked:
                raise AkaError(_('This Aka is already unlocked.'))
            aka.locked = False
            aka.locked_by = by
            aka.locked_at = datetime.datetime.now()
            db.commit()

Example 6

Project: Limnoria
Source File: plugin.py
View license
        def get_aka_lock(self, channel, name):
            name = callbacks.canonicalName(name, preserve_spaces=True)
            if minisix.PY2 and isinstance(name, str):
                name = name.decode('utf8')
            try:
                return self.get_db(channel) \
                        .query(SQLAlchemyAlias.locked, SQLAlchemyAlias.locked_by, SQLAlchemyAlias.locked_at)\
                        .filter(SQLAlchemyAlias.name == name).one()
            except sqlalchemy.orm.exc.NoResultFound:
                raise AkaError(_('This Aka does not exist.'))

Example 7

Project: Pyfa
Source File: queries.py
View license
@cachedQuery(1, "attr")
def getAttributeInfo(attr, eager=None):
    if isinstance(attr, basestring):
        filter = AttributeInfo.name == attr
    elif isinstance(attr, int):
        filter = AttributeInfo.ID == attr
    else:
        raise TypeError("Need integer or string as argument")
    try:
        result = gamedata_session.query(AttributeInfo).options(*processEager(eager)).filter(filter).one()
    except exc.NoResultFound:
        result = None
    return result

Example 8

Project: Tempo
Source File: api.py
View license
def task_get(task_uuid, session=None):
    if not session:
        session = get_session()

    try:
        return session.query(models.Task).\
                       filter_by(uuid=task_uuid).\
                       filter_by(deleted=False).\
                       one()
    except exc.NoResultFound:
        raise common_exception.NotFound(
                "No task found with UUID %s" % task_uuid)

Example 9

Project: sacrud
Source File: common.py
View license
def get_obj_by_request_data(session, table, data):
    pk = {}
    table_pk = get_pk(table)
    if not data:
        return None
    for item in table_pk:
        if item.name in data:
            pk[item.name] = data[item.name]
        else:
            return None
    try:
        return get_obj(session, table, pk)
    except sqlalchemy.orm.exc.NoResultFound:
        return None

Example 10

View license
    def _resource_exists(self, context, model, id):
        try:
            self._get_by_id(context, model, id)
        except exc.NoResultFound:
            return False
        return True

Example 11

View license
    def _delete_loadbalancer_stats(self, context, loadbalancer_id):
        # This is internal method to delete pool statistics. It won't
        # be exposed to API
        with context.session.begin(subtransactions=True):
            stats_qry = context.session.query(models.LoadBalancerStatistics)
            try:
                stats = stats_qry.filter_by(
                    loadbalancer_id=loadbalancer_id).one()
            except exc.NoResultFound:
                raise loadbalancerv2.EntityNotFound(
                    name=models.LoadBalancerStatistics.NAME,
                    id=loadbalancer_id)
            context.session.delete(stats)

Example 12

View license
    def _resource_exists(self, context, model, id):
        try:
            self._get_by_id(context, model, id)
        except exc.NoResultFound:
            return False
        return True

Example 13

View license
    def _delete_loadbalancer_stats(self, context, loadbalancer_id):
        # This is internal method to delete pool statistics. It won't
        # be exposed to API
        with context.session.begin(subtransactions=True):
            stats_qry = context.session.query(models.LoadBalancerStatistics)
            try:
                stats = stats_qry.filter_by(
                    loadbalancer_id=loadbalancer_id).one()
            except exc.NoResultFound:
                raise loadbalancerv2.EntityNotFound(
                    name=models.LoadBalancerStatistics.NAME,
                    id=loadbalancer_id)
            context.session.delete(stats)

Example 14

View license
    def _get_resource(self, context, model, id, for_update=False):
        resource = None
        try:
            if for_update:
                query = self._model_query(context, model).filter(
                    model.id == id).with_lockmode('update')
                resource = query.one()
            else:
                resource = self._get_by_id(context, model, id)
        except exc.NoResultFound:
            with excutils.save_and_reraise_exception(reraise=False) as ctx:
                if issubclass(model, (models.LoadBalancer, models.Listener,
                                      models.PoolV2, models.MemberV2,
                                      models.HealthMonitorV2,
                                      models.LoadBalancerStatistics,
                                      models.SessionPersistenceV2)):
                    raise loadbalancerv2.EntityNotFound(name=model.NAME, id=id)
                ctx.reraise = True
        return resource

Example 15

View license
    def _resource_exists(self, context, model, id):
        try:
            self._get_by_id(context, model, id)
        except exc.NoResultFound:
            return False
        return True

Example 16

View license
    def _delete_loadbalancer_stats(self, context, loadbalancer_id):
        # This is internal method to delete pool statistics. It won't
        # be exposed to API
        with context.session.begin(subtransactions=True):
            stats_qry = context.session.query(models.LoadBalancerStatistics)
            try:
                stats = stats_qry.filter_by(
                    loadbalancer_id=loadbalancer_id).one()
            except exc.NoResultFound:
                raise loadbalancerv2.EntityNotFound(
                    name=models.LoadBalancerStatistics.NAME,
                    id=loadbalancer_id)
            context.session.delete(stats)

Example 17

View license
    def _resource_exists(self, context, model, id):
        try:
            self._get_by_id(context, model, id)
        except exc.NoResultFound:
            return False
        return True

Example 18

View license
    def _delete_loadbalancer_stats(self, context, loadbalancer_id):
        # This is internal method to delete pool statistics. It won't
        # be exposed to API
        with context.session.begin(subtransactions=True):
            stats_qry = context.session.query(models.LoadBalancerStatistics)
            try:
                stats = stats_qry.filter_by(
                    loadbalancer_id=loadbalancer_id).one()
            except exc.NoResultFound:
                raise loadbalancerv2.EntityNotFound(
                    name=models.LoadBalancerStatistics.NAME,
                    id=loadbalancer_id)
            context.session.delete(stats)

Example 19

Project: dokomoforms
Source File: util.py
View license
def get_model(session, model_cls, model_id, exception=None):
    """Throw an error if session.query.get(model_id) returns None."""
    model = session.query(model_cls).get(model_id)
    if model is None:
        if exception is None:
            exception = NoResultFound((model_cls, model_id))
        raise exception
    return model

Example 20

Project: glacier-cli
Source File: glacier.py
View license
    def get_archive_id(self, vault, ref):
        try:
            result = self._get_archive_query_by_ref(vault, ref).one()
        except sqlalchemy.orm.exc.NoResultFound:
            raise KeyError(ref)
        return result.id

Example 21

Project: glacier-cli
Source File: glacier.py
View license
    def get_archive_name(self, vault, ref):
        try:
            result = self._get_archive_query_by_ref(vault, ref).one()
        except sqlalchemy.orm.exc.NoResultFound:
            raise KeyError(ref)
        return result.name

Example 22

Project: glacier-cli
Source File: glacier.py
View license
    def get_archive_name(self, vault, ref):
        try:
            result = self._get_archive_query_by_ref(vault, ref).one()
        except sqlalchemy.orm.exc.NoResultFound:
            raise KeyError(ref)
        return result.name

Example 23

Project: glacier-cli
Source File: glacier.py
View license
    def get_archive_last_seen(self, vault, ref):
        try:
            result = self._get_archive_query_by_ref(vault, ref).one()
        except sqlalchemy.orm.exc.NoResultFound:
            raise KeyError(ref)
        return result.last_seen_upstream or result.created_here

Example 24

Project: glacier-cli
Source File: glacier.py
View license
    def delete_archive(self, vault, ref):
        try:
            result = self._get_archive_query_by_ref(vault, ref).one()
        except sqlalchemy.orm.exc.NoResultFound:
            raise KeyError(name)
        result.deleted_here = time.time()
        self.session.commit()

Example 25

Project: raggregate
Source File: general.py
View license
def anon_allow(permission):
    from raggregate.models.anonallowance import AnonAllowance
    try:
        dbsession.query(AnonAllowance).filter(AnonAllowance.permission == permission).filter(AnonAllowance.allowed == True).one()
        return True
    except sqlalchemy.orm.exc.NoResultFound:
        return False

Example 26

Project: srepp_server
Source File: fileTaskWorker.py
View license
def recordAuthenticodeHashes(fileID, authenticode_hashes):
    # Find the executable file in the DB
    session = Session()
    try:
        exefile = session.query(ExecutableFiles) \
            .filter(ExecutableFiles.id == fileID).one()
    except sqlalchemy.orm.exc.NoResultFound:
        raise Exception("File ID not found in database")

    for hashType, hashValue in authenticode_hashes.iteritems():
        recordAuthenticodeHash(session, exefile, hashType, hashValue)

Example 27

Project: doubanbot
Source File: models.py
View license
    @staticmethod
    def get_authen_code(jid, session=None):
        s = session
        if not s:
	        s = Session()
        try:
            data = s.query(Authen).filter_by(jid=jid).one()
            timeout_date = datetime.datetime.now() - datetime.timedelta(minutes=int(config.AUTH_TIMEOUT))
            if data.last_modified and data.last_modified > timeout_date:
                return data.hash
        except exc.NoResultFound, e:
            pass
        finally:
            if not session:
                s.close()
        return False

Example 28

Project: u2fval
Source File: controller.py
View license
    def get_client(self, name):
        try:
            return self._session.query(Client) \
                .filter(Client.name == name) \
                .one()
        except exc.NoResultFound:
            raise KeyError('No Client with name %s found' % name)

Example 29

Project: u2fval
Source File: controller.py
View license
    def __init__(self, session, memstore, client_name, metadata,
                 require_trusted=True):
        self._session = session
        self._memstore = memstore
        try:
            self._client = session.query(Client) \
                .filter(Client.name == client_name).one()
        except exc.NoResultFound:
            raise KeyError('No Client with name %s found' % client_name)
        self._metadata = metadata
        self._require_trusted = require_trusted

Example 30

Project: OpenTAXII
Source File: api.py
View license
    def authenticate(self, username, password):
        try:
            account = Account.query.filter_by(username=username).one()
        except exc.NoResultFound:
            return

        if not account.is_password_valid(password):
            return

        return self._generate_token(account.id, ttl=TOKEN_TTL)

Example 31

Project: indico
Source File: models.py
View license
    @classmethod
    def get_one(cls, oid, is_deleted=None):
        obj = cls.get(oid, is_deleted=is_deleted)
        if obj is None:
            raise NoResultFound()
        return obj

Example 32

Project: opentuner
Source File: models.py
View license
  @classmethod
  def has_version(cls, session, version):
    try:
      session.flush()
      session.query(_Meta).filter_by(db_version=version).one()
      return True
    except sqlalchemy.orm.exc.NoResultFound:
      return False

Example 33

Project: opentuner
Source File: models.py
View license
  @classmethod
  def get_version(cls, session):
    try:
      session.flush()
      x = session.query(_Meta).one()
      return x.db_version
    except sqlalchemy.orm.exc.NoResultFound:
      return None

Example 34

Project: opentuner
Source File: models.py
View license
  @classmethod
  def get(cls, session, project, name):
    try:
      session.flush()
      return session.query(Program).filter_by(project=project, name=name).one()
    except sqlalchemy.orm.exc.NoResultFound:
      t = Program(project=project, name=name)
      session.add(t)
      return t

Example 35

Project: opentuner
Source File: models.py
View license
  @classmethod
  def get(cls, session, project, name, version, parameter_info=None):
    program = Program.get(session, project, name)
    try:
      session.flush()
      if parameter_info is None:
        return session.query(ProgramVersion).filter_by(program=program,
                                                     version=version).one()
      else:
        return session.query(ProgramVersion).filter_by(program=program,
                                                      version=version,
                                                      parameter_info=parameter_info).one()
    except sqlalchemy.orm.exc.NoResultFound:
      t = ProgramVersion(program=program, version=version, parameter_info=parameter_info)
      session.add(t)
      return t

Example 36

Project: OpenClos
Source File: dao.py
View license
    def getIfdByDeviceNamePortName(self, session, deviceName, portName):
        try:
            device = session.query(Device).filter_by(name = deviceName).one()
            return session.query(InterfaceDefinition).filter_by(device_id = device.id).filter_by(name = portName).one()
        except (exc.NoResultFound, exc.MultipleResultsFound) as ex:
            logger.info(str(ex))

Example 37

Project: OpenClos
Source File: dao.py
View license
    def getIfdByDeviceNamePortName(self, session, deviceName, portName):
        try:
            device = session.query(Device).filter_by(name = deviceName).one()
            return session.query(InterfaceDefinition).filter_by(device_id = device.id).filter_by(name = portName).one()
        except (exc.NoResultFound, exc.MultipleResultsFound) as ex:
            logger.info(str(ex))

Example 38

Project: OpenClos
Source File: l3Clos.py
View license
    def deletePod(self, podId):
        '''
        Delete an existing POD. As a sanity check, if we don't find the POD
        by UUID, a ValueException is thrown
        '''
        if podId is None: 
            raise InvalidRequest("Pod id cannot be None")

        with self._dao.getReadWriteSession() as session:        
            try:
                pod = self._dao.getObjectById(session, Pod, podId)
            except (exc.NoResultFound):
                raise PodNotFound(podId, exc) 

            self._dao.deleteObject(session, pod)
            logger.info("Pod[id='%s', name='%s']: deleted" % (pod.id, pod.name)) 

Example 39

Project: OpenClos
Source File: l3Clos.py
View license
    def deletePod(self, podId):
        '''
        Delete an existing POD. As a sanity check, if we don't find the POD
        by UUID, a ValueException is thrown
        '''
        if podId is None: 
            raise InvalidRequest("Pod id cannot be None")

        with self._dao.getReadWriteSession() as session:        
            try:
                pod = self._dao.getObjectById(session, Pod, podId)
            except (exc.NoResultFound):
                raise PodNotFound(podId, exc) 

            self._dao.deleteObject(session, pod)
            logger.info("Pod[id='%s', name='%s']: deleted" % (pod.id, pod.name)) 

Example 40

Project: OpenClos
Source File: rest.py
View license
    def isDeviceExists(self, dbSession, podId, deviceId):
        try:
            device = dbSession.query(Device).join(Pod).filter(Device.id == deviceId).filter(Pod.id == podId).one()
            return device
        except (exc.NoResultFound):
            raise bottle.HTTPError(404, exception = DeviceNotFound("No device found with podId: '%s', deviceId: '%s'" % (podId, deviceId)))

Example 41

Project: OpenClos
Source File: rest.py
View license
    def isDeviceExists(self, dbSession, podId, deviceId):
        try:
            device = dbSession.query(Device).join(Pod).filter(Device.id == deviceId).filter(Pod.id == podId).one()
            return device
        except (exc.NoResultFound):
            raise bottle.HTTPError(404, exception = DeviceNotFound("No device found with podId: '%s', deviceId: '%s'" % (podId, deviceId)))

Example 42

Project: OpenClos
Source File: ztp.py
View license
    def createPodSpecificDhcpConfFile(self, session, podId):
        if podId is not None:
            try:
                pod = self._dao.getObjectById(session, Pod, podId)
            except (exc.NoResultFound):
                raise PodNotFound("Pod[id='%s']: not found" % (podId)) 
            confWriter = DhcpConfWriter(self.__conf, pod, self._dao)
            confWriter.write(self.generatePodSpecificDhcpConf(session, pod.id))
        else:
            raise PodNotFound("Pod id can't be None")

Example 43

Project: Mycodo
Source File: init_databases.py
View license
def delete_user(username):
    if query_yes_no("Confirm delete user '{}' from user database.".format(username)):
        try:
            with session_scope(USER_DB_PATH) as db_session:
                user = db_session.query(Users).filter(Users.user_name == username).one()
                db_session.delete(user)
                print("User deleted.")
                sys.exit(0)
        except sqlalchemy.orm.exc.NoResultFound:
            print("No user found with this name.")
            sys.exit(1)

Example 44

Project: Mycodo
Source File: init_databases.py
View license
def delete_user(username):
    if query_yes_no("Confirm delete user '{}' from user database.".format(username)):
        try:
            with session_scope(USER_DB_PATH) as db_session:
                user = db_session.query(Users).filter(Users.user_name == username).one()
                db_session.delete(user)
                print("User deleted.")
                sys.exit(0)
        except sqlalchemy.orm.exc.NoResultFound:
            print("No user found with this name.")
            sys.exit(1)

Example 45

Project: Mycodo
Source File: init_databases.py
View license
def change_password(username):
    print('Changing password for {}'.format(username))

    with session_scope(USER_DB_PATH) as db_session:
        user = db_session.query(Users).filter(Users.user_name == username).one()

        while True:
            user_password = getpass.getpass('Password: ')
            user_password_again = getpass.getpass('Password (again): ')
            if user_password != user_password_again:
                print("Passwords don't match")
            else:
                try:
                    if test_password(user_password):
                        user.set_password(user_password)
                        sys.exit(0)
                except sqlalchemy.orm.exc.NoResultFound:
                    print("No user found with this name.")
                    sys.exit(1)

Example 46

Project: Mycodo
Source File: init_databases.py
View license
def change_password(username):
    print('Changing password for {}'.format(username))

    with session_scope(USER_DB_PATH) as db_session:
        user = db_session.query(Users).filter(Users.user_name == username).one()

        while True:
            user_password = getpass.getpass('Password: ')
            user_password_again = getpass.getpass('Password (again): ')
            if user_password != user_password_again:
                print("Passwords don't match")
            else:
                try:
                    if test_password(user_password):
                        user.set_password(user_password)
                        sys.exit(0)
                except sqlalchemy.orm.exc.NoResultFound:
                    print("No user found with this name.")
                    sys.exit(1)

Example 47

Project: bag
Source File: testing.py
View license
    def one(self):
        """Ensure there is only one result and returns i, or raise."""
        alist = self.all()
        if not alist:
            raise NoResultFound("No row was found for one()")
        elif len(alist) > 1:
            raise MultipleResultsFound("Multiple rows were found for one()")
        else:
            return alist[0]

Example 48

Project: bag
Source File: testing.py
View license
    def one(self):
        """Ensure there is only one result and returns i, or raise."""
        alist = self.all()
        if not alist:
            raise NoResultFound("No row was found for one()")
        elif len(alist) > 1:
            raise MultipleResultsFound("Multiple rows were found for one()")
        else:
            return alist[0]

Example 49

Project: cloudkitty
Source File: api.py
View license
    def set_state(self, name, state):
        session = db.get_session()
        with session.begin():
            try:
                q = utils.model_query(
                    models.StateInfo,
                    session)
                q = q.filter(models.StateInfo.name == name)
                q = q.with_lockmode('update')
                db_state = q.one()
                db_state.state = state
            except sqlalchemy.orm.exc.NoResultFound:
                db_state = models.StateInfo(name=name,
                                            state=state)
                session.add(db_state)
        return db_state.state

Example 50

Project: cloudkitty
Source File: api.py
View license
    def set_metadata(self, name, metadata):
        session = db.get_session()
        with session.begin():
            try:
                q = utils.model_query(
                    models.StateInfo,
                    session)
                q = q.filter(models.StateInfo.name == name)
                q = q.with_lockmode('update')
                db_state = q.one()
                db_state.s_metadata = metadata
            except sqlalchemy.orm.exc.NoResultFound:
                db_state = models.StateInfo(name=name,
                                            s_metadata=metadata)
                session.add(db_state)