How to use the boto3.dynamodb.conditions.Attr function in boto3

To help you get started, we’ve selected a few boto3 examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github boto / boto3 / tests / integration / test_dynamodb.py View on Github external
def test_condition_begins_with(self):
        r = self.scan(
            filter_expression=Attr('MyString').begins_with('my'))
        self.assertTrue(r['Items'][0]['MyString'].startswith('my'))
github boto / boto3 / tests / functional / dynamodb / test_stubber_conditions.py View on Github external
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()
github rojopolis / Take-Terraform-to-the-Next-Level / app / lambda / functions / crud_handler / app.py View on Github external
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)))
github aws / aws-dynamodb-encryption-python / src / dynamodb_encryption_sdk / material_providers / store / meta.py View on Github external
: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))
github ReutersMedia / sqs-browser-events / lib / dynamo_sessions.py View on Github external
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)
github chiradeep / dyndb-mutex / dyndbmutex / dyndbmutex.py View on Github external
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
github plecto / motorway / motorway / contrib / amazon_kinesis / ramps.py View on Github external
"""
        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
github wellcometrust / platform / reindexer / complete_reindex / src / complete_reindex.py View on Github external
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}')
github fugue / credstash / credstash.py View on Github external
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())
github AlisProject / serverless-application / src / handlers / me / articles / drafts / index / me_articles_drafts_index.py View on Github external
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']