当前位置: 首页>>代码示例>>Python>>正文


Python exc.NoResultFound方法代码示例

本文整理汇总了Python中sqlalchemy.orm.exc.NoResultFound方法的典型用法代码示例。如果您正苦于以下问题:Python exc.NoResultFound方法的具体用法?Python exc.NoResultFound怎么用?Python exc.NoResultFound使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在sqlalchemy.orm.exc的用法示例。


在下文中一共展示了exc.NoResultFound方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: add_token

# 需要导入模块: from sqlalchemy.orm import exc [as 别名]
# 或者: from sqlalchemy.orm.exc import NoResultFound [as 别名]
def add_token(request: LocalProxy, session: Session) -> str:
    """
    Create a new token for the user or return a
    valid existing token to the user.
    """
    token = None
    id_ = int(request.authorization['username'])
    try:
        token = session.query(Token).filter(Token.user_id == id_).one()
        if not token.is_valid():
            update_token = '%030x' % randrange(16**30)
            token.id = update_token
            token.timestamp = datetime.now()
            session.commit()
    except NoResultFound:
        token = '%030x' % randrange(16**30)
        new_token = Token(user_id=id_, id=token)
        session.add(new_token)
        session.commit()
        return token
    return token.id 
开发者ID:HTTP-APIs,项目名称:hydrus,代码行数:23,代码来源:user.py

示例2: authenticate_user

# 需要导入模块: from sqlalchemy.orm import exc [as 别名]
# 或者: from sqlalchemy.orm.exc import NoResultFound [as 别名]
def authenticate_user(id_: int, paraphrase: str, session: Session) -> bool:
    """Authenticate a user based on the ID and his paraphrase.

    Raises:
        UserNotFound: If a user with `id_` is not a valid/defined User

    """
    user = None
    try:
        user = session.query(User).filter(User.id == id_).one()
    except NoResultFound:
        raise UserNotFound(id_=id_)
    hashvalue = user.paraphrase
    generated_hash = sha224(paraphrase.encode('utf-8')).hexdigest()

    return generated_hash == hashvalue 
开发者ID:HTTP-APIs,项目名称:hydrus,代码行数:18,代码来源:user.py

示例3: insert_single

# 需要导入模块: from sqlalchemy.orm import exc [as 别名]
# 或者: from sqlalchemy.orm.exc import NoResultFound [as 别名]
def insert_single(object_: Dict[str, Any], session: scoped_session) -> Any:
    """Insert instance of classes with single objects.
    :param object_: object to be inserted
    :param session: sqlalchemy scoped session
    :return:

    Raises:
        ClassNotFound: If `type_` does not represt a valid/defined RDFClass.
        Instance: If an Instance of type `type_` already exists.

    """
    try:
        rdf_class = session.query(RDFClass).filter(
            RDFClass.name == object_["@type"]).one()
    except NoResultFound:
        raise ClassNotFound(type_=object_["@type"])

    try:
        session.query(Instance).filter(
            Instance.type_ == rdf_class.id).all()[-1]
    except (NoResultFound, IndexError, ValueError):
        return insert(object_, session=session)

    raise InstanceExists(type_=rdf_class.name) 
开发者ID:HTTP-APIs,项目名称:hydrus,代码行数:26,代码来源:crud.py

示例4: delete_single

# 需要导入模块: from sqlalchemy.orm import exc [as 别名]
# 或者: from sqlalchemy.orm.exc import NoResultFound [as 别名]
def delete_single(type_: str, session: scoped_session) -> None:
    """Delete instance of classes with single objects.
    :param type_: type of object to be deleted
    :param session: sqlalchemy scoped session
    :return: None

    Raises:
        ClassNotFound: If `type_` does not represt a valid/defined RDFClass.
        InstanceNotFound: If no Instance of the class exists.

    """
    try:
        rdf_class = session.query(RDFClass).filter(
            RDFClass.name == type_).one()
    except NoResultFound:
        raise ClassNotFound(type_=type_)

    try:
        instance = session.query(Instance).filter(
            Instance.type_ == rdf_class.id).all()[-1]
    except (NoResultFound, IndexError, ValueError):
        raise InstanceNotFound(type_=rdf_class.name)

    return delete(instance.id, type_, session=session) 
开发者ID:HTTP-APIs,项目名称:hydrus,代码行数:26,代码来源:crud.py

示例5: update_zun_service

# 需要导入模块: from sqlalchemy.orm import exc [as 别名]
# 或者: from sqlalchemy.orm.exc import NoResultFound [as 别名]
def update_zun_service(self, host, binary, values):
        session = get_session()
        with session.begin():
            query = model_query(models.ZunService, session=session)
            query = query.filter_by(host=host, binary=binary)
            try:
                ref = query.with_lockmode('update').one()
            except NoResultFound:
                raise exception.ZunServiceNotFound(host=host, binary=binary)

            if 'report_count' in values:
                if values['report_count'] > ref.report_count:
                    ref.last_seen_up = timeutils.utcnow()

            ref.update(values)
        return ref 
开发者ID:openstack,项目名称:zun,代码行数:18,代码来源:api.py

示例6: get_record

# 需要导入模块: from sqlalchemy.orm import exc [as 别名]
# 或者: from sqlalchemy.orm.exc import NoResultFound [as 别名]
def get_record(self, sequence_id: UUID, position: int) -> Any:
        """
        Gets record at position in sequence.
        """
        try:
            filter_args = {self.field_names.sequence_id: sequence_id}

            query = self.filter_by(**filter_args)

            query = self.filter_for_application_name(query)

            position_field = getattr(self.record_class, self.field_names.position)
            query = query.filter(position_field == position)
            return query.one()
        except (NoResultFound, MultipleResultsFound):
            raise IndexError(self.application_name, sequence_id, position) 
开发者ID:johnbywater,项目名称:eventsourcing,代码行数:18,代码来源:manager.py

示例7: has_tracking_record

# 需要导入模块: from sqlalchemy.orm import exc [as 别名]
# 或者: from sqlalchemy.orm.exc import NoResultFound [as 别名]
def has_tracking_record(
        self, upstream_application_name: str, pipeline_id: int, notification_id: int
    ) -> bool:
        query = self.session.query(self.tracking_record_class)
        application_name_field = (
            self.tracking_record_class.application_name  # type: ignore
        )
        upstream_name_field = (
            self.tracking_record_class.upstream_application_name  # type: ignore
        )
        pipeline_id_field = self.tracking_record_class.pipeline_id  # type: ignore
        notification_id_field = (
            self.tracking_record_class.notification_id  # type: ignore
        )

        query = query.filter(application_name_field == self.application_name)
        query = query.filter(upstream_name_field == upstream_application_name)
        query = query.filter(pipeline_id_field == pipeline_id)
        query = query.filter(notification_id_field == notification_id)
        try:
            query.one()
        except (MultipleResultsFound, NoResultFound):
            return False
        else:
            return True 
开发者ID:johnbywater,项目名称:eventsourcing,代码行数:27,代码来源:manager.py

示例8: get_subscription_by_id

# 需要导入模块: from sqlalchemy.orm import exc [as 别名]
# 或者: from sqlalchemy.orm.exc import NoResultFound [as 别名]
def get_subscription_by_id(subscription_id, session=None):
    """
    Get a specific subscription by id.

    :param subscription_id: The subscription_id to select.
    :param session: The database session in use.
    :raises: SubscriptionNotFound if no Subscription can be found.
    """

    try:
        subscription = session.query(models.Subscription).filter_by(id=subscription_id).one()
        result = {}
        for column in subscription.__table__.columns:
            result[column.name] = getattr(subscription, column.name)
        return result

    except NoResultFound:
        raise SubscriptionNotFound('No subscription with the id %s found' % (subscription_id))
    except StatementError:
        raise RucioException('Badly formatted subscription id (%s)' % (subscription_id)) 
开发者ID:rucio,项目名称:rucio,代码行数:22,代码来源:subscription.py

示例9: update_account_counter

# 需要导入模块: from sqlalchemy.orm import exc [as 别名]
# 或者: from sqlalchemy.orm.exc import NoResultFound [as 别名]
def update_account_counter(account, rse_id, session=None):
    """
    Read the updated_account_counters and update the account_counter.

    :param account:  The account to update.
    :param rse_id:   The rse_id to update.
    :param session:  Database session in use.
    """

    updated_account_counters = session.query(models.UpdatedAccountCounter).filter_by(account=account, rse_id=rse_id).all()

    try:
        account_counter = session.query(models.AccountUsage).filter_by(account=account, rse_id=rse_id).one()
        account_counter.bytes += sum([updated_account_counter.bytes for updated_account_counter in updated_account_counters])
        account_counter.files += sum([updated_account_counter.files for updated_account_counter in updated_account_counters])
    except NoResultFound:
        models.AccountUsage(rse_id=rse_id,
                            account=account,
                            files=sum([updated_account_counter.files for updated_account_counter in updated_account_counters]),
                            bytes=sum([updated_account_counter.bytes for updated_account_counter in updated_account_counters])).save(session=session)

    for update in updated_account_counters:
        update.delete(flush=False, session=session) 
开发者ID:rucio,项目名称:rucio,代码行数:25,代码来源:account_counter.py

示例10: set_tombstone

# 需要导入模块: from sqlalchemy.orm import exc [as 别名]
# 或者: from sqlalchemy.orm.exc import NoResultFound [as 别名]
def set_tombstone(rse_id, scope, name, tombstone=OBSOLETE, session=None):
    """
    Sets a tombstone on a replica.

    :param rse_id: ID of RSE.
    :param scope: scope of the replica DID.
    :param name: name of the replica DID.
    :param tombstone: the tombstone to set. Default is OBSOLETE
    :param session: database session in use.
    """
    stmt = update(models.RSEFileAssociation).where(and_(models.RSEFileAssociation.rse_id == rse_id, models.RSEFileAssociation.name == name, models.RSEFileAssociation.scope == scope,
                                                        ~session.query(models.ReplicaLock).filter_by(scope=scope, name=name, rse_id=rse_id).exists()))\
                                            .values(tombstone=tombstone)
    result = session.execute(stmt)
    if not result.rowcount:
        try:
            session.query(models.RSEFileAssociation).filter_by(scope=scope, name=name, rse_id=rse_id).one()
            raise exception.ReplicaIsLocked('Replica %s:%s on RSE %s is locked.' % (scope, name, get_rse_name(rse_id=rse_id, session=session)))
        except NoResultFound:
            raise exception.ReplicaNotFound('Replica %s:%s on RSE %s could not be found.' % (scope, name, get_rse_name(rse_id=rse_id, session=session))) 
开发者ID:rucio,项目名称:rucio,代码行数:22,代码来源:replica.py

示例11: update_exception

# 需要导入模块: from sqlalchemy.orm import exc [as 别名]
# 或者: from sqlalchemy.orm.exc import NoResultFound [as 别名]
def update_exception(exception_id, state, session=None):
    """
    Update exceptions state to Lifetime Model.

    :param exception_id:   The id of the exception
    :param state:          The states to filter
    :param session:        The database session in use.
    """
    query = session.query(models.LifetimeExceptions).filter_by(id=exception_id)
    try:
        query.first()
    except NoResultFound:
        raise LifetimeExceptionNotFound

    if state in [LifetimeExceptionsState.APPROVED, LifetimeExceptionsState.REJECTED]:
        query.update({'state': state, 'updated_at': datetime.utcnow()}, synchronize_session=False)
    else:
        raise UnsupportedOperation 
开发者ID:rucio,项目名称:rucio,代码行数:20,代码来源:lifetime_exception.py

示例12: list_content

# 需要导入模块: from sqlalchemy.orm import exc [as 别名]
# 或者: from sqlalchemy.orm.exc import NoResultFound [as 别名]
def list_content(scope, name, session=None):
    """
    List data identifier contents.

    :param scope: The scope name.
    :param name: The data identifier name.
    :param session: The database session in use.
    """
    try:
        query = session.query(models.DataIdentifierAssociation).\
            with_hint(models.DataIdentifierAssociation, "INDEX(CONTENTS CONTENTS_PK)", 'oracle').\
            filter_by(scope=scope, name=name)
        for tmp_did in query.yield_per(5):
            yield {'scope': tmp_did.child_scope, 'name': tmp_did.child_name, 'type': tmp_did.child_type,
                   'bytes': tmp_did.bytes, 'adler32': tmp_did.adler32, 'md5': tmp_did.md5}
    except NoResultFound:
        raise exception.DataIdentifierNotFound("Data identifier '%(scope)s:%(name)s' not found" % locals()) 
开发者ID:rucio,项目名称:rucio,代码行数:19,代码来源:did.py

示例13: get_metadata

# 需要导入模块: from sqlalchemy.orm import exc [as 别名]
# 或者: from sqlalchemy.orm.exc import NoResultFound [as 别名]
def get_metadata(scope, name, session=None):
    """
    Get data identifier metadata

    :param scope: The scope name.
    :param name: The data identifier name.
    :param session: The database session in use.
    """
    try:
        row = session.query(models.DataIdentifier).filter_by(scope=scope, name=name).\
            with_hint(models.DataIdentifier, "INDEX(DIDS DIDS_PK)", 'oracle').one()
        d = {}
        for column in row.__table__.columns:
            d[column.name] = getattr(row, column.name)
        return d
    except NoResultFound:
        raise exception.DataIdentifierNotFound("Data identifier '%(scope)s:%(name)s' not found" % locals()) 
开发者ID:rucio,项目名称:rucio,代码行数:19,代码来源:did.py

示例14: get_metadata_bulk

# 需要导入模块: from sqlalchemy.orm import exc [as 别名]
# 或者: from sqlalchemy.orm.exc import NoResultFound [as 别名]
def get_metadata_bulk(dids, session=None):
    """
    Get metadata for a list of dids
    :param dids: A list of dids.
    :param session: The database session in use.
    """
    condition = []
    for did in dids:
        condition.append(and_(models.DataIdentifier.scope == did['scope'],
                              models.DataIdentifier.name == did['name']))

    try:
        for chunk in chunks(condition, 50):
            for row in session.query(models.DataIdentifier).with_hint(models.DataIdentifier, "INDEX(DIDS DIDS_PK)", 'oracle').filter(or_(*chunk)):
                data = {}
                for column in row.__table__.columns:
                    data[column.name] = getattr(row, column.name)
                yield data
    except NoResultFound:
        raise exception.DataIdentifierNotFound('No Data Identifiers found') 
开发者ID:rucio,项目名称:rucio,代码行数:22,代码来源:did.py

示例15: get_did_meta

# 需要导入模块: from sqlalchemy.orm import exc [as 别名]
# 或者: from sqlalchemy.orm.exc import NoResultFound [as 别名]
def get_did_meta(scope, name, session=None):
    """
    Get all metadata for a given did

    :param scope: the scope of did
    :param name: the name of the did
    """
    if session.bind.dialect.name == 'oracle':
        oracle_version = int(session.connection().connection.version.split('.')[0])
        if oracle_version < 12:
            raise NotImplementedError

    try:
        row = session.query(models.DidMeta).filter_by(scope=scope, name=name).one()
        meta = getattr(row, 'meta')
        return json.loads(meta) if session.bind.dialect.name in ['oracle', 'sqlite'] else meta
    except NoResultFound:
        raise exception.DataIdentifierNotFound("No generic metadata found for '%(scope)s:%(name)s'" % locals()) 
开发者ID:rucio,项目名称:rucio,代码行数:20,代码来源:did.py


注:本文中的sqlalchemy.orm.exc.NoResultFound方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。