

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 在 requirements.txt 中管理 Python 依赖项
<a name="best-practices-dependencies"></a>

本主题介绍了在 `requirements.txt` 文件中如何为 Amazon MWAA 环境安装和管理 Python 依赖项。

**Contents**
+ [DAGs 使用 Amazon MWAA CLI 实用工具进行测试](#best-practices-dependencies-cli-utility)
+ [使用 PyPi .org 需求文件格式安装 Python 依赖项](#best-practices-dependencies-different-ways)
  + [选项一：来自 Python 程序包索引的 Python 依赖关系](#best-practices-dependencies-pip-extras)
  + [选项二：Python Wheel（.whl）](#best-practices-dependencies-python-wheels)
    + [在 Amazon S3 存储桶上使用 `plugins.zip` 文件](#best-practices-dependencies-python-wheels-s3)
    + [使用托管在 URL 上的 WHL 文件](#best-practices-dependencies-python-wheels-url)
    + [从 DAG 创建 WHL 文件](#best-practices-dependencies-python-wheels-dag)
  + [选项三：托管在兼容 PyPi /PEP-503 的私有存储库上的 Python 依赖关系](#best-practices-dependencies-custom-auth-url)
+ [在 Amazon MWAA 控制台上启用日志](#best-practices-dependencies-troubleshooting-enable)
+ [在日志控制台上访问 CloudWatch 日志](#best-practices-dependencies-troubleshooting-view)
+ [在 Apache Airflow UI 中访问错误](#best-practices-dependencies-troubleshooting-aa)
  + [登录 Apache Airflow](#airflow-access-and-login)
+ [示例 `requirements.txt` 应用场景](#best-practices-dependencies-ex-mix-match)

## DAGs 使用 Amazon MWAA CLI 实用工具进行测试
<a name="best-practices-dependencies-cli-utility"></a>
+ 命令行界面 (CLI) 实用工具可在本地复制 Amazon MWAA 环境。
+ CLI 在本地构建 Docker 容器镜像，类似于 Amazon MWAA 生产镜像。在部署到 Amazon MWAA 之前，您可以使用它来运行本地 Apache Airflow 环境来开发和 DAGs测试自定义插件和依赖项。
+ 要运行 CLI，请参阅[aws-mwaa-docker-images](https://github.com/aws/amazon-mwaa-docker-images)上的 GitHub。

## 使用 PyPi .org 需求文件格式安装 Python 依赖项
<a name="best-practices-dependencies-different-ways"></a>

以下部分介绍了根据 PyPi .org [需求文件格式](https://pip.pypa.io/en/stable/reference/pip_install/#requirements-file-format)安装 Python 依赖项的不同方法。

### 选项一：来自 Python 程序包索引的 Python 依赖关系
<a name="best-practices-dependencies-pip-extras"></a>

下一节介绍如何在 `requirements.txt` 文件中指定 [Python 程序包索引](https://pypi.org/)中的 Python 依赖项。

------
#### [ Apache Airflow v3 ]

1. **本地测试**。在创建 `requirements.txt` 文件之前，以迭代方式添加其他库以找到程序包及其版本的正确组合。要运行 Amazon MWAA CLI 实用程序，请参阅上的。[aws-mwaa-docker-images](https://github.com/aws/amazon-mwaa-docker-images) GitHub

1. **查看 Apache Airflow 程序包的 Extras**。要访问亚马逊 MWAA 上为 Apache Airflow v3 安装的软件包列表，请参阅网站。[aws-mwaa-docker-images `requirements.txt`](https://github.com/aws/amazon-mwaa-docker-images/blob/main/requirements.txt) GitHub 

1. **添加约束语句**。在文件顶部添加 Apache Airflow v3 环境的约束文件。`requirements.txt`Apache Airflow 约束文件指定了 Apache Airflow 发布时可用的提供程序版本。

    在以下示例中，用环境的版本号替换 *\$1environment-version\$1* 以及用与环境兼容的 Python 版本替换 *\$1Python-version\$1*。

    有关与 Apache Airflow 环境兼容的 Python 版本的信息，请参阅 [Apache Airflow 版本](airflow-versions.md#airflow-versions-official)。

   ```
   --constraint "https://raw.githubusercontent.com/apache/airflow/constraints-{Airflow-version}/constraints-{Python-version}.txt"
   ```

    如果约束文件确定该 `xyz==1.0` 程序包与环境中的其他程序包不兼容，则 `pip3 install` 将无法阻止不兼容的库安装到环境中。如果任何软件包的安装失败，则可以在日志的相应日志流中访问每个 Apache Airflow 组件（调度程序、工作程序和 Web 服务器）的错误日志。 CloudWatch 有关日志类型的更多信息，请参阅 [访问 Amazon 中的 Airflow 日志 CloudWatch](monitoring-airflow.md)。

1. **Apache Airflow 程序包**。添加[程序包 Extras](http://airflow.apache.org/docs/apache-airflow/2.5.1/extra-packages-ref.html)及其版本 (`==`)。这有助于防止在环境中安装同名但版本不同的程序包。

   ```
   apache-airflow[package-extra]==2.5.1
   ```

1. **Python 库**。在 `requirements.txt` 文件中添加程序包名称和版本 (`==`)。这有助于防止自动应用 [PyPi.org](https://pypi.org) 的 future 更新。

   ```
   library == version
   ```  
**Example boto3 和 psycopg2-binary**  

   此示例仅用于演示目的。boto 和 psycopg2-binary 库包含在 Apache Airflow v3 基础版安装中，无需在 `requirements.txt` 文件中指定。

   ```
   boto3==1.17.54
   boto==2.49.0
   botocore==1.20.54
   psycopg2-binary==2.8.6
   ```

   [如果指定的软件包没有版本，则 Amazon MWAA 会安装.org 中最新版本的PyPi软件包。](https://pypi.org)此版本可能与您 `requirements.txt` 中的其他程序包冲突。

------
#### [ Apache Airflow v2 ]

1. **本地测试**。在创建 `requirements.txt` 文件之前，以迭代方式添加其他库以找到程序包及其版本的正确组合。要运行 Amazon MWAA CLI 实用程序，请参阅上的。[aws-mwaa-docker-images](https://github.com/aws/amazon-mwaa-docker-images) GitHub

1. **查看 Apache Airflow 程序包的 Extras**。要访问亚马逊 MWAA 上为 Apache Airflow v2 安装的软件包列表，请访问网站。[aws-mwaa-docker-images `requirements.txt`](https://github.com/aws/amazon-mwaa-docker-images/blob/main/requirements.txt) GitHub 

1. **添加约束语句**。在 `requirements.txt` 文件顶部添加 Apache Airflow v2 环境的约束文件。Apache Airflow 约束文件指定了 Apache Airflow 发布时可用的提供程序版本。

    从 Apache Airflow v2.7.2 开始，要求文件必须包含一条 `--constraint` 语句。如果您未提供约束条件，Amazon MWAA 将为您指定一个约束条件，以确保您的要求中列出的程序包与您正在使用的 Apache Airflow 版本兼容。

   在以下示例中，用环境的版本号替换 *\$1environment-version\$1* 以及用与环境兼容的 Python 版本替换 *\$1Python-version\$1*。

   有关与 Apache Airflow 环境兼容的 Python 版本的信息，请参阅 [Apache Airflow 版本](airflow-versions.md#airflow-versions-official)。

   ```
   --constraint "https://raw.githubusercontent.com/apache/airflow/constraints-{Airflow-version}/constraints-{Python-version}.txt"
   ```

   如果约束文件确定该 `xyz==1.0` 程序包与环境中的其他程序包不兼容，则 `pip3 install` 将无法阻止不兼容的库安装到环境中。如果任何软件包的安装失败，则可以在日志的相应日志流中访问每个 Apache Airflow 组件（调度程序、工作程序和 Web 服务器）的错误日志。CloudWatch 有关日志类型的更多信息，请参阅 [访问 Amazon 中的 Airflow 日志 CloudWatch](monitoring-airflow.md)。

1. **Apache Airflow 程序包**。添加[程序包 Extras](http://airflow.apache.org/docs/apache-airflow/2.5.1/extra-packages-ref.html)及其版本 (`==`)。这有助于防止在环境中安装同名但版本不同的程序包。

   ```
   apache-airflow[package-extra]==2.5.1
   ```

1. **Python 库**。在 `requirements.txt` 文件中添加程序包名称和版本 (`==`)。这有助于防止自动应用 [PyPi.org](https://pypi.org) 的 future 更新。

   ```
   library == version
   ```  
**Example boto3 和 psycopg2-binary**  

   此示例仅用于演示目的。boto 和 psycopg2-binary 库包含在 Apache Airflow v2 基础版安装中，无需在 `requirements.txt` 文件中指定。

   ```
   boto3==1.17.54
   boto==2.49.0
   botocore==1.20.54
   psycopg2-binary==2.8.6
   ```

   [如果指定的软件包没有版本，则 Amazon MWAA 会安装.org 中最新版本的PyPi软件包。](https://pypi.org)此版本可能与您 `requirements.txt` 中的其他程序包冲突。

------

### 选项二：Python Wheel（.whl）
<a name="best-practices-dependencies-python-wheels"></a>

Python Wheel 是一种程序包格式，旨在发布包含已编译构件的库。将 Wheel 程序包作为在 Amazon MWAA 中安装依赖项的方法有几个好处：
+ **安装速度更快** — WHL 文件作为单个 ZIP 文件复制到容器中，然后安装到本地，无需下载每个文件。
+ **减少冲突**-您可以提前确定程序包的版本兼容性。因此，无需 `pip` 以递归方式计算出兼容版本。
+ **更高的弹性** — 对于外部托管的库，下游要求可能会发生变化，从而导致 Amazon MWAA 环境中容器之间的版本不兼容。由于不依赖外部来源来获取依赖项，因此无论每个容器何时实例化，其上每个容器都有相同的库。

我们建议使用以下方法来安装 `requirements.txt` 中来自 Python Wheel 档案 (`.whl`) 的 Python 依赖项。

**Topics**
+ [在 Amazon S3 存储桶上使用 `plugins.zip` 文件](#best-practices-dependencies-python-wheels-s3)
+ [使用托管在 URL 上的 WHL 文件](#best-practices-dependencies-python-wheels-url)
+ [从 DAG 创建 WHL 文件](#best-practices-dependencies-python-wheels-dag)

#### 在 Amazon S3 存储桶上使用 `plugins.zip` 文件
<a name="best-practices-dependencies-python-wheels-s3"></a>

Apache Airflow 调度程序、工作程序和网络服务器（适用于 Apache Airflow v2.2.2 及更高版本）在启动期间在您的环境的托管的 Fargate 容器上搜索自定义插件，网址为。 AWS`/usr/local/airflow/plugins/*`此过程在 Python 依赖项的 Amazon MWAA 的 `pip3 install -r requirements.txt` 和 Apache Airflow 服务启动之前开始。`plugins.zip`文件可用于任何您不想在环境执行期间持续更改的文件，或者您不想向写入用户授予访问权限的任何文件 DAGs。例如，Python 库 Wheel 文件、证书 PEM 文件和配置 YAML 文件。

下一节介绍如何在 Amazon S3 存储桶上安装 `plugins.zip` 文件中的 Wheel。

1. **下载必要的 WHL 文件**您可以使用[https://pip.pypa.io/en/stable/cli/pip_download/](https://pip.pypa.io/en/stable/cli/pip_download/)亚马逊 MWAA [aws-mwaa-docker-images](https://github.com/aws/amazon-mwaa-docker-images)或其他[亚马逊 Linux 2](https://aws.amazon.com/amazon-linux-2) 容器`requirements.txt`上的现有文件来解析和下载必要的 Python 轮子文件。

   ```
   pip3 download -r "$AIRFLOW_HOME/dags/requirements.txt" -d "$AIRFLOW_HOME/plugins"
   cd "$AIRFLOW_HOME/plugins"
   zip "$AIRFLOW_HOME/plugins.zip" *
   ```

1. **在 `requirements.txt` 中指定路径**。使用 [https://pip.pypa.io/en/stable/cli/pip_install/#install-find-links](https://pip.pypa.io/en/stable/cli/pip_install/#install-find-links) 指定位于 requirements.txt 顶部的插件目录，并指示 `pip` 不要使用 [https://pip.pypa.io/en/stable/cli/pip_install/#install-no-index](https://pip.pypa.io/en/stable/cli/pip_install/#install-no-index) 从其他来源安装，如下面的代码所列：

   ```
   --find-links /usr/local/airflow/plugins
   --no-index
   ```  
**Example 在 requirements.txt 中的 wheel**  

   以下示例假设您已将 Wheel 上传到 Amazon S3 存储桶根目录中的 `plugins.zip` 文件中。例如：

   ```
   --find-links /usr/local/airflow/plugins
   --no-index
   
   numpy
   ```

   Amazon MWAA 从 `plugins` 文件夹中提取 `numpy-1.20.1-cp37-cp37m-manylinux1_x86_64.whl` Wheel 并将其安装到环境中。

#### 使用托管在 URL 上的 WHL 文件
<a name="best-practices-dependencies-python-wheels-url"></a>

下一节将介绍如何安装托管在 URL 上的 Wheel。此 URL 必须是可公开访问的，或者可以从您为 Amazon MWAA 环境指定的自定义 Amazon VPC 中访问。
+ **提供 URL**。向 `requirements.txt` 中的 Wheel 提供 URL。  
**Example 公有 URL 上的 Wheel 档案**  

  以下示例从公有站点下载 Wheel。

  ```
  --find-links https://files.pythonhosted.org/packages/
  --no-index
  ```

  Amazon MWAA 从您指定的 URL 中获取 Wheel 并将其安装到环境中。
**注意**  
URLs 无法通过私有 Web 服务器访问 Amazon MWAA v2.2 及更高版本中的安装要求。

#### 从 DAG 创建 WHL 文件
<a name="best-practices-dependencies-python-wheels-dag"></a>

如果私有 Web 服务器使用 Apache Airflow v2.2.2 或更高版本，并且由于环境无法访问外部存储库而无法安装要求，则可以使用以下 DAG 来获取现有的 Amazon MWAA 要求并将其打包到 Amazon S3 上：

```
from airflow import DAG
 from airflow.operators.bash_operator import BashOperator
 from airflow.utils.dates import days_ago
					
 S3_BUCKET = 'my-s3-bucket'
 S3_KEY = 'backup/plugins_whl.zip' 
					
 with DAG(dag_id="create_whl_file", schedule_interval=None, catchup=False, start_date=days_ago(1)) as dag:
 cli_command = BashOperator(
 task_id="bash_command",
 bash_command=f"mkdir /tmp/whls;pip3 download -r /usr/local/airflow/requirements/requirements.txt -d /tmp/whls;zip -j /tmp/plugins.zip /tmp/whls/*;aws s3 cp /tmp/plugins.zip s3://amzn-s3-demo-bucket/{S3_KEY}"
)
```

运行 DAG 后，使用这个新文件作为 Amazon MWAA `plugins.zip`，也可以选择与其他插件一起打包。然后通过在前面添加 `--find-links /usr/local/airflow/plugins` 和 `--no-index`，但不添加 `--constraint` 来更新 `requirements.txt`。

此方法允许您离线使用相同的库。

### 选项三：托管在兼容 PyPi /PEP-503 的私有存储库上的 Python 依赖关系
<a name="best-practices-dependencies-custom-auth-url"></a>

下一节介绍如何安装托管在私有 URL 上且经过身份验证的 Apache Airflow Extra。

1. 将用户名和密码添加为 [Apache Airflow 配置选项](configuring-env-variables.md)。例如：
   + `foo.user` : `YOUR_USER_NAME`
   + `foo.pass` : `YOUR_PASSWORD`

1. 创建 `requirements.txt` 文件 用私有 URL 以及作为 [Apache Airflow 配置选项](configuring-env-variables.md)添加的用户名和密码替换以下示例中的占位符。例如：

   ```
   --index-url https://${AIRFLOW__FOO__USER}:${AIRFLOW__FOO__PASS}@my.privatepypi.com
   ```

1. 将任何其他库添加到 `requirements.txt` 文件中。例如：

   ```
   --index-url https://${AIRFLOW__FOO__USER}:${AIRFLOW__FOO__PASS}@my.privatepypi.com
   my-private-package==1.2.3
   ```

## 在 Amazon MWAA 控制台上启用日志
<a name="best-practices-dependencies-troubleshooting-enable"></a>

您的 Amazon MWAA 环境的[执行角色](mwaa-create-role.md)需要权限才能将日志发送到日志。 CloudWatch 要更新执行角色的权限，请参阅 [Amazon MWAA 执行角色](mwaa-create-role.md)。

您可以启用 `INFO`、`WARNING`、`ERROR` 或 `CRITICAL` 级别的 Apache Airflow 日志。当您选择日志级别时，Amazon MWAA 会发送该级别和所有更高级别的严重性级别的日志。例如，如果您在`INFO`级别启用日志，Amazon MWAA 会向`INFO`日志发送日志`WARNING`、`ERROR`、和`CRITICAL`日志级别。 CloudWatch 我们建议启用 `INFO` 级别的 Apache Airflow 日志，以便计划程序访问为 `requirements.txt` 收到的日志。

![\[此图说明了如何启用 INFO 级别的日志。\]](http://docs.aws.amazon.com/zh_cn/mwaa/latest/userguide/images/mwaa-console-logs-info.png)


## 在日志控制台上访问 CloudWatch 日志
<a name="best-practices-dependencies-troubleshooting-view"></a>

您可以访问调度工作流程并解析 `dags` 文件夹的计划程序的 Apache Airflow 日志。以下步骤介绍如何在 Amazon MWAA 控制台上打开计划程序的日志组，以及如何在日志控制台上访问 Apache Airflow 日志。 CloudWatch 

**访问 `requirements.txt` 的日志**

1. 在 Amazon MWAA 控制台上打开[环境页面](https://console.aws.amazon.com/mwaa/home#/environments)。

1. 选择环境。

1. 在**监控**窗格上选择 **Airflow 计划程序日志组**。

1. 在**日志流**中选择 `requirements_install_ip` 日志。

1. 请参阅 `/usr/local/airflow/.local/bin` 上环境中安装的程序包列表。例如：

   ```
   Collecting appdirs==1.4.4 (from -r /usr/local/airflow/.local/bin (line 1))
   Downloading https://files.pythonhosted.org/packages/3b/00/2344469e2084fb28kjdsfiuyweb47389789vxbmnbjhsdgf5463acd6cf5e3db69324/appdirs-1.4.4-py2.py3-none-any.whl  
   Collecting astroid==2.4.2 (from -r /usr/local/airflow/.local/bin (line 2))
   ```

1. 查看程序包列表以及其中任何程序包在安装过程中是否遇到错误。如果出现问题，您可能会收到类似以下内容的错误：

   ```
   2021-03-05T14:34:42.731-07:00
   No matching distribution found for LibraryName==1.0.0 (from -r /usr/local/airflow/.local/bin (line 4))
   No matching distribution found for LibraryName==1.0.0 (from -r /usr/local/airflow/.local/bin (line 4))
   ```

## 在 Apache Airflow UI 中访问错误
<a name="best-practices-dependencies-troubleshooting-aa"></a>

您可能还需要检查 Apache Airflow UI，以确定错误是否与其他问题有关。在 Amazon MWAA 上使用 Apache Airflow 时，您可能遇到的最常见错误是：

```
Broken DAG: No module named x
```

如果您在 Apache Airflow UI 中发现此错误，则 `requirements.txt` 文件中可能缺少必需的依赖项。

### 登录 Apache Airflow
<a name="airflow-access-and-login"></a>

你需要你的 AWS 账户 内部 AWS Identity and Access Management (IAM) [Apache Airflow 用户界面访问策略：亚马逊 MWAAWeb ServerAccess](access-policies.md#web-ui-access) 权限才能访问你的 Apache Airflow 用户界面。

**要访问 Apache Airflow UI，请执行以下操作**

1. 在 Amazon MWAA 控制台上打开[环境页面](https://console.aws.amazon.com/mwaa/home#/environments)。

1. 选择环境。

1. 选择**打开 Airflow UI**。

## 示例 `requirements.txt` 应用场景
<a name="best-practices-dependencies-ex-mix-match"></a>

您可以在 `requirements.txt` 中混合搭配不同的格式。以下示例使用不同方式的组合来安装 Extras。

**Example PyPi.org 上的额外内容和公共网址**  
除了在公共 URL 上指定软件包（例如 PyPi兼容 PEP 503 的自定义 repo）之外，您还需要使用该`--index-url`选项。 URLs  

```
aws-batch == 0.6
				phoenix-letter >= 0.3
				
				--index-url http://dist.repoze.org/zope2/2.10/simple
				zopelib
```