Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_condition_begins_with(self):
r = self.scan(
filter_expression=Attr('MyString').begins_with('my'))
self.assertTrue(r['Items'][0]['MyString'].startswith('my'))
def test_table_scan_can_be_stubbed_with_expressions(self):
table = self.resource.Table('mytable')
filter_expr = Attr('myattr').eq('foo') & (
Attr('myattr2').lte('buzz') | Attr('myattr2').gte('fizz')
)
stubber = Stubber(table.meta.client)
stubber.add_response('scan', dict(Items=list()), expected_params=dict(
TableName='mytable',
FilterExpression=filter_expr
))
with stubber:
response = table.scan(FilterExpression=filter_expr)
self.assertEqual(list(), response['Items'])
stubber.assert_no_pending_responses()
if startDate:
filters.append(Attr('Date').gte(str(startDate)))
if endDate:
filters.append(Attr('Date').lte(str(endDate)))
if age:
age_filter = reduce(ior, [Attr('Age').eq(str(x)) for x in age])
filters.append(age_filter)
if gender:
gender_filter = reduce(ior, [Attr('Gender').eq(str(x)) for x in gender])
filters.append(gender_filter)
if race:
race_filter = reduce(ior, [Attr('Race').eq(str(x)) for x in race])
filters.append(race_filter)
if sentiment:
sentiment = sentiment.split(',') if isinstance(sentiment, str) else sentiment
sentiment_filter = reduce(ior, [Attr('Sentiment').eq(str(x)) for x in sentiment])
filters.append(sentiment_filter)
if origin:
origin_filter = reduce(ior, [Attr('Origin').eq(str(x)) for x in origin])
filters.append(origin_filter)
if geo:
# [bottom left coordinates, upper right coordinates]
# 27.449790329784214%2C-142.55859375000003%2C53.592504809039376%2C-32.69531250000001
# Argument comes in as single string
# Need to convert to use offset fields
geo = geo.split(',')
filters.append(Attr('LatitudeOffset').gte(_convert_latitude(geo[0])))
filters.append(Attr('LongitudeOffset').gte(_convert_longitude(geo[1])))
filters.append(Attr('LatitudeOffset').lte( _convert_latitude(geo[2])))
filters.append(Attr('LongitudeOffset').lte(_convert_longitude(geo[3])))
if topic:
filters.append(Attr('Topic').eq(str(topic)))
:raises VersionAlreadyExistsError: if the specified version already exists
"""
item = {
MetaStoreAttributeNames.PARTITION.value: material_name,
MetaStoreAttributeNames.SORT.value: version,
MetaStoreAttributeNames.MATERIAL_TYPE_VERSION.value: MetaStoreValues.MATERIAL_TYPE_VERSION.value,
MetaStoreAttributeNames.ENCRYPTION_ALGORITHM.value: encryption_key.algorithm,
MetaStoreAttributeNames.ENCRYPTION_KEY.value: Binary(encryption_key.key),
MetaStoreAttributeNames.INTEGRITY_ALGORITHM.value: signing_key.algorithm,
MetaStoreAttributeNames.INTEGRITY_KEY.value: Binary(signing_key.key),
}
try:
self._encrypted_table.put_item(
Item=item,
ConditionExpression=(
Attr(MetaStoreAttributeNames.PARTITION.value).not_exists()
& Attr(MetaStoreAttributeNames.SORT.value).not_exists()
),
)
except botocore.exceptions.ClientError as error:
if error.response["Error"]["Code"] == "ConditionalCheckFailedException":
raise VersionAlreadyExistsError('Version already exists: "{}#{}"'.format(material_name, version))
def get_user_messages(user_id,start_t=None,end_t=None,type_filter=None):
q = {'KeyConditionExpression': Key('userId').eq(user_id)}
if start_t is not None and end_t is not None:
q['FilterExpression'] = Attr('created').gte(start_t) & Attr('created').lte(end_t)
elif start_t is not None:
q['FilterExpression'] = Attr('created').gte(start_t)
elif end_t is not None:
q['FilterExpression'] = Attr('created').lte(end_t)
if type_filter is not None:
type_exp = Attr('_type').is_in(type_filter)
if 'FilterExpression' in q:
q['FilterExpression'] = q['FilterExpression'] & type_exp
else:
q['FilterExpression'] = type_exp
return collect_results(get_history_table().query,q)
def clear_lock_item(self, lockname, caller):
try:
self.get_table().put_item(
Item={
'lockname': lockname,
'expire_ts': 0,
'holder': NO_HOLDER
},
ConditionExpression=Attr("holder").eq(caller) | Attr('lockname').not_exists()
)
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'ConditionalCheckFailedException':
logger.warning("clear_lock_item: lockname=" + lockname + ", caller=" + caller +
" release failed")
return False
logger.debug("clear_lock_item: lockname=" + lockname + ", caller=" + caller + " release succeeded")
return True
"""
Atomically update the shard in DynamoDB
:param shard_id:
:return: bool
"""
shard_election_logger.info("Claiming shard %s" % shard_id)
try:
control_record = self.control_table.get_item(Key={'shard_id': shard_id})['Item']
except KeyError:
raise NoItemsReturned()
control_record['worker_id'] = self.worker_id
control_record['heartbeat'] = 0
try:
self.control_table.put_item(Item=control_record,
ConditionExpression=Attr('shard_id').eq(shard_id) & Attr('checkpoint').eq(control_record['checkpoint'])
# ensure that the record was not changed between the get and put.
)
except self.dynamodb_client.exceptions.ConditionalCheckFailedException: # Someone else edited the record
shard_election_logger.debug("Failed to claim %s to %s" % (shard_id, self.worker_id))
return False
return True
def _update_versioned_item(table, item):
print(f'Attempting conditional update to {item}')
table.put_item(
Item=item,
ConditionExpression=Attr('version').not_exists() | Attr('version').lt(
item['version']
)
)
print(f'Successful update to {item}')
key_service,
secret,
digest_method=digest,
)
secrets = dynamodb.Table(table)
data = {
'name': name,
'version': paddedInt(version),
}
if comment:
data['comment'] = comment
data.update(sealed)
return secrets.put_item(Item=data, ConditionExpression=Attr('name').not_exists())
def exec_main_proc(self):
article_info_table = self.dynamodb.Table(os.environ['ARTICLE_INFO_TABLE_NAME'])
user_id = self.event['requestContext']['authorizer']['claims']['cognito:username']
limit = settings.USERS_ARTICLE_INDEX_DEFAULT_LIMIT
if self.params.get('limit'):
limit = int(self.params.get('limit'))
query_params = {
'Limit': limit,
'IndexName': 'user_id-sort_key-index',
'KeyConditionExpression': Key('user_id').eq(user_id),
'FilterExpression': Attr('status').eq('draft'),
'ScanIndexForward': False
}
if self.params.get('article_id') is not None and self.params.get('sort_key') is not None:
LastEvaluatedKey = {
'user_id': user_id,
'article_id': self.params['article_id'],
'sort_key': int(self.params['sort_key'])
}
query_params.update({'ExclusiveStartKey': LastEvaluatedKey})
response = article_info_table.query(**query_params)
items = response['Items']