通过 Python3 和 Boto3 将 TTL 添加到 DynamoDB 记录

hot*_*oup 5 ttl python-3.x amazon-dynamodb boto3

我有以下 Pyhton3/Boto3 脚本,它连接到 AWS DynamoDB 表并尝试通过循环遍历其所有记录来设置 19 天的 TTL:

#!/usr/bin/env python3
import boto3
import sys
from datetime import datetime, timedelta
from boto3.dynamodb.conditions import Key, Attr

client = boto3.resource('dynamodb')

ttl = 19    # The TTL in number of DAYS

myTable = client.Table('MyTable')

pe = "logId, id, created"
delCount = 0

try:
    response = integrationLogTable.scan(
        ProjectionExpression=pe,
        )
    while 'LastEvaluatedKey' in response:
        response = integrationLogTable.scan(
            ProjectionExpression=pe,
            ExclusiveStartKey=response['LastEvaluatedKey']
            )

        for i in response['Items']:
            # ???

except ClientError as e:
    print(e.response['Error']['Message'])
Run Code Online (Sandbox Code Playgroud)

我正在努力解决如何将 19 天的 TTL 添加到我的所有记录中...有什么想法吗?

Kan*_*yan 4

以下是将 TTL 添加到 DynamoDBTable 的过程,

  1. 将 TTL 添加到 dynamodb 表
  2. 将属性添加到每个记录并保存。

属性格式:

添加 TTL(以秒为单位)。

19天,就是19 24 60*60 => 19天/24小时/60分钟/60秒。

1641600 秒

import time
import sys

if sys.version_info < (3, 0):
    object.ttlattribute = 1641600 + long(time.time())
else:
    # In py3, long is renamed to int
    object.ttlattribute = 1641600 + int(time.time())
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你。查看此链接,了解如何使用 boto 在 DynamoDB 上执行所有操作。

  • 您需要在文档中创建该属性。它没有默认的属性名称。它是在您为该表启用 ttl 时配置的。在 AWS 控制台中单击为该表启用 TTL,它会要求您提供属性名称。 (2认同)