# @aws-cdk/aws-lambda-python-alpha 中文文档

规范地址：https://npmcn.com/package/%40aws-cdk/aws-lambda-python-alpha/

版本：2\.275\.0-alpha\.0
npm 元数据更新时间：2026-10-26T19:20:45.918Z
中文译文更新时间：2026-11-07T09:21:13.611Z
软件包许可：Apache-2\.0

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40aws-cdk/aws-lambda-python-alpha
原文对照：https://npmcn.com/package/%40aws-cdk/aws-lambda-python-alpha/?lang=original
项目主页：https://github.com/aws/aws-cdk
源码仓库：https://github.com/aws/aws-cdk

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：460 kB，24 个文件
- 模块格式：CommonJS
- TypeScript 类型：包内自带
- Node.js 要求：\>= 20\.0\.0
- 运行依赖：0 个
- peer 依赖：constructs ^10\.5\.0，aws-cdk-lib ^2\.275\.0
- 首次发布：2021-10-13T18:38:33.682Z
- 最新版本发布：2026-10-26T19:20:45.032Z
- 近 30 天下载量：1014521（2026-10-08 至 2026-11-06，npm 官方下载统计）
- 已发布版本数：380（近 12 个月 64 个）

## 中文简介

Python AWS Lambda 的 CDK 建构库

## 安装

```sh
npm install @aws-cdk/aws-lambda-python-alpha
```

也可以使用：`pnpm add @aws-cdk/aws-lambda-python-alpha`、`yarn add @aws-cdk/aws-lambda-python-alpha`、`bun add @aws-cdk/aws-lambda-python-alpha`

## README

# 亚马逊 Lambda Python 图书馆

* * *

![cdk-constructs: Experimental](https://img.shields.io/badge/cdk--constructs-experimental-important.svg?style=for-the-badge)

> 本单元中更高层次的构件的API是实验性的并正在积极开发中. 在今后任何版本中,它们都须作非背向相容的修改或去除。 这些是 不适用 [语义版本](https://semver.org/) 模型和断开的更改 在发行笔记中宣布. 这意味着虽然你可能使用它们,但可能需要更新 当更新到此软件包的更新版本时,您的源代码.

* * *

这个库为Python Lambda函数提供构造.

要使用此模块, 您需要安装 Docker .

## Python 函数

定义 a `PythonFunction`数字 :

```ts
new python.PythonFunction(this, 'MyFunction', {
  entry: '/path/to/my/function', // required
  runtime: Runtime.PYTHON_3_8, // required
  index: 'my_index.py', // optional, defaults to 'index.py'
  handler: 'my_exported_func', // optional, defaults to 'handler'
});
```

所有其他属性 `lambda.Function` 支持,另见 [AWS Lambda 构建库](https://github.com/aws/aws-cdk/tree/main/packages/aws-cdk-lib/aws-lambda)。 。 。 .

## Python 层

您可以创建基于蟒的羊肉地层 `PythonLayerVersion`如果 `PythonLayerVersion` 检测到 a `requirements.txt` 或者说 `Pipfile` 或者说 `poetry.lock` 页:1 `pyproject.toml` 在进入路径,然后 `PythonLayerVersion` 将会在 层.

定义 a `PythonLayerVersion`数字 :

```ts
new python.PythonLayerVersion(this, 'MyLayer', {
  entry: '/path/to/my/layer', // point this to your library's directory
})
```

一个地层也可以用作一个地层的一部分 `PythonFunction`数字 :

```ts
new python.PythonFunction(this, 'MyFunction', {
  entry: '/path/to/my/function',
  runtime: Runtime.PYTHON_3_8,
  layers: [
    new python.PythonLayerVersion(this, 'MyLayer', {
      entry: '/path/to/my/layer', // point this to your library's directory
    }),
  ],
});
```

## 包装

若为 `requirements.txt`, (中文(简体) ), `Pipfile`, (中文(简体) ), `uv.lock` 或者说 `poetry.lock` 在输入路径中存在,构造将处理安装所有所需的模块 [Lambda 兼容多克容器](https://gallery.ecr.aws/sam/build-python3.13) 根据 `runtime` 而与多克平台基于Lambda功能的目标架构.

Python 捆绑只有在源目录中的文件有变化时才会被再创建并发布. 因此(并作为一项一般最佳做法),强烈建议采用一个锁箱文件 列出所有过渡性依赖及其准确版本。 这将确保当任何依赖版本更新时,捆绑资产被重新创建并上传.

为此,我们建议使用\[`pipenv`\[`uv`或\[`poetry`有锁文件支持.

-   [`pipenv`](https://pipenv-fork.readthedocs.io/en/latest/basics.html#example-pipfile-lock)
-   [`poetry`](https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control)
-   [`uv`](https://docs.astral.sh/uv/concepts/projects/sync/#exporting-the-lockfile)

使用 `Packaging` 类,其中:

1.  根据当前文件推断出包装类型.
2.  如果它看到一个 `Pipfile`, (中文(简体) ), `uv.lock` 或一个 `poetry.lock` 文件,它导出为兼容 `requirements.txt` 带有证书的文件(如果在源文件或捆绑容器中可以提供的话).
3.  使用 `pip` 或者说 `uv`。 。 。 .
4.  将依赖性复制到捆绑在Lambda包上的资产中.

**有要求的Lambda(txt)**

```plaintext
.
├── lambda_function.py # exports a function named 'handler'
├── requirements.txt # has to be present at the entry path
```

**带管子的Lambda**

```plaintext
.
├── lambda_function.py # exports a function named 'handler'
├── Pipfile # has to be present at the entry path
├── Pipfile.lock # your lock file
```

**有诗歌的Lambda 洛克**

```plaintext
.
├── lambda_function.py # exports a function named 'handler'
├── pyproject.toml # your poetry project definition
├── poetry.lock # your poetry lock file has to be present at the entry path
```

**Lambda 有U. 锁**

参考: [https://docs.astral.sh/uv/concepts/projects/layout/ (中文(简体) )](https://docs.astral.sh/uv/concepts/projects/layout/)

```plaintext
.
├── lambda_function.py # exports a function named 'handler'
├── pyproject.toml # your poetry project definition
├── uv.lock # your uv lock file has to be present at the entry path
├── .python-version # this file is ignored, python version is configured via Runtime
```

**不包括源文件**

您可以使用可选的捆绑字符串数组参数排除文件复制 `assetExcludes`数字 :

```ts
new python.PythonFunction(this, 'function', {
  entry: '/path/to/poetry-function',
  runtime: Runtime.PYTHON_3_8,
  bundling: {
    // translates to `rsync --exclude='.venv'`
    assetExcludes: ['.venv'],
  },
});
```

**包括散装**

你可以把散装装进去 `poetry` 使用可选布尔参数 `poetryIncludeHashes`数字 :

```ts
new python.PythonFunction(this, 'function', {
  entry: '/path/to/poetry-function',
  runtime: Runtime.PYTHON_3_8,
  bundling: {
    poetryIncludeHashes: true,
  },
});
```

**不包括 URL 内容**

您可以在 `poetry` 使用可选布尔参数 `poetryWithoutUrls`数字 :

```ts
new python.PythonFunction(this, 'function', {
  entry: '/path/to/poetry-function',
  runtime: Runtime.PYTHON_3_8,
  bundling: {
    poetryWithoutUrls: true,
  },
});
```

## 自定义捆绑

自定义捆绑可以通过在附加的构建参数中通过指向将 URL 索引到私有重置中,或者使用一个完全自定义的多克图像来捆绑依赖关系来实现. 目前支持的建设参数有:

-   `PIP_INDEX_URL`
-   `PIP_EXTRA_INDEX_URL`
-   `HTTPS_PROXY`

提及 PyPI 索引的捆绑附加构建参数可以指定为:

```ts
const entry = '/path/to/function';
const image = DockerImage.fromBuild(entry);

new python.PythonFunction(this, 'function', {
  entry,
  runtime: Runtime.PYTHON_3_8,
  bundling: {
    buildArgs: { PIP_INDEX_URL: "https://your.index.url/simple/", PIP_EXTRA_INDEX_URL: "https://your.extra-index.url/simple/" },
  },
});
```

如果使用自定义的 Docker 图像来捆绑,则依赖性将安装在 `pip`, (中文(简体) ), `pipenv` 或者说 `poetry` 使用 `Packaging` 课。 与函数在同一目录中的不同的捆绑多克图像可以指定为:

```ts
const entry = '/path/to/function';
const image = DockerImage.fromBuild(entry);

new python.PythonFunction(this, 'function', {
 entry,
 runtime: Runtime.PYTHON_3_8,
 bundling: { image },
});
```

您可以设置额外的 Docker 选项来配置构建环境 :

```ts
const entry = '/path/to/function';

new python.PythonFunction(this, 'function', {
 entry,
 runtime: Runtime.PYTHON_3_8,
 bundling: {
   network: 'host',
   securityOpt: 'no-new-privileges',
   user: 'user:group',
   volumesFrom: ['777f7dc92da7'],
   volumes: [{ hostPath: '/host-path', containerPath: '/container-path' }],
 },
});
```

## 自定义装入密码

要使用密码Artifact PyPI repo,请输入 `PIP_INDEX_URL` 用于捆绑函数的可定制(在构建环境中需要AWS CLI):

```ts
import { execSync } from 'child_process';

const entry = '/path/to/function';
const image = DockerImage.fromBuild(entry);

const domain = 'my-domain';
const domainOwner = '111122223333';
const repoName = 'my_repo';
const region = 'us-east-1';
const codeArtifactAuthToken = execSync(`aws codeartifact get-authorization-token --domain ${domain} --domain-owner ${domainOwner} --query authorizationToken --output text`).toString().trim();

const indexUrl = `https://aws:${codeArtifactAuthToken}@${domain}-${domainOwner}.d.codeartifact.${region}.amazonaws.com/pypi/${repoName}/simple/`;

new python.PythonFunction(this, 'function', {
  entry,
  runtime: Runtime.PYTHON_3_8,
  bundling: {
    environment: { PIP_INDEX_URL: indexUrl },
  },
});
```

索引URL或令牌只在捆绑时使用,因此不包含在最终资产中. 只设置环境变量 `PIP_INDEX_URL` 或者说 `PIP_EXTRA_INDEX_URL` 应当努力访问私人 Python 寄存器 `pip`, (中文(简体) ), `pipenv` 财务报告和审定财务报表 `poetry` 基础依赖.

如果您还想要使用代码 Artifact repo 来构建用于捆绑的 Docker 图像, 请使用 `buildArgs`然而,请注意,设置用于捆绑的自定义构建参数会迫使基部捆绑图像每次被重建(即跳过多克缓存). 构建参数可定制为:

```ts
import { execSync } from 'child_process';

const entry = '/path/to/function';
const image = DockerImage.fromBuild(entry);

const domain = 'my-domain';
const domainOwner = '111122223333';
const repoName = 'my_repo';
const region = 'us-east-1';
const codeArtifactAuthToken = execSync(`aws codeartifact get-authorization-token --domain ${domain} --domain-owner ${domainOwner} --query authorizationToken --output text`).toString().trim();

const indexUrl = `https://aws:${codeArtifactAuthToken}@${domain}-${domainOwner}.d.codeartifact.${region}.amazonaws.com/pypi/${repoName}/simple/`;

new python.PythonFunction(this, 'function', {
  entry,
  runtime: Runtime.PYTHON_3_8,
  bundling: {
    buildArgs: { PIP_INDEX_URL: indexUrl },
  },
});
```

## 命令钩子

通过指定 `commandHooks` 道具 :

```ts
const entry = '/path/to/function';
new python.PythonFunction(this, 'function', {
  entry,
  runtime: Runtime.PYTHON_3_8,
  bundling: {
    commandHooks: {
      // run tests
      beforeBundling(inputDir: string): string[] {
        return ['pytest'];
      },
      afterBundling(inputDir: string): string[] {
        return ['pylint'];
      },
      // ...
    },
  },
});
```

现提供以下钩子:

-   `beforeBundling`: 在所有捆绑命令之前运行
-   `afterBundling`: 在所有捆绑命令后运行

它们都接收包含依赖文件的目录( Q)`inputDir`)和 捆绑资产将输出的目录( e)`outputDir`) (中文(简体) ). 他们必须回来 要运行的一系列命令。 命令与 `&&`。 。 。 .

命令将在捆绑发生的环境中运行: 用于多克捆绑的容器或用于本地捆绑的主机OS上.

## 基于 Docker 在复杂的 Docker 配置中捆绑

默认情况下,基于多克的捆绑的输入和输出是通过绑定挂载处理的. 在这样不起作用的情况下,比如多克-in-Docker设置,或者在使用远程多克套接字时,您可以配置一个替代但较慢的变体,在这些情况中同样有效.

```ts
const entry = '/path/to/function';

new python.PythonFunction(this, 'function', {
  entry,
  runtime: Runtime.PYTHON_3_8,
  bundling: {
    bundlingFileAccess: BundlingFileAccess.VOLUME_COPY,
  },
});
```

## 解决问题

### 容器文件: 没有此类文件或目录

如果你在Mac上,请使用 [芬奇,你好吗](https://github.com/runfinch/finch) 代替 Docker, 并看到一个错误 像这样:

```txt
lstat /private/var/folders/zx/d5wln9n10sn0tcj1v9798f1c0000gr/T/jsii-kernel-9VYgrO/node_modules/@aws-cdk/aws-lambda-python-alpha/lib/Containerfile: no such file or directory
```

这说明你的临时目录 还没有被映射到芬奇VM中 添加以下内容到 `~/.finch/finch.yaml`数字 :

```yaml
additional_directories:
  - path: /private/var/folders/
  - path: /var/folders/
```

然后通过运行重新启动 Finch VM `finch vm stop && finch vm start`。 。 。 .

## 常见问题

### @aws-cdk/aws-lambda-python-alpha 是什么？

Python AWS Lambda 的 CDK 建构库

### 如何安装 @aws-cdk/aws-lambda-python-alpha？

在项目目录运行 npm install @aws-cdk/aws-lambda-python-alpha，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：constructs（^10\.5\.0）、aws-cdk-lib（^2\.275\.0）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### @aws-cdk/aws-lambda-python-alpha 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @aws-cdk/aws-lambda-python-alpha 支持 ESM 还是 CommonJS？

以 CommonJS 形式发布，可以直接 require\(\)；在 ES Module 项目中也可以用 import 引入（Node\.js 会把 module\.exports 作为默认导出）。

### @aws-cdk/aws-lambda-python-alpha 需要什么版本的 Node\.js？

package\.json 的 engines 字段要求 Node\.js \>= 20\.0\.0。版本不符时 npm 默认只给出警告，开启 engine-strict 后会拒绝安装。

### @aws-cdk/aws-lambda-python-alpha 可以商用吗？

@aws-cdk/aws-lambda-python-alpha 使用 Apache-2\.0 许可。宽松许可：允许商业使用、修改和再分发，并附带明确的专利授权；分发时需保留许可与 NOTICE 文件，修改过的文件要注明改动。以上为概括，不构成法律意见，请以许可原文为准。

### @aws-cdk/aws-lambda-python-alpha 的下载量有多少？

根据 npm 官方下载统计，@aws-cdk/aws-lambda-python-alpha 在 2026/10/08 – 2026/11/06 这 30 天内被下载 1,014,521 次，日均约 33,817 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @aws-cdk/aws-lambda-python-alpha 还在维护吗？

最新版本 2\.275\.0-alpha\.0 发布于 2026/10/27（12 天前）；至今共发布 380 个版本，其中过去 12 个月发布了 64 个；首次发布于 2021/10/14。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

