PythonIDE Docs
中文
简体中文

network

原生 HTTP 请求、连接状态和下载。

原生 HTTP 客户端:发起 GET/POST 等请求、判断网络状态、下载文件到本地路径。

边界:适合 REST API 和小文件下载。大文件、后台传输或复杂上传请看系统能力规划;响应体在内存中,超大响应注意内存占用。

#模块概览

说明
导入import network
适合做什么拉取 JSON API、提交表单、检查联网、下载文件
调用时机放在按钮回调或加载任务;不要写在 AppUI body()
推荐顺序is_connected() 提示 → get/post → 检查 response.ok → 解析 json()
蜂窝/低数据is_expensive() / is_constrained() 为真时避免自动下大文件

#快速开始

下面脚本检查网络,请求 GitHub API 并打印仓库名:

python
import network

if not network.is_connected():
    print("当前无网络")
else:
    response = network.get(
        "https://api.github.com/repos/python/cpython",
        timeout=15,
    )
    if response.ok:
        data = response.json()
        print(data["full_name"], "⭐", data["stargazers_count"])
    else:
        print("请求失败:", response.status, response.text[:200])

#AppUI 示例

请求放在按钮回调里,加载、成功、失败都写回界面。

python
import appui
import network

state = appui.State(
    status="未请求",
    network="—",
    detail="点击按钮开始",
)


def refresh_network_info():
    if not network.is_connected():
        state.network = "离线"
        return
    conn = network.connection_type()
    flags = []
    if network.is_expensive():
        flags.append("计费网络")
    if network.is_constrained():
        flags.append("低数据模式")
    suffix = f"({' · '.join(flags)})" if flags else ""
    state.network = f"{conn}{suffix}"


def fetch_repo():
    refresh_network_info()
    if not network.is_connected():
        state.batch_update(status="离线", detail="当前没有可用网络")
        return

    state.status = "请求中..."
    response = network.get(
        "https://api.github.com/repos/python/cpython",
        timeout=15,
    )
    if not response.ok:
        state.batch_update(status="请求失败", detail=str(response.status))
        return

    try:
        data = response.json()
    except Exception as error:
        state.batch_update(status="解析失败", detail=str(error))
        return

    stars = data.get("stargazers_count", "—")
    state.batch_update(
        status="请求成功",
        detail=f"{data.get('full_name', '')} · ⭐ {stars}",
    )


def body():
    return appui.NavigationStack(
        appui.Form([
            appui.Section("网络", [
                appui.LabeledContent("连接", value=state.network),
                appui.LabeledContent("状态", value=state.status),
                appui.Text(state.detail).foreground_color("secondaryLabel"),
            ]),
            appui.Section("操作", [
                appui.Button("获取 CPython 仓库信息", action=fetch_repo)
                .button_style("bordered_prominent"),
            ], footer="需要网络;真机测试最可靠。"),
        ]).navigation_title("网络请求")
    )


appui.run(body, state=state)

#API 参考

#速查

API作用
is_connected()是否有可用网络 → bool
connection_type()wifi / cellular / ethernet / none / other
is_expensive()是否计费网络(蜂窝/热点)
is_constrained()是否低数据模式
get/post/put/delete/patch(...)HTTP 快捷方法 → Response
request(method, url, ...)通用 HTTP 请求
download(url, dest_path)下载文件 → bool

#网络状态

python
import network

if network.is_connected():
    print(network.connection_type())
    if network.is_expensive():
        print("计费网络,避免大流量")
API说明
is_connected()当前能否联网
connection_type()连接类型字符串
is_expensive()蜂窝或热点等
is_constrained()系统低数据模式

#HTTP 请求

request(method, url, headers=None, body=None, json=None, timeout=30) — 通用请求。

快捷方法:getpostputdeletepatch,参数相同。

python
response = network.get("https://httpbin.org/get", timeout=15)
response = network.post(
    "https://httpbin.org/post",
    json={"title": "Hello"},
    headers={"Accept": "application/json"},
    timeout=20,
)

Response 对象:

属性/方法说明
statusHTTP 状态码
ok200–299 时为 True
text响应正文字符串
json()解析 JSON;非 JSON 会抛异常
headers响应头字典
python
if response.ok:
    data = response.json()
else:
    print(response.status, response.text[:200])

#下载

download(url, dest_path, timeout=120) — 下载到本地路径,成功返回 True

python
ok = network.download(
    "https://httpbin.org/json",
    "report.json",
    timeout=30,
)

下载失败返回 False;路径需脚本可写。配合 photossave_video 时,先 download 再传本地路径。


#常见错误

错误写法后果修正
body() 里发请求每次刷新都联网放进按钮回调
不检查 response.ok把错误当成功解析先判断 okjson()
对非 JSON 直接 json()解析异常try/except 或改读 text
蜂窝网络自动下大文件流量浪费检查 is_expensive() 并提示用户

#相关文档

文档用途
photos下载视频后 save_video
weatherWeatherKit 联网查询
原生能力入口MiniApp 场景配方

#预期效果

运行示例后,界面应出现文档描述的目标结果;若与预期不符,先看「失败路径」并按返回值或日志排查。