本文整理匯總了Python中jmespath.search方法的典型用法代碼示例。如果您正苦於以下問題:Python jmespath.search方法的具體用法?Python jmespath.search怎麽用?Python jmespath.search使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類jmespath
的用法示例。
在下文中一共展示了jmespath.search方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: update_saved_search_handler
# 需要導入模塊: import jmespath [as 別名]
# 或者: from jmespath import search [as 別名]
def update_saved_search_handler(request, saved_search_guid):
search = VariantSearch.objects.get(guid=saved_search_guid)
if search.created_by != request.user:
return create_json_response({}, status=403, reason='User does not have permission to edit this search')
request_json = json.loads(request.body)
name = request_json.pop('name', None)
if not name:
return create_json_response({}, status=400, reason='"Name" is required')
search.name = name
search.save()
return create_json_response({
'savedSearchesByGuid': {
saved_search_guid: get_json_for_saved_search(search, request.user)
}
})
示例2: test_multi_dataset_get_es_variants
# 需要導入模塊: import jmespath [as 別名]
# 或者: from jmespath import search [as 別名]
def test_multi_dataset_get_es_variants(self):
search_model = VariantSearch.objects.create(search={'pathogenicity': {
'clinvar': ['pathogenic'],
}})
results_model = VariantSearchResults.objects.create(variant_search=search_model)
results_model.families.set(self.families)
variants, _ = get_es_variants(results_model, num_results=5)
self.assertListEqual(variants, [PARSED_SV_VARIANT] + PARSED_VARIANTS)
path_filter = {'terms': {
'clinvar_clinical_significance': [
'Pathogenic', 'Pathogenic/Likely_pathogenic'
]
}}
self.assertExecutedSearches([
dict(filters=[path_filter], start_index=0, size=5, sort=['xpos'], index=SV_INDEX_NAME),
dict(filters=[path_filter, ALL_INHERITANCE_QUERY], start_index=0, size=5, sort=['xpos'], index=INDEX_NAME),
])
示例3: test_all_samples_any_affected_get_es_variants
# 需要導入模塊: import jmespath [as 別名]
# 或者: from jmespath import search [as 別名]
def test_all_samples_any_affected_get_es_variants(self):
search_model = VariantSearch.objects.create(search={
'annotations': {'frameshift': ['frameshift_variant']}, 'inheritance': {'mode': 'any_affected'},
})
results_model = VariantSearchResults.objects.create(variant_search=search_model)
results_model.families.set(Family.objects.filter(project__guid='R0001_1kg'))
variants, total_results = get_es_variants(results_model, num_results=2)
self.assertListEqual(variants, PARSED_ANY_AFFECTED_VARIANTS)
self.assertEqual(total_results, 5)
self.assertExecutedSearch(filters=[
ANNOTATION_QUERY,
{'bool': {
'should': [
{'terms': {'samples_num_alt_1': ['HG00731', 'NA19675', 'NA20870']}},
{'terms': {'samples_num_alt_2': ['HG00731', 'NA19675', 'NA20870']}},
{'terms': {'samples': ['HG00731', 'NA19675', 'NA20870']}},
]
}}
], sort=['xpos'])
示例4: get_body
# 需要導入模塊: import jmespath [as 別名]
# 或者: from jmespath import search [as 別名]
def get_body(self, field):
""" extract body field with jmespath.
"""
try:
body = self.json
except exceptions.JSONDecodeError:
err_msg = u"Failed to extract body! => body.{}\n".format(field)
err_msg += u"response body: {}\n".format(self.content)
# logger.log_error(err_msg)
raise exceptions.ExtractFailure(err_msg)
if not field:
# extract response body
return body
return jmespath.search(field, body)
示例5: get_data_member
# 需要導入模塊: import jmespath [as 別名]
# 或者: from jmespath import search [as 別名]
def get_data_member(parent, path):
"""
Get a data member from a parent using a JMESPath search query,
loading the parent if required. If the parent cannot be loaded
and no data is present then an exception is raised.
:type parent: ServiceResource
:param parent: The resource instance to which contains data we
are interested in.
:type path: string
:param path: The JMESPath expression to query
:raises ResourceLoadException: When no data is present and the
resource cannot be loaded.
:returns: The queried data or ``None``.
"""
# Ensure the parent has its data loaded, if possible.
if parent.meta.data is None:
if hasattr(parent, 'load'):
parent.load()
else:
raise ResourceLoadException(
'{0} has no load method!'.format(parent.__class__.__name__))
return jmespath.search(path, parent.meta.data)
示例6: _json_path_records
# 需要導入模塊: import jmespath [as 別名]
# 或者: from jmespath import search [as 別名]
def _json_path_records(self, payload):
"""Extract records from the original json payload using a provided JSON path
Args:
payload (dict): The parsed json data
Returns:
list: A list of JSON records extracted via JSON path
"""
# Handle jsonpath extraction of records
LOGGER.debug('Parsing records with JSONPath: %s', self._json_path)
result = jmespath.search(self._json_path, payload)
if not result:
return []
if not isinstance(result, list):
result = [result]
return result
示例7: _parse
# 需要導入模塊: import jmespath [as 別名]
# 或者: from jmespath import search [as 別名]
def _parse(self, data):
"""Parse a syslog string into a dictionary
Matches syslog events with the following format:
timestamp(Month DD HH:MM:SS) host application: message
Example(s):
Jan 10 19:35:33 vagrant-ubuntu-trusty-64 sudo: session opened for root
Jan 10 19:35:13 vagrant-ubuntu-precise-32 ssh[13941]: login for mike
Args:
data (str): Data to be parsed
Returns:
list<tuple>: List of tuples with records and their parsing status
Examples: [({'key': 'value'}, True)]
"""
match = self._regex.search(data)
if not match:
return [(data, False)]
return [(match.groupdict(), True)]
示例8: handle_file_value
# 需要導入模塊: import jmespath [as 別名]
# 或者: from jmespath import search [as 別名]
def handle_file_value(value, working_dir):
components = value.split('|', 3)
if len(components) == 3:
url = components[2]
return FileLoader.get_file(url, working_dir)
elif len(components) == 4:
url = components[2]
pattern = components[3]
file_content = FileLoader.get_yaml_or_json_file(url, working_dir)
try:
return jmespath.search(pattern, file_content)
except JMESPathError as e:
raise CfnSphereException(e)
else:
raise CfnSphereException("Invalid format for |File| macro, it must be |File|<path>[|<pattern>]")
示例9: build_iterator
# 需要導入模塊: import jmespath [as 別名]
# 或者: from jmespath import search [as 別名]
def build_iterator(self, **kwargs) -> List:
results = []
for feed_name, feed in self.feed_name_to_config.items():
r = requests.get(
url=feed.get('url', self.url),
verify=self.verify,
auth=self.auth,
cert=self.cert,
headers=self.headers,
**kwargs
)
try:
r.raise_for_status()
data = r.json()
result = jmespath.search(expression=feed.get('extractor'), data=data)
results.append({feed_name: result})
except ValueError as VE:
raise ValueError(f'Could not parse returned data to Json. \n\nError massage: {VE}')
return results
示例10: process
# 需要導入模塊: import jmespath [as 別名]
# 或者: from jmespath import search [as 別名]
def process(self, resources):
c = local_session(self.manager.session_factory).client('rds')
for r in resources:
param = {
u['property']: u['value'] for u in self.data.get('update')
if r.get(
u['property'],
jmespath.search(
self.conversion_map.get(u['property'], 'None'), r))
!= u['value']}
if not param:
continue
param['ApplyImmediately'] = self.data.get('immediate', False)
param['DBInstanceIdentifier'] = r['DBInstanceIdentifier']
try:
c.modify_db_instance(**param)
except c.exceptions.DBInstanceNotFoundFault:
raise
示例11: process_cluster
# 需要導入模塊: import jmespath [as 別名]
# 或者: from jmespath import search [as 別名]
def process_cluster(self, client, cluster):
try:
config = dict(self.data.get('attributes'))
modify = {}
for k, v in config.items():
if ((k in self.cluster_mapping and
v != jmespath.search(self.cluster_mapping[k], cluster)) or
v != cluster.get('PendingModifiedValues', {}).get(k, cluster.get(k))):
modify[k] = v
if not modify:
return
modify['ClusterIdentifier'] = (cluster.get('PendingModifiedValues', {})
.get('ClusterIdentifier')
or cluster.get('ClusterIdentifier'))
client.modify_cluster(**modify)
except (client.exceptions.ClusterNotFoundFault):
return
except ClientError as e:
self.log.warning(
"Exception trying to modify cluster: %s error: %s",
cluster['ClusterIdentifier'], e)
raise
示例12: validate_healthcheck
# 需要導入模塊: import jmespath [as 別名]
# 或者: from jmespath import search [as 別名]
def validate_healthcheck(self, data):
for procType, healthcheck in data.items():
if healthcheck is None:
continue
for key, value in healthcheck.items():
if value is None:
continue
if key not in ['livenessProbe', 'readinessProbe']:
raise serializers.ValidationError(
"Healthcheck keys must be either livenessProbe or readinessProbe")
try:
jsonschema.validate(value, PROBE_SCHEMA)
except jsonschema.ValidationError as e:
raise serializers.ValidationError(
"could not validate {}: {}".format(value, e.message))
# http://kubernetes.io/docs/api-reference/v1/definitions/#_v1_probe
# liveness only supports successThreshold=1, no other value
# This is not in the schema since readiness supports other values
threshold = jmespath.search('livenessProbe.successThreshold', healthcheck)
if threshold is not None and threshold != 1:
raise serializers.ValidationError(
'livenessProbe successThreshold can only be 1'
)
return data
示例13: _extract_resources
# 需要導入模塊: import jmespath [as 別名]
# 或者: from jmespath import search [as 別名]
def _extract_resources(self, resp, select):
"""
Extracts the resources from the response from the boto client "describe" call
:param resp: Response from boto client
:param select: JMES path to filter returned resources and/or map/select attributes
:return: Selected resources
"""
if select is not None:
expression = select
else:
expression = self._custom_result_paths.get(self._resource_name, self._resource_name)
if expression != "":
resources = jmespath.search(expression, resp)
else:
resources = resp
if resources is None:
resources = []
elif not isinstance(resources, list):
resources = [resources]
return resources
示例14: query_variants_handler
# 需要導入模塊: import jmespath [as 別名]
# 或者: from jmespath import search [as 別名]
def query_variants_handler(request, search_hash):
"""Search variants.
"""
page = int(request.GET.get('page') or 1)
per_page = int(request.GET.get('per_page') or 100)
sort = request.GET.get('sort') or XPOS_SORT_KEY
if sort == PATHOGENICTY_SORT_KEY and request.user.is_staff:
sort = PATHOGENICTY_HGMD_SORT_KEY
try:
results_model = _get_or_create_results_model(search_hash, json.loads(request.body or '{}'), request.user)
except Exception as e:
logger.error(e)
return create_json_response({'error': str(e)}, status=400, reason=str(e))
_check_results_permission(results_model, request.user)
try:
variants, total_results = get_es_variants(results_model, sort=sort, page=page, num_results=per_page)
except InvalidIndexException as e:
logger.error('InvalidIndexException: {}'.format(e))
return create_json_response({'error': str(e)}, status=400, reason=str(e))
except ConnectionTimeout:
return create_json_response({}, status=504, reason='Query Time Out')
response = _process_variants(variants or [], results_model.families.all(), request.user)
response['search'] = _get_search_context(results_model)
response['search']['totalResults'] = total_results
return create_json_response(response)
示例15: _get_or_create_results_model
# 需要導入模塊: import jmespath [as 別名]
# 或者: from jmespath import search [as 別名]
def _get_or_create_results_model(search_hash, search_context, user):
results_model = VariantSearchResults.objects.filter(search_hash=search_hash).first()
if not results_model:
if not search_context:
raise Exception('Invalid search hash: {}'.format(search_hash))
project_families = search_context.get('projectFamilies')
if project_families:
all_families = set()
for project_family in project_families:
all_families.update(project_family['familyGuids'])
families = Family.objects.filter(guid__in=all_families)
elif search_context.get('allProjectFamilies'):
omit_projects = ProjectCategory.objects.get(name='Demo').projects.all()
projects = [project for project in get_projects_user_can_view(user) if project not in omit_projects]
families = Family.objects.filter(project__in=projects)
elif search_context.get('projectGuids'):
families = Family.objects.filter(project__guid__in=search_context['projectGuids'])
else:
raise Exception('Invalid search: no projects/ families specified')
search_dict = search_context.get('search', {})
search_model = VariantSearch.objects.filter(search=search_dict).filter(
Q(created_by=user) | Q(name__isnull=False)).first()
if not search_model:
search_model = VariantSearch.objects.create(created_by=user, search=search_dict)
# If a search_context request and results request are dispatched at the same time, its possible the other
# request already created the model
results_model, _ = VariantSearchResults.objects.get_or_create(search_hash=search_hash, variant_search=search_model)
results_model.families.set(families)
return results_model