AWS Lambda w/Dynamo DB上的Python UUID(概念)

Y A*_*son 7 python amazon-web-services amazon-dynamodb aws-lambda

这是一个概念问题:

我们希望在AWS Lambda上运行我们的代码时为Dynamo数据库表创建唯一的主键.

如果我们在AWS Lambda上使用内置函数uuid来创建一个发电机数据库数据库的唯一密钥,那么它有可能创建密钥的两倍,如果我们的dynamodb数据库中有例如5-20亿个项目.

我知道,例如,双uuid键的正常应用中的可能性几乎是不可能的.

据我所知,每次uuid运行时,都要确保它不能通过在内存中保存一些先前的值来创建double.

但是我不确定如果拉姆达只是用相同的蟒蛇控制台中运行了以下功能遍地(和保存UUID,以确保其唯一的),或者如果它创建多个单独的控制台实例,并通过运行它们分开(不保存内存uuid).

虽然这是一个概念问题,但这里有一些示例代码:

from __future__ import print_function
from decimal import *
import boto3
import json
from locale import str
import uuid

def my_handler(event, context):
    description = event['description'] 
    spot_id = uuid.uuid4() #Unique identifier for spot 
    dynamodb = boto3.client('dynamodb')
    tablesinfo = "sinfo"
    dynamodb.put_item(
    TableName = tablesinfo, Item = {
      'spot_id':{'S' : str(spot_id)},
      'description': {'S' : description}
      }
    )
    return {'spot_id' : spot_id}
Run Code Online (Sandbox Code Playgroud)

3G *_*oms 4

Amazon AWS 有自己的示例,用于在 Lambda 中使用 Python 创建 UUID 并将其存储在 elasticache 中。Amazon 没有明确表示这每次都会明确创建一个唯一条目,但您可以将其与检查结合起来,以查看生成的 UUID 在插入之前是否已在 DynamoDB 中。检查 UUID 是否已存在的缺点是,这将使用 DynamoDB 表上的一些读取容量,因此从概念上讲,这对您来说是一种成本。

这是来自 AWS 的代码,如果您调整它以适合 DynamoDB,并检查 UUID 是否已在表中创建,那么这将起作用:

来自:Amazon Lambda 文档 - 创建 Lambda 函数示例

from __future__ import print_function
import time
import uuid
import sys
import socket
import elasticache_auto_discovery
from pymemcache.client.hash import HashClient

#elasticache settings
elasticache_config_endpoint = "your-elasticache-cluster-endpoint:port"
nodes = elasticache_auto_discovery.discover(elasticache_config_endpoint)
nodes = map(lambda x: (x[1], int(x[2])), nodes)
memcache_client = HashClient(nodes)

def handler(event, context):
    """
    This function puts into memcache and get from it.
    Memcache is hosted using elasticache
    """

    #Create a random UUID... this will the sample element we add to the cache.
    uuid_inserted = uuid.uuid4().hex
    #Put the UUID to the cache.
    memcache_client.set('uuid', uuid_inserted)
    #Get item (UUID) from the cache.
    uuid_obtained = memcache_client.get('uuid')
    if uuid_obtained == uuid_inserted:
        # this print should go to the CloudWatch Logs and Lambda console.
        print ("Success: Fetched value %s from memcache" %(uuid_inserted))
    else:
        raise Exception("Value is not the same as we put :(. Expected %s got %s" %(uuid_inserted, uuid_obtained))

    return "Fetched value from memcache: " + uuid_obtained
Run Code Online (Sandbox Code Playgroud)