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


Python exc.MultipleResultsFound方法代码示例

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


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

示例1: get_record

# 需要导入模块: from sqlalchemy.orm import exc [as 别名]
# 或者: from sqlalchemy.orm.exc import MultipleResultsFound [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

示例2: has_tracking_record

# 需要导入模块: from sqlalchemy.orm import exc [as 别名]
# 或者: from sqlalchemy.orm.exc import MultipleResultsFound [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

示例3: from_schedule

# 需要导入模块: from sqlalchemy.orm import exc [as 别名]
# 或者: from sqlalchemy.orm.exc import MultipleResultsFound [as 别名]
def from_schedule(cls, dbsession, schedule):
        spec = {'minute': schedule._orig_minute,
                'hour': schedule._orig_hour,
                'day_of_week': schedule._orig_day_of_week,
                'day_of_month': schedule._orig_day_of_month,
                'month_of_year': schedule._orig_month_of_year}
        try:
            query = dbsession.query(CrontabSchedule)
            query = query.filter_by(**spec)
            existing = query.one()
            return existing
        except NoResultFound:
            return cls(**spec)
        except MultipleResultsFound:
            query = dbsession.query(CrontabSchedule)
            query = query.filter_by(**spec)
            query.delete()
            dbsession.commit()
            return cls(**spec) 
开发者ID:tuomur,项目名称:celery_sqlalchemy_scheduler,代码行数:21,代码来源:sqlalchemy_scheduler_models.py

示例4: connections_delete

# 需要导入模块: from sqlalchemy.orm import exc [as 别名]
# 或者: from sqlalchemy.orm.exc import MultipleResultsFound [as 别名]
def connections_delete(args):
    """Deletes connection from DB"""
    with create_session() as session:
        try:
            to_delete = (session
                         .query(Connection)
                         .filter(Connection.conn_id == args.conn_id)
                         .one())
        except exc.NoResultFound:
            msg = '\n\tDid not find a connection with `conn_id`={conn_id}\n'
            msg = msg.format(conn_id=args.conn_id)
            print(msg)
            return
        except exc.MultipleResultsFound:
            msg = ('\n\tFound more than one connection with ' +
                   '`conn_id`={conn_id}\n')
            msg = msg.format(conn_id=args.conn_id)
            print(msg)
            return
        else:
            deleted_conn_id = to_delete.conn_id
            session.delete(to_delete)
            msg = '\n\tSuccessfully deleted `conn_id`={conn_id}\n'
            msg = msg.format(conn_id=deleted_conn_id)
            print(msg) 
开发者ID:apache,项目名称:airflow,代码行数:27,代码来源:connection_command.py

示例5: get_ori_identifier

# 需要导入模块: from sqlalchemy.orm import exc [as 别名]
# 或者: from sqlalchemy.orm.exc import MultipleResultsFound [as 别名]
def get_ori_identifier(self, iri):
        """
        Retrieves a Resource-based ORI identifier from the database. If no corresponding Resource exists,
        a new one is created.
        """

        session = self.Session()
        try:
            resource = session.query(Resource).join(Source).filter(Source.iri == iri).first()
            if not resource:
                raise NoResultFound
            return Uri(Ori, resource.ori_id)
        except MultipleResultsFound:
            raise MultipleResultsFound('Multiple resources found for IRI %s' % iri)
        except NoResultFound:
            return self.generate_ori_identifier(iri=iri)
        finally:
            session.close() 
开发者ID:openstate,项目名称:open-raadsinformatie,代码行数:20,代码来源:postgres_database.py

示例6: ca_trust_payload_from_configuration

# 需要导入模块: from sqlalchemy.orm import exc [as 别名]
# 或者: from sqlalchemy.orm.exc import MultipleResultsFound [as 别名]
def ca_trust_payload_from_configuration() -> PEMCertificatePayload:
    """Create a CA payload with the PEM representation of the Certificate Authority used by this instance.

    You need to check whether the app config contains 'CA_CERTIFICATE' before invoking this.
    """
    try:
        org = db.session.query(Organization).one()
    except NoResultFound:
        abort(500, 'No organization is configured, cannot generate enrollment profile.')
    except MultipleResultsFound:
        abort(500, 'Multiple organizations, backup your database and start again')

    with open(current_app.config['CA_CERTIFICATE'], 'rb') as fd:
        pem_data = fd.read()
        pem_payload = PEMCertificatePayload(
            uuid=uuid4(),
            identifier=org.payload_prefix + '.ca',
            payload_content=pem_data,
            display_name='Certificate Authority',
            description='Required for your device to trust the server',
            type='com.apple.security.root',
            version=1
        )

        return pem_payload 
开发者ID:cmdmnt,项目名称:commandment,代码行数:27,代码来源:profiles.py

示例7: ssl_trust_payload_from_configuration

# 需要导入模块: from sqlalchemy.orm import exc [as 别名]
# 或者: from sqlalchemy.orm.exc import MultipleResultsFound [as 别名]
def ssl_trust_payload_from_configuration() -> PEMCertificatePayload:
    """Generate a PEM certificate payload in order to trust this host.

    """
    try:
        org = db.session.query(Organization).one()
    except NoResultFound:
        abort(500, 'No organization is configured, cannot generate enrollment profile.')
    except MultipleResultsFound:
        abort(500, 'Multiple organizations, backup your database and start again')

    basepath = os.path.dirname(__file__)
    certpath = os.path.join(basepath, current_app.config['SSL_CERTIFICATE'])

    with open(certpath, 'rb') as fd:
        pem_payload = PEMCertificatePayload(
            uuid=uuid4(),
            identifier=org.payload_prefix + '.ssl',
            payload_content=fd.read(),
            display_name='Web Server Certificate',
            description='Required for your device to trust the server',
            type='com.apple.security.pkcs1',
            version=1
        )
        return pem_payload 
开发者ID:cmdmnt,项目名称:commandment,代码行数:27,代码来源:profiles.py

示例8: get_or_create

# 需要导入模块: from sqlalchemy.orm import exc [as 别名]
# 或者: from sqlalchemy.orm.exc import MultipleResultsFound [as 别名]
def get_or_create(cls, channel, location):
        try:
            cls.validate(channel, location)
        except ValidationError as err:
            raise ValueError("invalid value {}: {}".format(location, err))

        try:
            r = DB.session.query(cls) \
                .filter(and_(cls.channel == channel,
                             cls.location == location)) \
                .one()
        except (MultipleResultsFound, NoResultFound,):
            r = cls(channel=channel, location=location)
            DB.session.add(r)
            DB.session.flush()
        return r 
开发者ID:geopython,项目名称:GeoHealthCheck,代码行数:18,代码来源:models.py

示例9: __init__

# 需要导入模块: from sqlalchemy.orm import exc [as 别名]
# 或者: from sqlalchemy.orm.exc import MultipleResultsFound [as 别名]
def __init__(self, problem, database = "featurehub"):
        self.__database            = database
        self.__orm                 = ORMManager(database)
        self.__username            = None

        with self.__orm.session_scope() as session:
            try:
                problem = session.query(Problem)\
                                 .filter(Problem.name == problem)\
                                 .one()
                self.__problem_id = problem.id
            except NoResultFound:
                raise ValueError("Invalid problem name: {}".format(problem))
            except MultipleResultsFound:
                raise ValueError("Unexpected issue talking to database. " +
                                 TRY_AGAIN_LATER)

        # "log in" to the system
        self._login()

        # initialize evaluation client
        self.__evaluation_client = EvaluatorClient(self.__problem_id,
                self.__username, self.__orm) 
开发者ID:HDI-Project,项目名称:FeatureHub,代码行数:25,代码来源:session.py

示例10: _login

# 需要导入模块: from sqlalchemy.orm import exc [as 别名]
# 或者: from sqlalchemy.orm.exc import MultipleResultsFound [as 别名]
def _login(self):
        name = os.environ.get("USER")
        if not name:
            raise ValueError("Missing environment variable 'USER'. FeatureHub"
                             " session not initialized.")

        with self.__orm.session_scope() as session:
            try:
                user = session.query(User)\
                              .filter(User.name == name)\
                              .one()
                self.__username = user.name
            except NoResultFound:
                data = { "database" : self.__orm.database }
                response = Session._eval_server_post("create-user", data)
                if response.ok:
                    self.__username = name
                else:
                    raise ValueError("Couldn't log in to FeatureHub. " \
                                     + TRY_AGAIN_LATER) 

            except MultipleResultsFound as e:
                raise ValueError("Unexpected error logging in to FeatureHub. " \
                                 + TRY_AGAIN_LATER) 
开发者ID:HDI-Project,项目名称:FeatureHub,代码行数:26,代码来源:session.py

示例11: _get_project

# 需要导入模块: from sqlalchemy.orm import exc [as 别名]
# 或者: from sqlalchemy.orm.exc import MultipleResultsFound [as 别名]
def _get_project(session, project):
    """Helper method to return Project class for a project with the given name.

    Args:
        session: SQLAlchemy ORM Session object
        project: Name of the project (e.g. 'build-tools')

    Returns:
        the corresponding python Project object

    Exceptions:
        HTTP 404: Project could not be found
        HTTP 500: Multiple projects with same name found
    """
    try:
        return Project.query.filter_by(name=project).one()
    except MultipleResultsFound:
        abort(500, "Multiple projects with name %s found in database" %
              project)
    except NoResultFound:
        abort(404, "Could not find project %s in database" % project) 
开发者ID:mozilla,项目名称:build-relengapi,代码行数:23,代码来源:__init__.py

示例12: get_rev

# 需要导入模块: from sqlalchemy.orm import exc [as 别名]
# 或者: from sqlalchemy.orm.exc import MultipleResultsFound [as 别名]
def get_rev(projects, vcs_type, commit):
    # (documentation in relengapi/docs/usage/mapper.rst)
    _check_well_formed_sha(vcs_type, commit, exact_length=None)  # can raise http 400
    q = Hash.query.join(Project).filter(_project_filter(projects))
    if vcs_type == "git":
        q = q.filter(sa.text("git_commit like :cspatttern")).params(
            cspatttern=commit + "%")
    elif vcs_type == "hg":
        q = q.filter(sa.text("hg_changeset like :cspatttern")).params(
            cspatttern=commit + "%")
    try:
        row = q.one()
        return "%s %s" % (row.git_commit, row.hg_changeset)
    except NoResultFound:
        if vcs_type == "git":
            abort(404, "No hg changeset found for git commit id %s in project(s) %s"
                  % (commit, projects))
        elif vcs_type == "hg":
            abort(404, "No git commit found for hg changeset %s in project(s) %s"
                  % (commit, projects))
    except MultipleResultsFound:
        abort(500, "Internal error - multiple results returned for %s commit %s"
              "in project %s - this should not be possible in database"
              % (vcs_type, commit, projects)) 
开发者ID:mozilla,项目名称:build-relengapi,代码行数:26,代码来源:__init__.py

示例13: insert_one

# 需要导入模块: from sqlalchemy.orm import exc [as 别名]
# 或者: from sqlalchemy.orm.exc import MultipleResultsFound [as 别名]
def insert_one(project, git_commit, hg_changeset):
    # (documentation in relengapi/docs/usage/mapper.rst)
    session = g.db.session(DB_DECLARATIVE_BASE)
    proj = _get_project(session, project)  # can raise HTTP 404 or HTTP 500
    _add_hash(session, git_commit, hg_changeset, proj)  # can raise HTTP 400
    try:
        session.commit()
        q = Hash.query.join(Project).filter(_project_filter(project))
        q = q.filter(sa.text("git_commit == :commit")).params(commit=git_commit)
        return q.one().as_json()
    except sa.exc.IntegrityError:
        abort(409, "Provided mapping %s %s for project %s already exists and "
              "cannot be reinserted" % (git_commit, hg_changeset, project))
    except NoResultFound:
        abort(500, "Provided mapping %s %s for project %s could not be inserted "
              "into the database" % (git_commit, hg_changeset, project))
    except MultipleResultsFound:
        abort(500, "Provided mapping %s %s for project %s has been inserted into "
              "the database multiple times" % (git_commit, hg_changeset, project)) 
开发者ID:mozilla,项目名称:build-relengapi,代码行数:21,代码来源:__init__.py

示例14: retrieve_worker_results

# 需要导入模块: from sqlalchemy.orm import exc [as 别名]
# 或者: from sqlalchemy.orm.exc import MultipleResultsFound [as 别名]
def retrieve_worker_results(rdb, external_request_id):
    """Retrieve results for all workers from RDB."""
    start = datetime.datetime.now()
    try:
        query = rdb.session.query(WorkerResult) \
                           .filter(WorkerResult.external_request_id == external_request_id)
        results = query.all()
    except (NoResultFound, MultipleResultsFound):
        return None
    except SQLAlchemyError:
        rdb.session.rollback()
        raise

    # compute elapsed time
    elapsed_seconds = (datetime.datetime.now() - start).total_seconds()
    msg = "It took {t} seconds to retrieve " \
          "all worker results for {r}.".format(t=elapsed_seconds, r=external_request_id)
    current_app.logger.debug(msg)

    return results 
开发者ID:fabric8-analytics,项目名称:fabric8-analytics-server,代码行数:22,代码来源:utils.py

示例15: retrieve_worker_result

# 需要导入模块: from sqlalchemy.orm import exc [as 别名]
# 或者: from sqlalchemy.orm.exc import MultipleResultsFound [as 别名]
def retrieve_worker_result(rdb, external_request_id, worker):
    """Retrieve results for selected worker from RDB."""
    start = datetime.datetime.now()
    try:
        query = rdb.session.query(WorkerResult) \
                           .filter(WorkerResult.external_request_id == external_request_id,
                                   WorkerResult.worker == worker)
        result = query.one()
    except (NoResultFound, MultipleResultsFound):
        return None
    except SQLAlchemyError:
        rdb.session.rollback()
        raise
    result_dict = result.to_dict()

    # compute elapsed time
    elapsed_seconds = (datetime.datetime.now() - start).total_seconds()
    msg = "It took {t} seconds to retrieve {w} " \
          "worker results for {r}.".format(t=elapsed_seconds, w=worker, r=external_request_id)
    current_app.logger.debug(msg)

    return result_dict 
开发者ID:fabric8-analytics,项目名称:fabric8-analytics-server,代码行数:24,代码来源:utils.py


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