

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

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

本主題說明如何在 Amazon Managed Workflows for Apache Airflow 環境的 `requirements.txt` 檔案中安裝和管理 Python 相依性。

**Contents**
+ [

## 使用 Amazon MWAA CLI 公用程式測試 DAGs
](#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 Logs 主控台上存取日誌
](#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)

## 使用 Amazon MWAA CLI 公用程式測試 DAGs
<a name="best-practices-dependencies-cli-utility"></a>
+ 命令列界面 (CLI) 公用程式會在本機複寫 Amazon Managed Workflows for Apache Airflow 環境。
+ CLI 會在本機建置類似於 Amazon MWAA 生產映像的 Docker 容器映像。您可以使用它來執行本機 Apache Airflow 環境，以在部署到 Amazon MWAA 之前開發和測試 DAGs、自訂外掛程式和相依性。
+ 若要執行 CLI，請參閱 GitHub 上的 [aws-mwaa-docker-images](https://github.com/aws/amazon-mwaa-docker-images)。

## 使用 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 [套件索引指定 Python](https://pypi.org/) 相依性。

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

1. 在**本機測試**。在建立`requirements.txt`檔案之前，反覆新增其他程式庫，以尋找套件及其版本的正確組合。若要執行 Amazon MWAA CLI 公用程式，請參閱 GitHub 上的 [aws-mwaa-docker-images](https://github.com/aws/amazon-mwaa-docker-images)。

1. **檢閱 Apache Airflow 套件額外項目**。若要存取 Amazon MWAA 上為 Apache Airflow v3 安裝的套件清單，請參閱 GitHub 網站上的 [aws-mwaa-docker-images`requirements.txt`](https://github.com/aws/amazon-mwaa-docker-images/blob/main/requirements.txt)。

1. **新增限制條件陳述式**。在檔案頂端新增 Apache Airflow v3 環境的限制條件`requirements.txt`檔案。Apache Airflow 限制條件檔案會指定 Apache Airflow 發行時可用的提供者版本。

    在下列範例中，將 *\$1environment-version\$1* 取代為您環境的版本編號，並將 *\$1Python-version\$1* 取代為您環境相容的 Python 版本。

    如需有關與 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` 無法防止不相容的程式庫安裝到您的環境。如果任何套件的安裝失敗，您可以在 CloudWatch Logs 的對應日誌串流中存取每個 Apache Airflow 元件 （排程器、工作者和 Web 伺服器） 的錯誤日誌。如需日誌類型的詳細資訊，請參閱 [在 Amazon CloudWatch 中存取 Airflow 日誌](monitoring-airflow.md)。

1. **Apache Airflow 套件**。新增[套件額外項目](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) 未來的重大更新自動套用。

   ```
   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 會從 [PyPi.org](https://pypi.org) 安裝最新版本的套件。此版本可能會與您 中的其他套件衝突`requirements.txt`。

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

1. 在**本機測試**。在建立`requirements.txt`檔案之前，反覆新增其他程式庫，以尋找套件及其版本的正確組合。若要執行 Amazon MWAA CLI 公用程式，請參閱 GitHub 上的 [aws-mwaa-docker-images](https://github.com/aws/amazon-mwaa-docker-images)。

1. **檢閱 Apache Airflow 套件額外項目**。若要存取 Amazon MWAA 上為 Apache Airflow v2 安裝的套件清單，請存取 GitHub 網站上的 [aws-mwaa-docker-images`requirements.txt`](https://github.com/aws/amazon-mwaa-docker-images/blob/main/requirements.txt)。

1. **新增限制條件陳述式**。在檔案頂端新增 Apache Airflow v2 環境的限制條件`requirements.txt`檔案。Apache Airflow 限制條件檔案會指定 Apache Airflow 發行時可用的提供者版本。

    從 Apache Airflow 2.7.2 版開始，您的需求檔案必須包含 `--constraint`陳述式。如果您未提供限制條件，Amazon MWAA 會為您指定一個限制條件，以確保您的需求中列出的套件與您正在使用的 Apache Airflow 版本相容。

   在下列範例中，將 *\$1environment-version\$1* 取代為您環境的版本編號，並將 *\$1Python-version\$1* 取代為您環境相容的 Python 版本。

   如需有關與 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` 無法防止不相容的程式庫安裝到您的環境。如果任何套件的安裝失敗，您可以在 CloudWatch Logs 的對應日誌串流中存取每個 Apache Airflow 元件 （排程器、工作者和 Web 伺服器） 的錯誤日誌。如需日誌類型的詳細資訊，請參閱 [在 Amazon CloudWatch 中存取 Airflow 日誌](monitoring-airflow.md)。

1. **Apache Airflow 套件**。新增[套件額外項目](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) 未來的重大更新自動套用。

   ```
   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 會從 [PyPi.org](https://pypi.org) 安裝最新版本的套件。此版本可能會與您 中的其他套件衝突`requirements.txt`。

------

### 選項二：Python wheel (.whl)
<a name="best-practices-dependencies-python-wheels"></a>

Python wheel 是一種套件格式，旨在使用編譯的成品來運送程式庫。輪子套件做為在 Amazon MWAA 中安裝相依性的方法，有幾個好處：
+ **更快速的安裝** – WHL 檔案會以單一 ZIP 的形式複製到容器，然後在本機安裝，無需下載每個檔案。
+ **較少衝突** – 您可以事先判斷套件的版本相容性。因此， 不需要`pip`遞迴處理相容的版本。
+ **更高的彈性** – 使用外部託管程式庫時，下游需求可能會變更，導致 Amazon MWAA 環境中容器之間的版本不相容。透過不依賴相依性的外部來源， 上的每個容器都有相同的程式庫，無論每個容器何時執行個體化。

我們建議您使用下列方法來從 中的 Python wheel 封存檔 (`.whl`) 安裝 Python 相依性`requirements.txt`。

**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 排程器、工作者和 webserver （適用於 Apache Airflow 2.2.2 版及更新版本） 會在 中為您的環境在 AWS受管 Fargate 容器上啟動期間搜尋自訂外掛程式。 `/usr/local/airflow/plugins/*`此程序會在 Python 相依性和 Apache Airflow 服務啟動`pip3 install -r requirements.txt`的 Amazon MWAA 之前開始。`plugins.zip` 檔案可用於您不想要在環境執行期間持續變更的任何檔案，或者您不想將存取權授予寫入 DAGs的使用者。例如，Python 程式庫 wheel 檔案、憑證 PEM 檔案和組態 YAML 檔案。

下一節說明如何在 Amazon S3 儲存貯體的 `plugins.zip` 檔案中安裝輪子。

1. **下載必要的 WHL 檔案** 您可以[https://pip.pypa.io/en/stable/cli/pip_download/](https://pip.pypa.io/en/stable/cli/pip_download/)與 Amazon MWAA [aws-mwaa-docker-images](https://github.com/aws/amazon-mwaa-docker-images) 或其他 [Amazon Linux 2](https://aws.amazon.com/amazon-linux-2) 容器`requirements.txt`上的現有 搭配使用，以解析和下載必要的 Python wheel 檔案。

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

1. **在 中指定路徑`requirements.txt`**。使用 指定您 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)並指示`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**  

   下列範例假設您已在 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`輪子，並將其安裝在您的環境中。

#### 使用 URL 上託管的 WHL 檔案
<a name="best-practices-dependencies-python-wheels-url"></a>

下一節說明如何安裝託管在 URL 上的滾輪。URL 必須可公開存取，或從您為 Amazon MWAA 環境指定的自訂 Amazon VPC 中存取。
+ **提供 URL**。將 URL 提供給 中的滾輪`requirements.txt`。  
**Example 公有 URL 上的車輪封存**  

  下列範例會從公有網站下載輪子。

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

  Amazon MWAA 會從您指定的 URL 擷取輪子，並將其安裝在您的環境中。
**注意**  
URLs。

#### 從 DAG 建立 WHL 檔案
<a name="best-practices-dependencies-python-wheels-dag"></a>

如果您有使用 Apache Airflow 2.2.2 版或更新版本的私有 Web 伺服器，而且由於您的環境無法存取外部儲存庫，因此無法安裝需求，您可以使用下列 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 之後，請`plugins.zip`選擇性地使用此新檔案做為您的 Amazon MWAA，並與其他外掛程式一起封裝。然後，以 `--find-links /usr/local/airflow/plugins` 和 更新您的`requirements.txt`前綴，`--no-index`而不新增 `--constraint`。

此方法可讓您離線使用相同的程式庫。

### 選項三：託管在私有 PyPi/PEP-503 相容儲存庫上的 Python 相依性
<a name="best-practices-dependencies-custom-auth-url"></a>

下一節說明如何安裝在具有身分驗證的私有 URL 上託管的 Apache Airflow 額外項目。

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 Logs。若要更新執行角色的許可，請參閱 [Amazon MWAA 執行角色](mwaa-create-role.md)。

您可以在 `INFO`、`ERROR`、 或 `CRITICAL`層級啟用 Apache Airflow `WARNING`日誌。當您選擇日誌層級時，Amazon MWAA 會傳送該層級和所有較高嚴重性層級的日誌。例如，如果您在 `INFO`層級啟用日誌，Amazon MWAA 會將`INFO`日誌和 `ERROR`、 `WARNING`和 `CRITICAL`日誌層級傳送至 CloudWatch Logs。我們建議在排程器的 `INFO`層級啟用 Apache Airflow 日誌，以存取 收到的日誌`requirements.txt`。

![\[此影像說明如何在 INFO 層級啟用日誌。\]](http://docs.aws.amazon.com/zh_tw/mwaa/latest/userguide/images/mwaa-console-logs-info.png)


## 在 CloudWatch Logs 主控台上存取日誌
<a name="best-practices-dependencies-troubleshooting-view"></a>

您可以存取排程器的 Apache Airflow 日誌來排程工作流程和剖析`dags`資料夾。下列步驟說明如何在 Amazon MWAA 主控台上開啟排程器的日誌群組，以及在 CloudWatch Logs 主控台上存取 Apache Airflow 日誌。

**存取 的日誌 `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 帳戶 in AWS Identity and Access Management (IAM) 存取 Apache Airflow UI 的[Apache Airflow UI 存取政策：AmazonMWAAWebServerAccess](access-policies.md#web-ui-access)許可。

**存取您的 Apache Airflow UI**

1. 在 Amazon MWAA 主控台上開啟[環境](https://console.aws.amazon.com/mwaa/home#/environments)頁面。

1. 選擇環境。

1. 選擇**開啟氣流使用者介面**。

## 範例`requirements.txt`案例
<a name="best-practices-dependencies-ex-mix-match"></a>

您可以在 中混合和比對不同的格式`requirements.txt`。下列範例使用不同方式的組合來安裝額外項目。

**Example PyPi.org 上的額外項目和公有 URL**  
從 PyPi.org 指定套件時，除了公有 URL 上的套件，例如自訂 PEP 503 相容儲存庫 URLs，您還需要使用 `--index-url`選項。 PyPi.org,   

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