FastAPI 到 DynamoDB
connection 生成器将 FastAPI 连接到 Python DynamoDB 项目,配置本地开发环境使两者自动一起启动。
在使用此生成器之前,请确保您具备:
- 一个
py#fast-api项目 - 一个
py#dynamodb项目
- 安装 Nx Console VSCode Plugin 如果您尚未安装
- 在VSCode中打开Nx控制台
- 点击
Generate (UI)在"Common Nx Commands"部分 - 搜索
@aws/nx-plugin - connection - 填写必需参数
- 点击
Generate
pnpm nx g @aws/nx-plugin:connectionyarn nx g @aws/nx-plugin:connectionnpx nx g @aws/nx-plugin:connectionbunx nx g @aws/nx-plugin:connection选择您的 FastAPI 项目作为源,选择您的 DynamoDB 项目作为目标。
| 参数 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| sourceProject 必需 | string | - | 源项目 |
| targetProject 必需 | string | - | 要连接到的目标项目 |
| sourceComponent | string | - | 要从其连接的源组件(组件名称、相对于源项目根目录的路径或生成器 ID)。使用 '.' 显式选择项目作为源。 |
| targetComponent | string | - | 要连接到的目标组件(组件名称、相对于目标项目根目录的路径或生成器 ID)。使用 '.' 显式选择项目作为目标。 |
| preferInstallDependencies | boolean | true | 是否在生成器运行后优先安装依赖项。设置为 false 可在批量运行多个生成器时延迟安装(如果后续生成器需要计算 Nx 项目图,仍会运行安装);在最后统一安装一次。 |
该生成器会更新 FastAPI 的 project.json,从其 dev 目标添加对 DynamoDB 项目的 dev 目标的依赖,并将 DynamoDB 包添加为工作区依赖项。不会修改源文件。
在路由处理器中使用 DynamoDB
Section titled “在路由处理器中使用 DynamoDB”从 DynamoDB 包导入实体类并在路由处理器中使用它们:
from my_scope.my_table.entities.example import ExampleModel
@app.get("/examples")def list_examples(): return list(ExampleModel.scan())要允许 Lambda 函数访问 DynamoDB 表,请在您的基础设施中授予必要的权限。
在表构造上调用 grantReadWriteData。这将授予 Lambda 执行角色所需的 DynamoDB 和 KMS 权限:
import { MyTable } from ':my-scope/common-constructs';
const table = new MyTable(this, 'Table');
const api = new Api(this, 'Api', { integrations: Api.defaultIntegrations(this).build(),});
Object.entries(api.integrations).forEach(([, integration]) => { table.grantReadWriteData(integration.handler);});授予 Lambda 执行角色访问 DynamoDB 表及其 KMS 加密密钥的权限:
module "my_table" { source = "../../common/terraform/src/app/dynamodb/my-table"}
resource "aws_iam_role_policy" "dynamodb_access" { role = module.my_api.lambda_role_name
policy = jsonencode({ Version = "2012-10-17" Statement = [ { Effect = "Allow" Action = [ "dynamodb:GetItem", "dynamodb:PutItem", "dynamodb:UpdateItem", "dynamodb:DeleteItem", "dynamodb:Query", "dynamodb:Scan", "dynamodb:BatchGetItem", "dynamodb:BatchWriteItem", ] Resource = [ module.my_table.table_arn, "${module.my_table.table_arn}/index/*", ] }, { Effect = "Allow" Action = [ "kms:Encrypt", "kms:Decrypt", "kms:ReEncrypt*", "kms:GenerateDataKey*", "kms:DescribeKey" ] Resource = [module.my_table.kms_key_arn] }, ] })}connection 生成器会配置您项目的 dev 目标,使其依赖于 DynamoDB 项目的 dev 目标。当运行 dev 时,DynamoDB Local 将与您的项目一起自动启动。
LOCAL_DEV=true 环境变量会自动设置,因此 is_local() 返回 True,您的 PynamoDB 实体将连接到本地 DynamoDB 实例而不是 AWS。