> ## Documentation Index
> Fetch the complete documentation index at: https://docs.squarecloud.app/llms.txt
> Use this file to discover all available pages before exploring further.

# 环境变量

> 使用 client.apps.envs 读取、添加、替换和删除应用的环境变量。

环境变量位于 `client.apps.envs` 上。每个方法都以应用 ID 作为第一个参数，并以普通的 `dict[str, str]` 返回应用的变量。

<Note>
  静态应用没有环境变量：每个方法都会返回 400 `STATIC_APP_ENV_NOT_SUPPORTED`。更改会在下一次[重启](/zh/sdks/py/managing_application#启动停止和重启)时生效。
</Note>

## 读取变量

```python theme={"system"}
envs = client.apps.envs.get(app_id)

print(envs.get("NODE_ENV"))
```

## 添加或更新变量

`envs.set(app_id, envs)` 添加给定的键，并覆盖已存在的键。其他变量保持不变。它返回更改后的所有变量。

```python theme={"system"}
envs = client.apps.envs.set(app_id, {
    "NODE_ENV": "production",
    "LOG_LEVEL": "info",
})
```

## 替换所有变量

`envs.replace(app_id, envs)` 用给定的集合替换**所有**变量。不在该字典中的键会被删除。`{}` 会清空所有变量。

```python theme={"system"}
client.apps.envs.replace(app_id, {"NODE_ENV": "production"})
```

## 删除变量

`envs.delete(app_id, keys)` 删除给定的键，并返回剩余的变量。`keys` 是一个列表（任何字符串可迭代对象）或单个键。

```python theme={"system"}
remaining = client.apps.envs.delete(app_id, ["LOG_LEVEL"])

# A single key also works
remaining = client.apps.envs.delete(app_id, "LOG_LEVEL")
```

## 限制和错误

| 状态  | 代码                             | 触发条件                         |
| --- | ------------------------------ | ---------------------------- |
| 400 | `STATIC_APP_ENV_NOT_SUPPORTED` | 该应用是静态应用                     |
| 400 | `INVALID_ENV_CONTENT`          | 变量不是有效的对象（对于 `delete`，则是空列表） |
| 400 | `TOO_MANY_ENV_VARS`            | 结果将超过 256 个变量                |
| 400 | `ENV_NAME_TOO_LONG`            | 某个键超过 1024 个字符               |
| 400 | `ENV_CONTENT_TOO_LONG`         | 某个值超过 4096 个字符               |
| 400 | `READ_FAILED`                  | 集群无法读取这些变量                   |
