我们从Python开源项目中,提取了以下37个代码示例,用于说明如何使用sqlalchemy.orm.exc.MultipleResultsFound()。
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]
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
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
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" )
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
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
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)
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)
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 ) )
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." )
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
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
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/
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()")
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
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.')
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.')
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.')
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.')
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
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
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)
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
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
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
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")
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
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.')
def push_notify_expired_contracts(expiring_contracts): for contract in expiring_contracts: try: provider_name = Provider.query.filter(Provider.id==Contract.provider_id).one() except (NoResultFound, MultipleResultsFound) as e: err = "No valid provider associated with contract (id={}).".format(contract.id) print_log(err) raise InvalidUsage(message=err, status_code=500) res = client.send(contract.user.phone_id, "Your contract with \"{}\" is expiring soon!".format(provider_name)) if res.errors: print_log(res.errors)
def patch_users_contracts(): contract_id = g.req.data.get('contract_id') try: contract = Contract.query.filter(Contract.id == contract_id).one() except (NoResultFound, MultipleResultsFound) as e: raise InvalidUsage(message="Failed to due to invalid contract ID.") provider_name = g.req.data.get('provider_name') if provider_name: contract.provider_name = str(provider_name) rate = g.req.data.get('rate') if rate: contract.rate = float(rate) expiration = g.req.data.get('expiration') if expiration: contract.expiration=datetime.strptime(expiration, '%m/%d/%y') term = g.req.data.get('term') if term: contract.term = str(term) cancellation = g.req.data.get('cancellation') if cancellation: contract.cancellation = str(cancellation) enrollment = g.req.data.get('enrollment') if enrollment: contract.enrollment = str(enrollment) db.session.add(contract) db.session.commit() g.res.message = "Updated existing contract with id \"{}\".".format(contract.id) return jsonify(g.res) # DELETE /users/contracts/<contract_id>
def post_users_login(): try: user = user_from_attribute('email', g.req.data.get('email')) except NoResultFound: raise InvalidUsage(message="No user exists with the provided e-mail address.") except MultipleResultsFound: raise InvalidUsage(message="Multiple, identical e-mail addresses found.", status_code=500) if not password_matches_user(g.req.data.get('password'), user=user): raise InvalidUsage(message="Password is invalid.") # Ensure that there are never any collisions with user tokens. # Guaranteed with unique constraint for User.token. while True: user.token = generate_user_token() db.session.add(user) try: db.session.commit() break except IntegrityError: print_log("Failed generating user token due to collision, retrying...") g.res.update_data({'user': {'token': user.token}}) g.res.message = "User with id \"{}\" was logged in.".format(user.id) return jsonify(g.res) # POST /users/logout/
def create_seasons(session, start_yr, end_yr): """ Adds Years and calendar and European Seasons records to database. :param session: Transaction session object. :param start_yr: Start of year interval. :param end_yr: End of year interval, inclusive. """ def exists(model, **conditions): return session.query(model).filter_by(**conditions).count() != 0 logger.info("Creating Years between {0} and {1}...".format(start_yr, end_yr)) year_range = range(start_yr, end_yr+1) for yr in year_range: if not exists(Years, yr=yr): session.add(Years(yr=yr)) session.commit() session.flush() logger.info("Creating Seasons...") # insert calendar year season record for year in year_range: try: yr_obj = session.query(Years).filter_by(yr=year).one() except NoResultFound: logger.error("Cannot insert Season record: {} not in database".format(year)) continue except MultipleResultsFound: logger.error("Cannot insert Season record: multiple {} records in database".format(year)) continue if not exists(Seasons, start_year=yr_obj, end_year=yr_obj): logger.info("Creating record for {0} season".format(yr_obj.yr)) season_record = Seasons(start_year=yr_obj, end_year=yr_obj) session.add(season_record) # insert European season record for start, end in zip(year_range[:-1], year_range[1:]): try: start_yr_obj = session.query(Years).filter_by(yr=start).one() end_yr_obj = session.query(Years).filter_by(yr=end).one() except NoResultFound: logger.error("Cannot insert Season record: {} or {} not in database".format(start, end)) continue except MultipleResultsFound: logger.error("Cannot insert Season record: multiple {} or {} records in database".format(start, end)) continue if not exists(Seasons, start_year=start_yr_obj, end_year=end_yr_obj): logger.info("Creating record for {0}-{1} season".format(start_yr_obj.yr, end_yr_obj.yr)) season_record = Seasons(start_year=start_yr_obj, end_year=end_yr_obj) session.add(season_record) session.commit() logger.info("Season records committed to database") logger.info("Season creation complete.")
def get_measurement(measurement_id): # XXX this query is SUPER slow m = RE_MSM_ID.match(measurement_id) if not m: raise BadRequest("Invalid measurement_id") msm_no = int(m.group(1)) q = current_app.db_session.query( Measurement.report_no.label('report_no'), Measurement.frame_off.label('frame_off'), Measurement.frame_size.label('frame_size'), Measurement.intra_off.label('intra_off'), Measurement.intra_size.label('intra_size'), Report.report_no.label('r_report_no'), Report.autoclaved_no.label('r_autoclaved_no'), Autoclaved.filename.label('a_filename'), Autoclaved.autoclaved_no.label('a_autoclaved_no'), ).filter(Measurement.msm_no == msm_no)\ .join(Report, Report.report_no == Measurement.report_no)\ .join(Autoclaved, Autoclaved.autoclaved_no == Report.autoclaved_no) try: msmt = q.one() except exc.MultipleResultsFound: current_app.logger.warning("Duplicate rows for measurement_id: %s" % measurement_id) msmt = q.first() except exc.NoResultFound: # XXX we should actually return a 404 here raise BadRequest("No measurement found") # Usual size of LZ4 frames is 256kb of decompressed text. # Largest size of LZ4 frame was ~55Mb compressed and ~56Mb decompressed. :-/ range_header = "bytes={}-{}".format(msmt.frame_off, msmt.frame_off + msmt.frame_size - 1) r = requests.get(urljoin(current_app.config['AUTOCLAVED_BASE_URL'], msmt.a_filename), headers={"Range": range_header}) r.raise_for_status() blob = r.content if len(blob) != msmt.frame_size: raise RuntimeError('Failed to fetch LZ4 frame', len(blob), msmt.frame_size) blob = lz4framed.decompress(blob)[msmt.intra_off:msmt.intra_off+msmt.intra_size] if len(blob) != msmt.intra_size or blob[:1] != b'{' or blob[-1:] != b'}': raise RuntimeError('Failed to decompress LZ4 frame to measurement.json', len(blob), msmt.intra_size, blob[:1], blob[-1:]) # There is no replacement of `measurement_id` with `msm_no` or anything # else to keep sanity. Maybe it'll happen as part of orchestration update. # Also, blob is not decoded intentionally to save CPU return current_app.response_class( blob, mimetype=current_app.config['JSONIFY_MIMETYPE'] )
def get_category_by_name(session, name): ''' Get the category matching a name. - Category name can be a simple name, or a full path to a category inside the Category hierarchy. - A full path consists of a sequence of category names separated by '->' e.g. 'Refined->Gasoline' ''' full_path = name.split('->') if len(full_path) > 1: # traverse the path try: cat_obj = (session.query(Category) .filter(Category.name == full_path[0]) .filter(Category.parent == None) .one()) for cat_name in full_path[1:]: matching_catlist = [c for c in cat_obj.children if c.name == cat_name] if len(matching_catlist) > 1: raise MultipleResultsFound('One matching child Category ' 'required, found {} categories ' 'matching the name {}' .format(len(matching_catlist), cat_name)) elif len(matching_catlist) == 0: raise NoResultFound('child Category matching the name {} ' 'not found' .format(cat_name)) cat_obj = matching_catlist[0] except Exception: cat_obj = None else: # just a simple name try: cat_obj = (session.query(Category) .filter(Category.name == name).one()) except Exception: cat_obj = None return cat_obj
def __init__(self, app_token: str, timestamp: float, data=None): """ Initialize a request given an app token, a request-sent timestamp, and additional data provided from the caller. App token and timestamp validation will be performed. Parameters ---------- app_token : str Allows ability to validate that request is from a valid caller. timestamp : float When the the original request was sent, used for ensuring requests are recent. data : dict, optional Additional information supplied by the caller. """ if not data: data = {} # App Token provided with the request. if not app_token: raise InvalidRequestError('No app token.') if not validate_app_token(app_token): raise InvalidRequestError('Invalid app token.') self.app_token = app_token # Set request timestamp. timestamp = floor_unix_epoch(timestamp) time_limit = floor_unix_epoch(time.time() - EXPIRATION_SECONDS) if time_limit > timestamp: raise InvalidRequestError('Request expired.') self.timestamp = timestamp # Authentication details. user_token = data.get("user_token") email = data.get("email") if user_token: try: if validate_user_token(user_token): self.user_token = user_token except (NoResultFound, MultipleResultsFound) as e: raise InvalidRequestError('Invalid user token: {}'.\ format(str(e))) try: self.user = user_from_attribute('token', user_token) except (NoResultFound, MultipleResultsFound): self.user = None elif email: if "@" not in email: raise InvalidRequestError('Invalid e-mail address.') self.email = email try: self.user = user_from_attribute('email', email) except (NoResultFound, MultipleResultsFound): self.user = None else: raise InvalidRequestError('No authentication provided.') # Extra data provided with the request. self.data = data