

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

# 在 uv中使用 建置 Python Lambda 函數 AWS SAM
<a name="building-python-uv"></a>


|  | 
| --- |
| 此功能目前為 的預覽版本 AWS SAM ，可能會有所變更。 | 

使用 AWS Serverless Application Model 命令列界面 (AWS SAM CLI) 搭配 uv，這是一個快速的 Python 套件安裝程式和解析程式，來建置您的 Python AWS Lambda 函數。

**Topics**
+ [先決條件](#building-python-uv-prerequisites)
+ [設定 AWS SAM 搭配 Python Lambda 函數和 使用 uv](#building-python-uv-configure)
+ [範例](#building-python-uv-examples)

## 先決條件
<a name="building-python-uv-prerequisites"></a>

**Python**  
若要安裝 Python，請參閱 [Python 網站上的下載](https://www.python.org/downloads/) *Python*。

**uv**  
需要安裝 [https://docs.astral.sh/uv/](https://docs.astral.sh/uv/)，這是非常快速的 Python AWS SAM CLI套件安裝程式和解析程式。如需安裝說明，請參閱 *uv 文件*中的[安裝](https://docs.astral.sh/uv/getting-started/installation/)。

**選擇加入 AWS SAM CLI Beta 版功能**  
由於此功能處於預覽狀態，您必須使用下列其中一種方法選擇加入：  

1. 使用環境變數：`SAM_CLI_BETA_PYTHON_UV=1`。

1. 將以下內容新增到您的 `samconfig.toml` 檔案：

   ```
   [default.build.parameters]
   beta_features = true
   [default.sync.parameters]
   beta_features = true
   ```

1. 使用支援的 AWS SAM CLI命令時，請使用 `--beta-features`選項。例如：

   ```
   $ sam build --beta-features
   ```

1. 當 提示您選擇加入`y`時 AWS SAM CLI，請選擇選項。以下是範例：

   ```
   $ sam build
   Starting Build use cache
   Build method "python-uv" is a beta feature.
   Please confirm if you would like to proceed
   You can also enable this beta feature with "sam build --beta-features". [y/N]: y
   ```

## 設定 AWS SAM 搭配 Python Lambda 函數和 使用 uv
<a name="building-python-uv-configure"></a>

### 步驟 1：設定您的 AWS SAM 範本
<a name="building-python-uv-configure-template"></a>

使用下列項目設定您的 AWS SAM 範本：
+ **BuildMethod** – `python-uv`。
+ **CodeUri** – 函數程式碼目錄的路徑，其中包含 `pyproject.toml`或 `requirements.txt`。
+ **處理常**式 – 您的函數處理常式 （例如 `app.lambda_handler`)。
+ **執行時間** – Python 執行時間版本 （例如 `python3.12`)。

以下是已設定 AWS SAM 範本的範例：

```
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
...
Resources:
  MyFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: ./my_function
      Handler: app.lambda_handler
      Runtime: python3.12
    Metadata:
      BuildMethod: python-uv
...
```

## 範例
<a name="building-python-uv-examples"></a>

### Hello World 範例
<a name="building-python-uv-examples-hello"></a>

**在此範例中，我們使用 Python 搭配 uv做為套件管理員，建置範例 Hello World 應用程式。**

uv 可以使用 `pyproject.toml`或 `requirements.txt`讀取相依性。如果同時提供兩者， `sam build`將從 `requirements.txt` 讀取相依性。

以下是 Hello World 應用程式的結構：

```
hello-python-uv
├── README.md
├── events
│   └── event.json
├── hello_world
│   ├── __init__.py
│   ├── app.py
│   └── pyproject.toml
├── samconfig.toml
└── template.yaml
```

`pyproject.toml` 檔案：

```
[project]
name = "my-function"
version = "0.1.0"
requires-python = ">=3.12"
dependencies = [
    "requests>=2.31.0",
    "boto3>=1.28.0",
]
```

在我們的 AWS SAM 範本中，我們的 Python 函數定義如下：

```
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
...
Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: hello_world/
      Handler: app.lambda_handler
      Runtime: python3.12
      Architectures:
        - x86_64
    Metadata:
      BuildMethod: python-uv
```

接下來，我們會執行 `sam build`來建置應用程式並準備部署。 AWS SAM CLI 會建立`.aws-sam`目錄，並在其中組織我們的建置成品。我們的函數相依性是使用 安裝uv，並存放在 `.aws-sam/build/HelloWorldFunction/`。

```
hello-python-uv$ sam build
Starting Build use cache
Build method "python-uv" is a beta feature.
Please confirm if you would like to proceed
You can also enable this beta feature with "sam build --beta-features". [y/N]: y

Experimental features are enabled for this session.
Visit the docs page to learn more about the AWS Beta terms https://aws.amazon.com/service-terms/.

Cache is invalid, running build and copying resources for following functions (HelloWorldFunction)
Building codeuri: /Users/.../hello-python-uv/hello_world runtime: python3.12 metadata: {'BuildMethod': 'python-uv'} architecture: x86_64 functions: HelloWorldFunction
Running PythonUvBuilder:UvBuild
Running PythonUvBuilder:CopySource

Build Succeeded

Built Artifacts  : .aws-sam/build
Built Template   : .aws-sam/build/template.yaml

Commands you can use next
=========================
[*] Validate SAM template: sam validate
[*] Invoke Function: sam local invoke
[*] Test Function in the Cloud: sam sync --stack-name {{stack-name}} --watch
[*] Deploy: sam deploy --guided
```

**注意**  
`python-uv` 建置方法會依 `Metadata`區段中的函數設定。範本中的每個函數都可以使用不同的建置方法，可讓您在相同 AWS SAM 範本中混合 uv型函數與 `pip`型函數。如果未指定建置方法，預設`pip`會使用 。