How to use the boto3.dynamodb.conditions.Key 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 AlisProject / serverless-application / tests / handlers / me / articles / like / create / test_me_articles_like_create.py View on Github external
def get_article_liked_user(self, article_id, user_id):
        query_params = {
            'KeyConditionExpression': Key('article_id').eq(article_id) & Key('user_id').eq(user_id)
        }
        article_liked_user_table = self.dynamodb.Table(os.environ['ARTICLE_LIKED_USER_TABLE_NAME'])
        return article_liked_user_table.query(**query_params)['Items'][0]
github AlisProject / serverless-application / tests / handlers / me / articles / drafts / publish_with_header / test_me_articles_drafts_publish_with_header.py View on Github external
response = MeArticlesDraftsPublishWithHeader(params, {}, dynamodb=self.dynamodb,
                                                     elasticsearch=self.elasticsearch).main()

        article_info_after = self.article_info_table.scan()['Items']
        article_history_after = self.article_history_table.scan()['Items']
        article_content_edit_after = self.article_content_edit_table.scan()['Items']

        self.assertEqual(response['statusCode'], 200)

        article_info = self.article_info_table.get_item(Key={'article_id': params['pathParameters']['article_id']})['Item']
        article_content = self.article_content_table.get_item(
            Key={'article_id': params['pathParameters']['article_id']}
        )['Item']
        article_history = self.article_history_table.query(
            KeyConditionExpression=Key('article_id').eq(params['pathParameters']['article_id'])
        )['Items'][-1]
        self.assertEqual(article_info['status'], 'public')
        self.assertEqual(article_info['sort_key'], 1520150552000000)
        self.assertEqual(article_info['published_at'], 1525000000)
        self.assertEqual(article_info['sync_elasticsearch'], 1)
        self.assertEqual(article_info['topic'], 'crypto')
        self.assertEqual(article_info['tags'], ['A', 'B', 'C', 'D', 'E' * 25])
        self.assertEqual(article_info['eye_catch_url'], 'https://' + os.environ['DOMAIN'] + '/test.png')
        self.assertEqual(article_info.get('price'), None)
        self.assertEqual(article_content['title'], article_history['title'])
        self.assertEqual(article_content.get('paid_body'), None)
        self.assertEqual(len(article_info_after) - len(article_info_before), 0)
        self.assertEqual(len(article_history_after) - len(article_history_before), 1)
        self.assertEqual(len(article_content_edit_after) - len(article_content_edit_before), 0)
github bahrmichael / aws-scheduler / scheduler.py View on Github external
def handle(event_ids):
    print(f"Scheduling {event_ids}")
    events = []
    for event_id in event_ids:
        items = table.query(
                KeyConditionExpression=Key('pk').eq(event_id['pk']) & Key('sk').eq(event_id['sk'])
            ).get('Items', [])
        if len(items) == 0:
            print('Event %s doesn\'t exist anymore' % event_id)
            continue
        events.append(items[0])

    schedule_events(events)
github AlisProject / serverless-application / src / handlers / me / articles / purchase / create / me_articles_purchase_create.py View on Github external
def __create_paid_article(self, paid_articles_table, article_info, purchase_transaction, sort_key):
        article_history_table = self.dynamodb.Table(os.environ['ARTICLE_HISTORY_TABLE_NAME'])
        article_histories = article_history_table.query(
            KeyConditionExpression=Key('article_id').eq(self.params['article_id']),
            ScanIndexForward=False
        )['Items']
        history_created_at = None
        # 一番新しい記事historyデータを取得する
        for Item in json.loads(json.dumps(article_histories, cls=DecimalEncoder)):
            if Item.get('price') is not None and Item.get('price') == article_info['price']:
                history_created_at = Item.get('created_at')
                break

        # burnのtransactionが失敗した場合に購入transactionを追跡するためにburn_transaction以外を保存
        paid_article = {
            'article_id': self.params['article_id'],
            'user_id': self.event['requestContext']['authorizer']['claims']['cognito:username'],
            'article_user_id': article_info['user_id'],
            'article_title': article_info['title'],
            'purchase_transaction': purchase_transaction,
github aws-samples / connected-drink-dispenser-workshop / deploy / lambda_functions / api_dispense / dispense.py View on Github external
def read_dispenser(dispenser, table):
    """Read, parse, and return dispenser record"""

    response = table.query(KeyConditionExpression=Key("dispenserId").eq(dispenser))
    # If count is zero, this is a non-existent dispenser
    if response["Count"] == 0:
        return http_response(
            httpHeaders, 200, f"ERROR: Dispenser {dispenser} does not exist"
        )
    else:
        return response["Items"][0]
github awslabs / aws-media-services-application-mapper / api / msam / chalicelib / cache.py View on Github external
def cached_by_service_region(service, region):
    """
    API entry point to retrieve items from the cache under the service and region name.
    """
    try:
        service = unquote(service)
        region = unquote(region)
        ddb_table_name = CONTENT_TABLE_NAME
        ddb_index_name = "ServiceRegionIndex"
        ddb_resource = boto3.resource('dynamodb')
        ddb_table = ddb_resource.Table(ddb_table_name)
        response = ddb_table.query(IndexName=ddb_index_name, KeyConditionExpression=Key('service').eq(service) & Key('region').eq(region))
        items = response["Items"]
        while "LastEvaluatedKey" in response:
            response = ddb_table.query(IndexName=ddb_index_name, KeyConditionExpression=Key('service').eq(service) & Key('region').eq(region), ExclusiveStartKey=response['LastEvaluatedKey'])
            items = items + response["Items"]
        return items
    except ClientError as error:
        print(error)
        return {"message": str(error)}
github gouthambs / Flask-Blogging / flask_blogging / dynamodbstorage.py View on Github external
def _get_post_ids(self, count=10, offset=0, recent=True, tag=None,
                      user_id=None, include_draft=False):
        # include_draft is not supported yet
        kwargs = dict(ProjectionExpression='post_id',
                      ScanIndexForward=not recent)
        if count:
            kwargs['Limit'] = count
        table = self._blog_posts_table
        if user_id:
            kwargs.update(
                dict(IndexName='user_id_index',
                     KeyConditionExpression=Key('user_id').eq(user_id))
            )

        elif tag:
            table = self._tag_posts_table
            norm_tag = self.normalize_tag(tag)
            kwargs.update(
                dict(IndexName='tag_index',
                     KeyConditionExpression=Key('tag').eq(norm_tag))
            )
        else:
            kwargs.update(
                dict(IndexName='post_index',
                     KeyConditionExpression=Key('draft').eq(0))
            )
        if offset and offset > 0:
            kwargs2 = copy.deepcopy(kwargs)
github mlda065 / paragraphiser_bot_aws / {{cookiecutter.directory_name}} / data / lambda / poll / main.py View on Github external
#pp.pprint(table.key_schema)

    response = table.query(
        Select='ALL_ATTRIBUTES',
        Limit=100,
        ConsistentRead=False, # if we miss out by a few milliseconds, we'll get it again in a minute
        KeyConditionExpression=Key('hash').eq(common.hash_key_val) & Key('time').lte(time_until)
    )
    items = response['Items']

    while ('LastEvaluatedKey' in response) and len(response['LastEvaluatedKey'] > 0):
        response = table.query(
            Select='ALL_ATTRIBUTES',
            Limit=100,
            ConsistentRead=False, # if we miss out by a few milliseconds, we'll get it again in a minute
            KeyConditionExpression=Key('hash').eq(common.hash_key_val) & Key('time').lte(time_until), # Key('hash').eq(common.hash_key_val) & 
            ExclusiveStartKey=response['LastEvaluatedKey']
        )
        items.extend(response['Items'])

    return(items)
github aws / lumberyard / dev / Gems / CloudGemPlayerAccount / AWS / lambda-code / ServiceLambda / api / admin_accountSearch.py View on Github external
def get_accounts_by_username(Username):
    response = account_utils.get_account_table().query(
        ConsistentRead=False,
        IndexName='CognitoUsernameIndex',
        KeyConditionExpression=Key('CognitoUsername').eq(Username)
    )

    accounts = []

    for item in response.get('Items', []):
        accounts.append(account_utils.convert_account_from_dynamo_to_admin_model(item))

    populate_identity_providers(accounts)

    return accounts
github PaloAltoNetworks / aws-transit-vpc / lambda / deleteTransitVpnConfigurationLambda.py View on Github external
def getItemFromVpcTable(tableName,vpcId):
    """Returns an Item from Transit VpcTable by querying the table with VpcId key
    """
    try:
        dynamodb = boto3.resource('dynamodb', region_name=region)
        table = dynamodb.Table(tableName)
        response = table.query(KeyConditionExpression=Key('VpcId').eq(vpcId))
        if response['Items']:
            return response['Items'][0]
        else:
            logger.info("No Item matched with VpcId: {}".format(vpcId))
            return False
    except Exception as e:
        logger.error("Error from getItemFromVpcTable, Error: {}".format(str(e)))