You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用TypeScript CDK部署含外部库的Python Lambda及多Lambda最佳实践

部署依赖外部库的Python Lambda(TypeScript CDK)

处理外部依赖(以requests库为例)

  • 先在Python Lambda的代码目录下创建requirements.txt,明确指定依赖版本,比如:
    requests==2.31.0
    
  • 有两种打包方式可选:
    1. 直接通过PythonFunction自动打包:利用CDK的PythonFunction(来自aws-cdk-lib/aws-lambda-python-alpha模块)的bundling配置,让CDK自动把依赖和代码打包在一起,默认会用Docker模拟Lambda运行环境,避免本地依赖不兼容问题:
      import { PythonFunction } from 'aws-cdk-lib/aws-lambda-python-alpha';
      import { Stack, StackProps } from 'aws-cdk-lib';
      import { Construct } from 'constructs';
      import * as lambda from 'aws-cdk-lib/aws-lambda';
      
      export class MyStack extends Stack {
        constructor(scope: Construct, id: string, props?: StackProps) {
          super(scope, id, props);
      
          new PythonFunction(this, 'RequestHandlerLambda', {
            entry: './lambda-functions/request-handler', // Python代码所在目录
            runtime: lambda.Runtime.PYTHON_3_11,
            bundling: {
              command: [
                'bash', '-c',
                'pip install -r requirements.txt -t /asset-output && cp -au . /asset-output'
              ],
            },
          });
        }
      }
      
    2. 构建共享依赖层:如果多个Lambda都需要用requests这类库,把依赖打包成Layer,复用给所有需要的Lambda,减少重复打包:
      import { PythonLayerVersion } from 'aws-cdk-lib/aws-lambda-python-alpha';
      import * as lambda from 'aws-cdk-lib/aws-lambda';
      
      // 先创建依赖层
      const requestsLayer = new PythonLayerVersion(this, 'RequestsCommonLayer', {
        entry: './layers/common-requests', // 该目录下放置requirements.txt
        compatibleRuntimes: [lambda.Runtime.PYTHON_3_11],
      });
      
      // 给Lambda挂载层
      new PythonFunction(this, 'AnotherLambda', {
        entry: './lambda-functions/another-handler',
        runtime: lambda.Runtime.PYTHON_3_11,
        layers: [requestsLayer],
      });
      

多Lambda的推荐实践与目录结构

目录结构示例

my-cdk-project/
├── bin/
│   └── my-cdk-app.ts       # CDK应用入口,定义要部署的栈
├── lib/
│   ├── stacks/
│   │   ├── api-service-stack.ts    # 存放API接口类Lambda的栈
│   │   └── data-processing-stack.ts # 存放后台数据处理类Lambda的栈
│   └── constructs/
│       └── base-python-lambda.ts # 封装通用配置的自定义Construct,复用Lambda基础设置
├── lambda-functions/
│   ├── api-handlers/
│   │   ├── get-user/
│   │   │   ├── index.py
│   │   │   └── requirements.txt
│   │   └── create-user/
│   │       ├── index.py
│   │       └── requirements.txt
│   └── processing-jobs/
│       ├── data-transform/
│       │   ├── index.py
│       │   └── requirements.txt
│       └── notification-sender/
│           ├── index.py
│           └── requirements.txt
├── layers/
│   └── common-deps/
│       └── requirements.txt # 存放requests、boto3等多Lambda共用的依赖
└── cdk.json

栈的拆分原则

  • 按业务域拆分:比如把API相关的Lambda集中放在ApiServiceStack,数据处理类的放在DataProcessingStack,便于权限管理和资源隔离
  • 按资源关联性拆分:如果多个Lambda需要共享同一个DynamoDB表、S3桶,建议放在同一栈内,减少跨栈引用的复杂度
  • 按部署频率拆分:变更频繁的Lambda(比如API接口)单独放一个栈,稳定的后台任务Lambda放另一个栈,避免不必要的全栈部署

复用Lambda配置

  • 封装自定义Construct:把Python Lambda的通用配置(比如运行时、默认日志级别、超时时间)封装成一个Construct,避免重复写相同代码:
    import { Construct } from 'constructs';
    import { PythonFunction } from 'aws-cdk-lib/aws-lambda-python-alpha';
    import { Runtime } from 'aws-cdk-lib/aws-lambda';
    
    export class BasePythonLambda extends Construct {
      constructor(scope: Construct, id: string, props: { entry: string, layers?: any[] }) {
        super(scope, id);
    
        new PythonFunction(this, 'LambdaFunction', {
          entry: props.entry,
          runtime: Runtime.PYTHON_3_11,
          layers: props.layers,
          environment: {
            LOG_LEVEL: 'INFO',
          },
          timeout: cdk.Duration.seconds(30),
          memorySize: 256,
        });
      }
    }
    
  • 共用依赖层:把多个Lambda都需要的库打包成共享层,减少每个Lambda的包体积,提升部署效率

内容的提问来源于stack exchange,提问作者Some-one

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 03:42:24