python-3.x - 为什么 AWS SAM 给我随机的 DynamoDB 表名
问题描述
当我使用 SAM 创建我的 Lambda、API 网关和 DynamoDB 表时,它都可以正常工作,直到我到达实际创建的表。它应该被称为“列表”,但是在“列表”这个词之后它给了我一堆随机数字和字母。我想要做的是,当所有 3 个服务都创建后,它们应该相互通信,但是由于我遇到了这个问题,我必须手动将名称添加到我的函数中才能正常工作。
AWSTemplateFormatVersion: '2010-09-09'
Transform: 'AWS::Serverless-2016-10-31'
Resources:
ClickSam:
Type: 'AWS::Serverless::Function'
Properties:
Handler: app.lambda_handler
Runtime: python3.8
CodeUri: Lambda/
MemorySize: 128
Timeout: 3
Environment:
Variables:
TABLE_NAME: !Ref List
REGION_NAME: !Ref AWS::Region
Events:
ClickAPI:
Type: Api
Properties:
Path: /visits
Method: GET
Policies:
- DynamoDBCrudPolicy:
TableName: !Ref List
List:
Type: AWS::Serverless::SimpleTable
Properties:
PrimaryKey:
Name: url
Type: String
---------- 这是我为表创建项目的 Lambda 函数代码。
import boto3
import json
def lambda_handler(event, context):
dynamodb = boto3.client('dynamodb')
response = dynamodb.update_item(
TableName='List',
Key={
'url':{'S': "etc.com"}
},
UpdateExpression='ADD visits :inc',
ExpressionAttributeValues={
':inc': {'N': '1'}
},
ReturnValues="UPDATED_NEW"
)
response = {
'statusCode': 200,
'headers': {
"Content-Type" : "application/json",
"Access-Control-Allow-Origin" : "*",
"Allow" : "GET, OPTIONS, POST",
"Access-Control-Allow-Methods" : "GET, OPTIONS, POST",
"Access-Control-Allow-Headers" : "*"
},
'body': json.dumps(int(response["Attributes"]["visits"]["N"]))
}
return response
解决方案
使用TableName
参数来修复表名(参见AWS::Serverless::SimpleTable)。
Type: AWS::Serverless::SimpleTable
Properties:
TableName: MyTable
AWS::DynamoDB::Table资源的文档:
如果您不指定名称,AWS CloudFormation 会生成一个唯一的物理 ID 并将该 ID 用作表名称。
推荐阅读
- javascript - 将数组传递给Javascript函数只传递第一个元素
- python - ModuleNotFoundError:Spyder 上没有名为“selenium”的模块
- html - div 用最小高度覆盖父 div
- c - 如何使用 OpenMP 在多线程(超过 10 个线程)中打开文件
- python - 类`__init__`,在导入时调用装饰器
- spring-boot - 可以为 azure-active-directory-spring-boot-starter 配置多个身份提供程序吗?
- reactjs - React Hook Form and Material ui 组件-inputRef 不起作用-组件正在更改类型的不受控制的输入
- vb.net - For Loop 没有在我的 get 函数中运行
- reactjs - 使用 Formik、React 验证自定义表单字段
- python - 如何限制 aws lambda 在失败时执行的次数?