当前位置: 首页>>代码示例>>Python>>正文


Python conditions.Key方法代码示例

本文整理汇总了Python中boto3.dynamodb.conditions.Key方法的典型用法代码示例。如果您正苦于以下问题:Python conditions.Key方法的具体用法?Python conditions.Key怎么用?Python conditions.Key使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在boto3.dynamodb.conditions的用法示例。


在下文中一共展示了conditions.Key方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: job_progress

# 需要导入模块: from boto3.dynamodb import conditions [as 别名]
# 或者: from boto3.dynamodb.conditions import Key [as 别名]
def job_progress(jobId):
    DYNAMO_TABLE_NAME = os.environ['JobTable']
    DYNAMO_INDEX_NAME = 'id-createdAt-index' 

    logger.info('GET progress for {} from {}'.format(jobId, DYNAMO_TABLE_NAME))
    
    try:
        table = dynamodb_resource.Table(DYNAMO_TABLE_NAME)
        
        response = table.query(IndexName=DYNAMO_INDEX_NAME, KeyConditionExpression=Key('id').eq(jobId))
    
    except ClientError as e:
        logger.info("ClientError from Dynamodb {}".format(e.response['Error']['Message']))
        raise BadRequestError("Dynamodb returned error message '%s'" % e.response['Error']['Message'])
    except Exception as e:
        logger.info("ClientError from Dynamodb {}".format(e.response['Error']['Message']))
        raise ChaliceViewError("Dynamodb returned error message '%s'" % e.response['Error']['Message'])

    print (json.dumps(response, cls=DecimalEncoder))
    # there is no information about this job yet
    if response['Count'] > 0:
        return response['Items'][0]
    else:
        return {} 
开发者ID:aws-samples,项目名称:aws-media-services-vod-automation,代码行数:26,代码来源:app.py

示例2: getMediaConvertJob

# 需要导入模块: from boto3.dynamodb import conditions [as 别名]
# 或者: from boto3.dynamodb.conditions import Key [as 别名]
def getMediaConvertJob(id, JOBTABLE):
    """
    Retrieve a job data structure from dynamodb
    :param id:  id of the job
    :param JOBTABLE: Name of the dynamodb job table for this stack
    """    
    try:
        table = DYNAMO_CLIENT.Table(JOBTABLE)
        response = table.get_item(Key={'id': id}, ConsistentRead=True)
    
    except ClientError as e:
        print(e.response['Error']['Message'])
    else:
        if 'Item' not in response:
            return None
        else:
            item = response['Item']
            print("GetItem succeeded:")
            #print(json.dumps(item, indent=4, cls=DecimalEncoder))
            return item 
开发者ID:aws-samples,项目名称:aws-media-services-vod-automation,代码行数:22,代码来源:event_collector.py

示例3: parse_filters

# 需要导入模块: from boto3.dynamodb import conditions [as 别名]
# 或者: from boto3.dynamodb.conditions import Key [as 别名]
def parse_filters(self, filters, doc_class):
        index_name = None
        filter_expression_list = []
        query_params = {}
        for idx, filter in enumerate(filters):
            prop_name, prop_value = filter.split(':')[3:5]
            if idx == 0:
                prop = doc_class()._base_properties[prop_name]
                index_name = prop.kwargs.get(self.index_field_name, None) or \
                             self.default_index_name.format(prop_name)
                query_params['KeyConditionExpression'] = Key(prop_name).eq(prop_value)
            else:
                filter_expression_list.append(Attr(prop_name).eq(prop_value))
        if len(filter_expression_list) > 1:
            query_params['FilterExpression'] = And(*filter_expression_list)
        elif len(filter_expression_list) == 1:
            query_params['FilterExpression'] = filter_expression_list[0]
        if index_name != '_id':
            query_params['IndexName'] = index_name
        return query_params 
开发者ID:capless,项目名称:kev,代码行数:22,代码来源:db.py

示例4: dynamo_query_multi

# 需要导入模块: from boto3.dynamodb import conditions [as 别名]
# 或者: from boto3.dynamodb.conditions import Key [as 别名]
def dynamo_query_multi(self, key, value_arr):
        '''
        Does a union of multiple queries for a single key and multiple values
        '''
        items = []
        for value in value_arr:
            resp = self._dynamo_table.query(
                ConsistentRead= True,
                KeyConditionExpression=Key(key).eq(value) 
            )   
            logger.debug(resp)
            items += resp["Items"]        
        return(items)

    #########################
    #   SSM Parameter
    ######################### 
开发者ID:aws-samples,项目名称:aws-service-catalog-reference-architectures,代码行数:19,代码来源:__init__.py

示例5: get_alert_record

# 需要导入模块: from boto3.dynamodb import conditions [as 别名]
# 或者: from boto3.dynamodb.conditions import Key [as 别名]
def get_alert_record(self, rule_name, alert_id):
        """Get a single alert record from the alerts table.

        Args:
            rule_name (str): Name of the rule the alert triggered on
            alert_id (str): Alert UUID

        Returns:
            (dict): Dynamo record corresponding to this alert, or None if the alert was not found.
        """
        kwargs = {
            'ConsistentRead': True,
            'KeyConditionExpression': Key('RuleName').eq(rule_name) & Key('AlertID').eq(alert_id)
        }
        items = list(self._paginate(self._table.query, kwargs))
        return items[0] if items else {}

    # ---------- Add/Delete/Update Operations ---------- 
开发者ID:airbnb,项目名称:streamalert,代码行数:20,代码来源:alert_table.py

示例6: mark_as_dispatched

# 需要导入模块: from boto3.dynamodb import conditions [as 别名]
# 或者: from boto3.dynamodb.conditions import Key [as 别名]
def mark_as_dispatched(self, alert):
        """Mark a specific alert as dispatched (in progress).

        Args:
            alert (Alert): Alert instance which has just been sent to the alert processor
        """
        # Update the alerts table with the dispatch time, but only if the alert still exists.
        # (The alert processor could have deleted the alert before this table update finishes).
        self._table.update_item(
            Key=alert.dynamo_key,
            UpdateExpression='SET Attempts = :attempts, Dispatched = :dispatched',
            ExpressionAttributeValues={
                ':attempts': alert.attempts,
                ':dispatched': alert.dispatched.strftime(Alert.DATETIME_FORMAT)
            },
            ConditionExpression='attribute_exists(AlertID)'
        ) 
开发者ID:airbnb,项目名称:streamalert,代码行数:19,代码来源:alert_table.py

示例7: update_ticket

# 需要导入模块: from boto3.dynamodb import conditions [as 别名]
# 或者: from boto3.dynamodb.conditions import Key [as 别名]
def update_ticket(form):
    table = get_tickets_table()
    limit_type = form.limit_type.data
    table.update_item(
        Key={
            "display_id": form.display_id.data,
        },
        AttributeUpdates={
            'limit_type': {
                'Value': limit_type,
                'Action': 'PUT',
            },
            'limit_value': {
                'Value': form.limit_value.data,
                'Action': 'PUT',
            },
    })
    update_limit_value(limit_type) 
开发者ID:Yipit,项目名称:awslimits,代码行数:20,代码来源:support.py

示例8: register_channel

# 需要导入模块: from boto3.dynamodb import conditions [as 别名]
# 或者: from boto3.dynamodb.conditions import Key [as 别名]
def register_channel(self, uaid, channel_id, ttl=None):
        # type: (str, str, int) -> bool
        """Register a channel for a given uaid"""
        # Generate our update expression
        if ttl is None:
            ttl = self._max_ttl
        # Create/Append to list of channel_ids
        self.table.update_item(
            Key={
                'uaid': hasher(uaid),
                'chidmessageid': ' ',
            },
            UpdateExpression='ADD chids :channel_id SET expiry = :expiry',
            ExpressionAttributeValues={
                ":channel_id": set([normalize_id(channel_id)]),
                ":expiry": _expiry(ttl)
            },
        )
        return True 
开发者ID:mozilla-services,项目名称:autopush,代码行数:21,代码来源:db.py

示例9: unregister_channel

# 需要导入模块: from boto3.dynamodb import conditions [as 别名]
# 或者: from boto3.dynamodb.conditions import Key [as 别名]
def unregister_channel(self, uaid, channel_id, **kwargs):
        # type: (str, str, **str) -> bool
        """Remove a channel registration for a given uaid"""
        chid = normalize_id(channel_id)

        response = self.table.update_item(
            Key={
                'uaid': hasher(uaid),
                'chidmessageid': ' ',
            },
            UpdateExpression="DELETE chids :channel_id SET expiry = :expiry",
            ExpressionAttributeValues={
                ":channel_id": set([chid]),
                ":expiry": _expiry(self._max_ttl)
            },
            ReturnValues="UPDATED_OLD",
        )
        chids = response.get('Attributes', {}).get('chids', {})
        if chids:
            try:
                return chid in chids
            except (TypeError, AttributeError):  # pragma: nocover
                pass
        # if, for some reason, there are no chids defined, return False.
        return False 
开发者ID:mozilla-services,项目名称:autopush,代码行数:27,代码来源:db.py

示例10: all_channels

# 需要导入模块: from boto3.dynamodb import conditions [as 别名]
# 或者: from boto3.dynamodb.conditions import Key [as 别名]
def all_channels(self, uaid):
        # type: (str) -> Tuple[bool, Set[str]]
        """Retrieve a list of all channels for a given uaid"""

        # Note: This only returns the chids associated with the UAID.
        # Functions that call store_message() would be required to
        # update that list as well using register_channel()
        result = self.table.get_item(
            Key={
                'uaid': hasher(uuid.UUID(uaid).hex),
                'chidmessageid': ' ',
            },
            ConsistentRead=True
        )
        if result['ResponseMetadata']['HTTPStatusCode'] != 200:
            return False, set([])
        if 'Item' not in result:
            return False, set([])
        return True, result['Item'].get("chids", set([])) 
开发者ID:mozilla-services,项目名称:autopush,代码行数:21,代码来源:db.py

示例11: delete_message

# 需要导入模块: from boto3.dynamodb import conditions [as 别名]
# 或者: from boto3.dynamodb.conditions import Key [as 别名]
def delete_message(self, notification):
        # type: (WebPushNotification) -> bool
        """Deletes a specific message"""
        if notification.update_id:
            try:
                self.table.delete_item(
                    Key={
                        'uaid': hasher(notification.uaid.hex),
                        'chidmessageid': notification.sort_key
                    },
                    Expected={
                        'updateid': {
                            'Exists': True,
                            'Value': notification.update_id
                            }
                    })
            except ClientError:
                return False
        else:
            self.table.delete_item(
                Key={
                    'uaid': hasher(notification.uaid.hex),
                    'chidmessageid': notification.sort_key,
                })
        return True 
开发者ID:mozilla-services,项目名称:autopush,代码行数:27,代码来源:db.py

示例12: drop_user

# 需要导入模块: from boto3.dynamodb import conditions [as 别名]
# 或者: from boto3.dynamodb.conditions import Key [as 别名]
def drop_user(self, uaid):
        # type: (str) -> bool
        """Drops a user record"""
        # The following hack ensures that only uaids that exist and are
        # deleted return true.
        try:
            item = self.table.get_item(
                Key={
                    'uaid': hasher(uaid)
                },
                ConsistentRead=True,
            )
            if 'Item' not in item:
                return False
        except ClientError:  # pragma nocover
            pass
        result = self.table.delete_item(
            Key={'uaid': hasher(uaid)})
        return result['ResponseMetadata']['HTTPStatusCode'] == 200 
开发者ID:mozilla-services,项目名称:autopush,代码行数:21,代码来源:db.py

示例13: update_item

# 需要导入模块: from boto3.dynamodb import conditions [as 别名]
# 或者: from boto3.dynamodb.conditions import Key [as 别名]
def update_item(self, table_name, key_dict, update_dict):
        """
        Update an item.
        PARAMS
        @table_name: name of the table
        @key_dict: dict containing the key name and val eg. {"uuid": item_uuid}
        @update_dict: dict containing the key name and val of
        attributes to be updated
        eg. {"attribute": "processing_status", "value": "completed"}
        """
        dynamodb = self.conn
        table = dynamodb.Table(table_name)
        update_expr = 'SET {} = :val1'.format(update_dict['attribute'])
        response = table.update_item(
            Key=key_dict,
            UpdateExpression=update_expr,
            ExpressionAttributeValues={
                ':val1': update_dict['value']
            }
        )
        if response['ResponseMetadata']['HTTPStatusCode'] == 200:
            return True
        else:
            return False 
开发者ID:santoshghimire,项目名称:boto3-examples,代码行数:26,代码来源:dynamodb.py

示例14: delete_item

# 需要导入模块: from boto3.dynamodb import conditions [as 别名]
# 或者: from boto3.dynamodb.conditions import Key [as 别名]
def delete_item(self, table_name, item_key):
        """
        delete an item
        PARAMS
        @table_name: name of the table
        @item_key: dict containing key and val of sort key
        e.g. {'name': 'uuid', 'value': 'some-uuid-val'}
        """
        dynamodb = self.conn
        table = dynamodb.Table(table_name)
        response = table.delete_item(
            Key={item_key['name']: item_key['value']}
        )
        if response['ResponseMetadata']['HTTPStatusCode'] == 200:
            return True
        else:
            return False 
开发者ID:santoshghimire,项目名称:boto3-examples,代码行数:19,代码来源:dynamodb.py

示例15: get_post_by_id

# 需要导入模块: from boto3.dynamodb import conditions [as 别名]
# 或者: from boto3.dynamodb.conditions import Key [as 别名]
def get_post_by_id(self, post_id):
        try:
            response = self._blog_posts_table.get_item(
                Key={'post_id': post_id}
            )
            item = response.get('Item')
            if item:
                r = item
                r['post_date'] = self._from_timestamp(r['post_date'])
                r['last_modified_date'] = \
                    self._from_timestamp(r['last_modified_date'])
                r["draft"] = bool(r["draft"])
            else:
                r = None
        except Exception as e:
            self._logger.exception(str(e))
            r = None
        return r 
开发者ID:gouthambs,项目名称:Flask-Blogging,代码行数:20,代码来源:dynamodbstorage.py


注:本文中的boto3.dynamodb.conditions.Key方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。