當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。