python类MultipleResultsFound()的实例源码

__init__.py 文件源码 项目:tuning-box 作者: openstack 项目源码 文件源码 阅读 52 收藏 0 点赞 0 评论 0
def get_resource_definition(id_or_name, environment_id):
    query = db.ResourceDefinition.query.join(db.Component). \
        join(db.Environment.environment_components_table). \
        filter_by(environment_id=environment_id)

    if isinstance(id_or_name, int):
        query = query.filter(db.ResourceDefinition.id == id_or_name)
    else:
        query = query.filter(db.ResourceDefinition.name == id_or_name)

    result = query.all()

    if not result:
        raise errors.TuningboxNotFound(
            "{0} not found by {1} in environment {2}".format(
                db.ResourceDefinition.__tablename__,
                id_or_name,
                environment_id
            )
        )
    elif len(result) > 1:
        raise sa_exc.MultipleResultsFound

    return result[0]
mh_caller.py 文件源码 项目:sciz 作者: erk3 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def monstres_ftp_call(self):
        # Fetch MH Monstres (Metamobs) from FTP
        mh_r = requests.get("http://%s/%s" % (self.ftpURL, self.ftpMonstres, ))
        lines = mh_r.text.split('\n')
        for line in lines:
            if line.find(";") > 0:
                id, nom, determinant, blason_url, empty = line.split(';')
                try:
                    metamob = sg.db.session.query(METAMOB).filter(METAMOB.id == id).one()
                except NoResultFound, MultipleResultsFound:
                    metamob = METAMOB()
                metamob.id = id
                metamob.nom = nom
                metamob.determinant = determinant
                metamob.blason_url = blason_url
                sg.db.session.add(metamob)
        sg.db.session.commit()

    # Main MH call dispatcher
base.py 文件源码 项目:marcotti-mls 作者: soccermetrics 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def get_id(self, model, **conditions):
        """
        Retrieve unique ID of record in database model that satisfies conditions.

        If no unique record exists, communicate error in log file and return None.

        :param model: Marcotti-MLS data model.
        :param conditions: Dictionary of fields/values that describe a record in model.
        :return: Unique ID of database record.
        """
        record_id = None
        try:
            record_id = self.session.query(model).filter_by(**conditions).one().id
        except NoResultFound:
            logger.error("{} has no records in Marcotti database for: {}".format(model.__name__, conditions))
        except MultipleResultsFound:
            logger.error("{} has multiple records in Marcotti database for: {}".format(model.__name__, conditions))
        return record_id
test_engine.py 文件源码 项目:deb-python-pykmip 作者: openstack 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def test_get_object_type_multiple_objects(self):
        """
        Test that a sqlalchemy.orm.exc.MultipleResultsFound error is generated
        when getting the object type of multiple objects map to the same
        object ID.
        """
        e = engine.KmipEngine()
        e._data_store = self.engine
        e._data_store_session_factory = self.session_factory
        e._data_session = e._data_store_session_factory()
        test_exception = exc.MultipleResultsFound()
        e._data_session.query = mock.MagicMock(side_effect=test_exception)
        e._logger = mock.MagicMock()

        args = ('1', )
        self.assertRaises(
            exc.MultipleResultsFound,
            e._get_object_type,
            *args
        )
        e._data_session.commit()
        e._logger.warning.assert_called_once_with(
            "Multiple objects found for ID: 1"
        )
utils.py 文件源码 项目:fabric8-analytics-server 作者: fabric8-analytics 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def retrieve_worker_results(rdb, external_request_id):
    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

    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
utils.py 文件源码 项目:fabric8-analytics-server 作者: fabric8-analytics 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def retrieve_worker_result(rdb, external_request_id, worker):
    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()
    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
test_engine.py 文件源码 项目:deb-python-kmip 作者: openstack 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def test_get_object_type_multiple_objects(self):
        """
        Test that a sqlalchemy.orm.exc.MultipleResultsFound error is generated
        when getting the object type of multiple objects map to the same
        object ID.
        """
        e = engine.KmipEngine()
        e._data_store = self.engine
        e._data_store_session_factory = self.session_factory
        e._data_session = e._data_store_session_factory()
        test_exception = exc.MultipleResultsFound()
        e._data_session.query = mock.MagicMock(side_effect=test_exception)
        e._logger = mock.MagicMock()

        args = ('1', )
        self.assertRaises(
            exc.MultipleResultsFound,
            e._get_object_type,
            *args
        )
        e._data_session.commit()
        e._logger.warning.assert_called_once_with(
            "Multiple objects found for ID: 1"
        )
session.py 文件源码 项目:FeatureHub 作者: HDI-Project 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
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)
session.py 文件源码 项目:FeatureHub 作者: HDI-Project 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
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)
serializers.py 文件源码 项目:contactista 作者: singingwolfboy 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def get_pronouns_by_subject(subject_pronoun):
    """
    Given a subject pronoun (as a string), return the Pronouns object
    that corresponds to that subject pronoun. This can be called with
    strings like "he", "she", and "it".

    If no Pronouns object is found that matches this subject pronoun, or
    there are multiple Pronouns objects that match, a ValidationError is raised.
    """
    try:
        return Pronouns.query.filter_by(subject=subject_pronoun).one()
    except NoResultFound:
        raise ValidationError(
            'No set of pronouns found for subject pronoun "{subject}"'.format(
                subject=subject_pronoun
            )
        )
    except MultipleResultsFound:
        raise ValidationError(
            'Multiple sets of pronouns found for subject pronoun '
            '"{subject}". Use more specific filters.'.format(
                subject=subject_pronoun
            )
        )
serializers.py 文件源码 项目:contactista 作者: singingwolfboy 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def get_pronouns_by_filters(filters):
    """
    Given a dictionary of pronoun filters, return the Pronouns object
    that corresponds to those pronouns pronoun. Some examples:

    {"subject": "he"}
    {"subject": "they", "reflexive": "themself"}
    {"subject": "they", "reflexive": "themselves"}
    {"possessive": "hers"}

    If no Pronouns object is found that matches these filters, or
    there are multiple Pronouns objects that match, a ValidationError is raised.
    """
    try:
        return Pronouns.query.filter_by(**filters).one()
    except NoResultFound:
        raise ValidationError(
            "No set of pronouns found for filters."
        )
    except MultipleResultsFound:
        raise ValidationError(
            "Multiple sets of pronouns found. Use more specific filters."
        )
package_postgres.py 文件源码 项目:fabric8-analytics-worker 作者: fabric8-analytics 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def get_analysis_by_id(self, analysis_id):
        """Get result of previously scheduled analysis

        :param analysis_id: str, ID of analysis
        :return: analysis result
        """

        try:
            return PostgresBase.session.query(PackageAnalysis).\
                                        filter(PackageAnalysis.id == analysis_id).\
                                        one()
        except (NoResultFound, MultipleResultsFound):
            raise
        except SQLAlchemyError:
            PostgresBase.session.rollback()
            raise
switching.py 文件源码 项目:GridLight-Server 作者: Lunabit 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def contracts_set_to_expire():
    expiring_contracts = []

    for contract in Contract.query.all():
        try:
            user = User.query.filter(User.id==contract.user_id).one()
        except (NoResultFound, MultipleResultsFound) as e:
            err = "No valid user associated with contract (id={}).".format(contract.id)
            print_log(err)
            raise InvalidUsage(message=err, status_code=500)

        today = datetime.today()
        expiration_date = contract.expiration
        notif_days = timedelta(days=user.notif_days)

        notifs_are_ready = (today - notif_days) <= expiration_date
        is_notif_day = (today - (expiration_date - notif_days)).days % user.notif_freq == 0

        if notifs_are_ready and is_notif_day:
            expiring_contracts.append(contract)

    return expiring_contracts
__init__.py 文件源码 项目:GridLight-Server 作者: Lunabit 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def delete_users_contracts(contract_id: int):
    try:
        contract = Contract.query.filter(
            Contract.id == contract_id
        ).filter(
            Contract.user_id == g.user.id
        ).one()
    except (NoResultFound, MultipleResultsFound) as e:
        err = "Failed due to no contract with specified contract_id \"{}\" " \
              "for user with user_id \"{}\".".format(contract_id, g.user.id)
        print_log(err)
        raise InvalidUsage(message=err, status_code=400)

    db.session.remove(contract)
    db.session.commit()

    g.res.message = "Removed contract with id \"{}\".".format(contract_id)

    return jsonify(g.res)


# POST /users/login/
db.py 文件源码 项目:tuning-box 作者: openstack 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def one_or_none(self):
        ret = list(self)
        l = len(ret)
        if l == 1:
            return ret[0]
        elif l == 0:
            return None
        else:
            raise orm_exc.MultipleResultsFound(
                "Multiple rows were found for one_or_none()")
sqlalchemy.py 文件源码 项目:falcon-api 作者: Opentopic 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def get_object(self, req, resp, path_params, for_update=False, db_session=None):
        """
        :param req: Falcon request
        :type req: falcon.request.Request

        :param resp: Falcon response
        :type resp: falcon.response.Response

        :param path_params: path params extracted from URL path
        :type path_params: dict

        :param for_update: if the object is going to be updated or deleted
        :type for_update: bool

        :param db_session: SQLAlchemy session
        :type db_session: sqlalchemy.orm.session.Session
        """
        query = db_session.query(self.objects_class)
        if for_update:
            query = query.with_for_update()

        for key, value in path_params.items():
            attr = getattr(self.objects_class, key, None)
            query = query.filter(attr == value)

        conditions = dict(req.params)
        if self.PARAM_RELATIONS in conditions:
            conditions.pop(self.PARAM_RELATIONS)
        query = self.filter_by(query, conditions)

        try:
            obj = query.one()
        except NoResultFound:
            raise HTTPNotFound()
        except MultipleResultsFound:
            raise HTTPBadRequest('Multiple results', 'Query params match multiple records')
        return obj
api.py 文件源码 项目:zun 作者: openstack 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def get_container_by_name(self, context, container_name):
        query = model_query(models.Container)
        query = self._add_tenant_filters(context, query)
        query = query.filter_by(name=container_name)
        try:
            return query.one()
        except NoResultFound:
            raise exception.ContainerNotFound(container=container_name)
        except MultipleResultsFound:
            raise exception.Conflict('Multiple containers exist with same '
                                     'name. Please use the container uuid '
                                     'instead.')
api.py 文件源码 项目:zun 作者: openstack 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def _get_resource_provider_by_name(self, context, provider_name):
        query = model_query(models.ResourceProvider)
        query = query.filter_by(name=provider_name)
        try:
            return query.one()
        except NoResultFound:
            raise exception.ResourceProviderNotFound(
                resource_provider=provider_name)
        except MultipleResultsFound:
            raise exception.Conflict('Multiple resource providers exist with '
                                     'same name. Please use the uuid instead.')
api.py 文件源码 项目:zun 作者: openstack 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def get_compute_node_by_hostname(self, context, hostname):
        query = model_query(models.ComputeNode)
        query = query.filter_by(hostname=hostname)
        try:
            return query.one()
        except NoResultFound:
            raise exception.ComputeNodeNotFound(
                compute_node=hostname)
        except MultipleResultsFound:
            raise exception.Conflict('Multiple compute nodes exist with same '
                                     'hostname. Please use the uuid instead.')
api.py 文件源码 项目:zun 作者: openstack 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def get_capsule_by_meta_name(self, context, capsule_name):
        query = model_query(models.Capsule)
        query = self._add_tenant_filters(context, query)
        query = query.filter_by(meta_name=capsule_name)
        try:
            return query.one()
        except NoResultFound:
            raise exception.CapsuleNotFound(capsule=capsule_name)
        except MultipleResultsFound:
            raise exception.Conflict('Multiple capsules exist with same '
                                     'name. Please use the capsule uuid '
                                     'instead.')
bgp_db.py 文件源码 项目:neutron-dynamic-routing 作者: openstack 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def _get_dvr_fip_next_hop(self, context, fip_address):
        try:
            dvr_agent_gw_query = self._get_dvr_fip_agent_gateway_query(
                context)
            fip_fix_port_query = self._get_fip_fixed_port_host_query(
                context, fip_address)
            q = self._join_fip_by_host_binding_to_agent_gateway(
                context,
                fip_fix_port_query.subquery(),
                dvr_agent_gw_query.subquery()).one()
            return q[1]
        except sa_exc.NoResultFound:
            return
        except sa_exc.MultipleResultsFound:
            return
engine.py 文件源码 项目:deb-python-pykmip 作者: openstack 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def _get_object_type(self, unique_identifier):
        try:
            object_type = self._data_session.query(
                objects.ManagedObject._object_type
            ).filter(
                objects.ManagedObject.unique_identifier == unique_identifier
            ).one()[0]
        except exc.NoResultFound as e:
            self._logger.warning(
                "Could not identify object type for object: {0}".format(
                    unique_identifier
                )
            )
            raise exceptions.ItemNotFound(
                "Could not locate object: {0}".format(unique_identifier)
            )
        except exc.MultipleResultsFound as e:
            self._logger.warning(
                "Multiple objects found for ID: {0}".format(
                    unique_identifier
                )
            )
            raise e

        class_type = self._object_map.get(object_type)
        if class_type is None:
            name = object_type.name
            raise exceptions.InvalidField(
                "The {0} object type is not supported.".format(
                    ''.join(
                        [x.capitalize() for x in name.split('_')]
                    )
                )
            )

        return class_type
engine.py 文件源码 项目:deb-python-kmip 作者: openstack 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def _get_object_type(self, unique_identifier):
        try:
            object_type = self._data_session.query(
                objects.ManagedObject._object_type
            ).filter(
                objects.ManagedObject.unique_identifier == unique_identifier
            ).one()[0]
        except exc.NoResultFound as e:
            self._logger.warning(
                "Could not identify object type for object: {0}".format(
                    unique_identifier
                )
            )
            raise exceptions.ItemNotFound(
                "Could not locate object: {0}".format(unique_identifier)
            )
        except exc.MultipleResultsFound as e:
            self._logger.warning(
                "Multiple objects found for ID: {0}".format(
                    unique_identifier
                )
            )
            raise e

        class_type = self._object_map.get(object_type)
        if class_type is None:
            name = object_type.name
            raise exceptions.InvalidField(
                "The {0} object type is not supported.".format(
                    ''.join(
                        [x.capitalize() for x in name.split('_')]
                    )
                )
            )

        return class_type
mechanism_h3c.py 文件源码 项目:neutron_agent 作者: XiaolongHu 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
def _get_agent_by_type_and_host(self, context, agent_type, host):
        query = context.session.query(H3CAgent)
        try:
            agent_db = query.filter_by(agent_type=agent_type,
                                       host=host).one()
            return agent_db
        except exc.NoResultFound:
            raise ext_a.AgentNotFoundByTypeHost(agent_type=agent_type,
                                                host=host)
        except exc.MultipleResultsFound:
            raise ext_a.MultipleAgentFoundByTypeHost(agent_type=agent_type,
                                                     host=host)
init_categories.py 文件源码 项目:OilLibrary 作者: NOAA-ORR-ERD 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def get_categories_by_names(session, top_name, child_names):
    '''
        Get the top level category by name, and a list of child categories
        directly underneath it by their names.

        This is a utility function that serves some common functionality in
        our various categorization functions.  Probably not useful outside
        of this module.
    '''
    try:
        top_category = (session.query(Category)
                        .filter(Category.parent == None)
                        .filter(Category.name == top_name)
                        .one())
    except MultipleResultsFound as ex:
        ex.message = ('Multiple top categories named "{}" found.'
                      .format(top_name))
        ex.args = (ex.message, )

        raise ex
    except NoResultFound:
        ex.message = ('Top category "{}" not found.'.format(top_name))
        ex.args = (ex.message, )

        raise ex

    child_categories = [c for c in top_category.children
                        if c.name in child_names]

    return top_category, child_categories
postgres.py 文件源码 项目:fabric8-analytics-worker 作者: fabric8-analytics 项目源码 文件源码 阅读 46 收藏 0 点赞 0 评论 0
def get_analysis_by_id(analysis_id):
        """Get result of previously scheduled analysis

        :param analysis_id: str, ID of analysis
        :return: analysis result
        """
        try:
            return PostgresBase.session.query(Analysis).\
                                        filter(Analysis.id == analysis_id).\
                                        one()
        except (NoResultFound, MultipleResultsFound):
            raise
        except SQLAlchemyError:
            PostgresBase.session.rollback()
            raise
postgres_base.py 文件源码 项目:fabric8-analytics-worker 作者: fabric8-analytics 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def retrieve(self, flow_name, task_name, task_id):
        if not self.is_connected():
            self.connect()

        try:
            record = PostgresBase.session.query(self.query_table).\
                                          filter_by(worker_id=task_id).\
                                          one()
        except (NoResultFound, MultipleResultsFound):
            raise
        except SQLAlchemyError:
            PostgresBase.session.rollback()
            raise

        assert record.worker == task_name

        task_result = record.task_result
        if not self.is_real_task_result(task_result):
            # we synced results to S3, retrieve them from there
            # We do not care about some specific version, so no time-based collisions possible
            return self.s3.retrieve_task_result(
                record.ecosystem.name,
                record.package.name,
                record.version.identifier,
                task_name
            )

        return task_result
test_finance.py 文件源码 项目:pycroft 作者: agdsn 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def test_0020_get_current_semester(self):
        try:
            get_current_semester()
        except NoResultFound:
            self.fail("No semester found")
        except MultipleResultsFound:
            self.fail("Multiple semesters found")
__init__.py 文件源码 项目:Jackalope 作者: brysontyrrell 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def jamf_webhook(jamf_uuid):
    """The receiver endpoint where ``jamf_uuid`` is the auto-generated UUID for
     and installed Slack channel.

     Inbound webhooks must be in JSON format or a 400 error will be returned.

     If a supported webhook event has been received it will be formatted into
     a Slack message via
     :func:`jackalope.routes.jamfpro.webhooks.webhook_notification` and sent via
     :func:`jackalope.slack.send_notification`.

     :param str jamf_uuid: The generated UUID for the installed Slack channel.

     :raises: SlackChannelLookupError
     :raises: JSONNotProvided

     :returns: HTTP 204 success response.
     """
    try:
        channel = SlackChannel.query.filter_by(jamf_uuid=jamf_uuid).one()
    except (NoResultFound, MultipleResultsFound) as err:
        raise SlackChannelLookupError(err)

    if not flask.request.json:
        raise JSONNotProvided

    message = webhook_notification(flask.request.json)

    if message:
        send_notification(channel.slack_webhook_url, message)

    return '', 204
database.py 文件源码 项目:GridLight-Server 作者: Lunabit 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def user_from_attribute(attr: str, value: str):
    """ Return User instance based on given value, if exists, compared to
    User.attr. Otherwise, raise InvalidRequestError.

    Parameters
    ----------
    attr : str
        Attribute of a user to check for with `value` value.
    value : str
        Alleged value of user attribute `attr`.

    Raises
    ------
    NoResultFound
        If no user exists where `user`.`attr` == `value`.
    MultipleResultsFound
        If more than one user exists where `user`.`attr` == `value`.

    Returns
    -------
    `gridback.models.User`
        An instance of a user where `user`.`attr` == `value`.

    """
    try:
        return User.query.filter_by(**{attr: value}).one()
    except NoResultFound as e:
        print_log(e)
        raise NoResultFound('No matching user with the provided value.')
    except MultipleResultsFound as e:
        print_log(e)
        raise MultipleResultsFound('Multiple users existed with the provided value.')


问题


面经


文章

微信
公众号

扫码关注公众号