> ## 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.network 读取 Web 应用的边缘分析、错误、请求日志和性能数据，检查 DNS，设置自定义域名以及清除缓存。

`client.apps.network` **仅适用于 Web 应用**。每个方法都以应用 ID 作为第一个参数。

## 时间窗口

`analytics`、`errors`、`logs` 和 `performance` 接受 `start` 和 `end`，每个都是 ISO 8601 字符串或 `datetime`。naive（不带时区的）`datetime` 被视为本地时间，并转换为 UTC。一个窗口最长 **7 天**，且 `start` 会被限制为不早于应用的创建日期。无效的窗口会返回 400 `INVALID_TIME_RANGE`。

```python theme={"system"}
from datetime import UTC, datetime, timedelta

end = datetime.now(UTC)
start = end - timedelta(hours=24)  # last 24 h
```

结果以 5 分钟为单位进行缓存。这四个方法的缓存未命中共享每个账户每 60 秒 20 次请求的限制：超出后返回 429 `RATE_LIMITED`。

## 分析

`network.analytics(app_id, start, end, **filters)` 返回流量总计和细分数据。对于没有流量的窗口返回 `None`。

```python theme={"system"}
analytics = client.apps.network.analytics(app_id, start, end)

if analytics:
    print(analytics["visits"])     # [{'visits', 'requests', 'bytes', 'date'}]
    print(analytics["countries"])  # [{'type': 'BR', 'visits', 'requests', 'bytes'}]
```

细分维度包括 `countries`、`devices`、`os`、`browsers`、`protocols`、`methods`、`paths`、`referers`、`providers`、`ips`、`status_codes`、`bots` 和 `content_types`。每个分组都有 `type`、`visits`、`requests` 和 `bytes`。

### 过滤器

过滤器以关键字参数传入，会缩小每个细分维度的范围。每个过滤器接受其对应细分维度中确切的 `type` 值：

```python theme={"system"}
brazil = client.apps.network.analytics(
    app_id,
    start,
    end,
    country="BR",
    path="/api",
    provider="GOOGLE (15169)",
)
```

| 过滤器                                | 示例                                   |
| ---------------------------------- | ------------------------------------ |
| `country`                          | `"BR"`（两个字母的代码）                      |
| `ip`                               | `"203.0.113.7"`                      |
| `path`                             | `"/api"`（路径前缀）                       |
| `status`                           | `"404"`                              |
| `os`, `browser`, `protocol`, `bot` | 细分维度的 `type`                         |
| `referer`                          | `"Direct"` 表示没有来源                    |
| `provider`                         | `"NAME (ASN)"`，例如 `"GOOGLE (15169)"` |
| `content_type`                     | 细分维度的 `type`                         |

无效的过滤器会返回 400 `INVALID_FILTER`。设置为 `None` 或 `''` 的过滤器不会被发送。

## 错误

`network.errors(app_id, start, end, include_4xx=False)` 返回该窗口内的 5xx 响应，设置 `include_4xx=True`（仅限关键字参数）时还包括 4xx。对于空窗口返回 `None`。

```python theme={"system"}
errors = client.apps.network.errors(app_id, start, end, include_4xx=True)

if errors:
    print(errors["summary"]["total"], errors["summary"]["by_class"])
    print(errors["top_paths"])
```

## 请求日志

`network.logs(app_id, start, end)` 返回单个请求，包含客户端、请求和响应的详细信息。适用于 Pro 和 Enterprise 套餐（否则返回 403 `UPGRADE_REQUIRED`）。

```python theme={"system"}
for log in client.apps.network.logs(app_id, start, end):
    print(log["timestamp"], log["request"]["method"], log["request"]["path"], log["response"]["status"])
```

## 性能

`network.performance(app_id, start, end)` 返回边缘和源站的延迟百分位数（`p50`、`p95`、`p99`，单位为毫秒），按国家、按位置以及最慢的路径分别统计。对于空窗口返回 `None`。适用于 Pro 和 Enterprise 套餐。

```python theme={"system"}
performance = client.apps.network.performance(app_id, start, end)

if performance:
    print(performance["summary"]["edge"]["p95"], performance["summary"]["origin"]["p95"])
```

## DNS

`network.dns(app_id)` 返回你的自定义域名所需的 DNS 记录及其状态。没有自定义域名时返回 400 `NO_CUSTOM_DOMAIN`。

```python theme={"system"}
for record in client.apps.network.dns(app_id):
    print(record["type"], record["name"], record["value"], record["status"])  # type: "txt" | "cname"
```

## 自定义域名

`network.set_domain(app_id, domain)` 绑定一个自定义域名（Standard 及以上套餐）。传入 `"@"` 即可移除。

```python theme={"system"}
client.apps.network.set_domain(app_id, "www.example.com")

# Remove it
client.apps.network.set_domain(app_id, "@")
```

| 状态  | 代码                            | 触发条件                |
| --- | ----------------------------- | ------------------- |
| 400 | `INVALID_DOMAIN`              | 不是有效的域名             |
| 400 | `RESERVED_DOMAIN`             | 属于 Square Cloud 的域名 |
| 403 | `UPGRADE_REQUIRED`            | 该套餐不支持自定义域名         |
| 403 | `LOAD_BALANCER_LIMIT_REACHED` | 已达到套餐在此域名上的应用数量限制   |
| 409 | `DOMAIN_ALREADY_EXISTS`       | 该域名属于另一个账户的应用       |
| 502 | `DNS_FAILED`                  | 边缘服务提供商拒绝了该域名       |

## 清除缓存

`network.purge_cache(app_id)` 清除应用的边缘缓存。每 60 秒最多清除一次（429 `KEEP_CALM`）。

```python theme={"system"}
client.apps.network.purge_cache(app_id)
```

## 分析方法的错误

| 状态  | 代码                                                                                   | 触发条件                                               |
| --- | ------------------------------------------------------------------------------------ | -------------------------------------------------- |
| 400 | `INVALID_TIME_RANGE`                                                                 | `start`/`end` 缺失、格式错误或顺序颠倒                         |
| 400 | `INVALID_FILTER`                                                                     | 某个过滤器不符合其格式（`analytics`）                           |
| 403 | `UPGRADE_REQUIRED`                                                                   | 在 Pro 和 Enterprise 以外的套餐上使用 `logs` 和 `performance` |
| 429 | `RATE_LIMITED`                                                                       | 已达到缓存未命中的共享限制                                      |
| 500 | `UNABLE_TO_FETCH_ANALYTICS`, `UNABLE_TO_FETCH_ERRORS`, `UNABLE_TO_FETCH_PERFORMANCE` | 边缘服务提供商出错                                          |
| 503 | `ANALYTICS_BUSY`                                                                     | 边缘分析繁忙：会自动重试                                       |
