PYTHON MINI PROJECTS / PRACTICE 03
实战篇 3 · 再往前一步PRACTICE 03 · async / API / FastAPI
目标:看懂 async/await,会调一个 API,能起一个最小 FastAPI 服务,最后用自检清单验收自己。
本章内容与知识点
第三份实战再往前一步:看懂 async / await 的并发写法,用 urllib 调 API 并处理超时和异常,起一个最小的 FastAPI 服务,最后用自检清单验收自己是不是真的学完了。 注意:任务 2 调 API 需要网络(另附离线练习),任务 3 需先 pip install fastapi uvicorn。
并发
async / awaitasyncio.gather
网络
urllib超时处理异常捕获
服务
FastAPI 最小应用
验收
自检清单全流程复盘
本篇章知识点覆盖对照
| 知识点 | 落在哪个项目 | 你要做到的程度 |
|---|---|---|
| async / await / asyncio.run | 案例、任务 1 | 会写并运行一个协程 |
| gather 并发 | 案例、任务 1 | 能对比顺序与并发耗时 |
| urllib 请求 / 超时 / 异常 | 任务 2 | 知道 I/O 一定要设超时 |
| JSON 解析 | 任务 2 | 离线也能用 json.loads 验证 |
| FastAPI 最小服务 / Pydantic 模型 | 任务 3 | 能起服务并打开 /docs |
| 自检清单与后续路线 | 任务 3 | 能自己判断下一步学什么 |
案例
async 与 await 初探(跟着敲)
介绍 · 纯本地可运行保存为 async_first.py。先建立直觉:async def 定义协程,await 是"我可以先等一会儿,你去跑别的"。
# -*- coding: utf-8 -*-
"""实战 3 速览:async / await / gather / JSON 解析。"""
import asyncio
import json
async def work(n):
await asyncio.sleep(0.05) # 异步等待,不阻塞
return n * n
async def main():
result = await asyncio.gather(work(1), work(2), work(3))
print("并发结果:", result)
data = json.loads('{"name": "小明", "ok": true}')
print("解析结果:", data["name"], data["ok"])
if __name__ == "__main__":
asyncio.run(main())
并发结果: [1, 4, 9] 解析结果: 小明 True
asyncio.sleep() 是异步版 sleep;普通 time.sleep() 会真的把线程堵住,放进协程里就没意义了。任务 1
顺序 vs 并发耗时对比
自己敲 · gather / 耗时统计解题提示:本题主要用到 gather、耗时统计。先对照要求自己敲一遍,卡住了再展开答案。
写 async_compare.py:
- 定义协程
work(i):await asyncio.sleep(0.3)后返回i*i。 - 先顺序执行 4 次(在 for 里直接
await work(i)),记录耗时。 - 再用
asyncio.gather(*(work(i) for i in range(4)))并发执行,记录耗时。 - 打印两种耗时与结果,验证并发明显更快。
- 注释说明:I/O 等待型任务适合 asyncio,CPU 密集型要靠多进程。
参考答案(先自己敲,再看)
# async_compare.py —— 顺序 vs 并发
import asyncio
import time
async def work(i):
await asyncio.sleep(0.3)
return i * i
async def main():
t0 = time.perf_counter()
seq = []
for i in range(4):
seq.append(await work(i))
seq_time = time.perf_counter() - t0
t0 = time.perf_counter()
par = await asyncio.gather(*(work(i) for i in range(4)))
par_time = time.perf_counter() - t0
print("顺序结果:", seq, f"耗时 {seq_time:.2f}s")
print("并发结果:", par, f"耗时 {par_time:.2f}s")
if __name__ == "__main__":
asyncio.run(main())
# I/O 等待型任务(网络、文件)适合 asyncio;CPU 密集型请用多进程。顺序结果: [0, 1, 4, 9] 耗时 1.20s 并发结果: [0, 1, 4, 9] 耗时 0.30s
任务 2
调一个 API:请求、超时、异常、解析
自己敲 · urllib / 离线模拟解题提示:本题主要用到 urllib、离线模拟。先对照要求自己敲一遍,卡住了再展开答案。
写 api_call.py。真实请求需要联网,先把离线解析部分跑通:
- 用标准库
urllib.request.urlopen(url, timeout=5)请求https://httpbin.org/get。 - 用
json.load(response)解析,打印origin字段。 - 用
try/except urllib.error.URLError捕获网络错误,打印友好提示。 - 用
TimeoutError单独处理超时。 - 离线练习:把一段 JSON 字符串用
json.loads()解析并打印某个字段,确保"解析"这一步不依赖网络。
参考答案(先自己敲,再看)
# api_call.py —— 调 API 与离线解析
import json
import urllib.request
import urllib.error
def fetch(url: str, timeout: int = 5) -> dict | None:
try:
with urllib.request.urlopen(url, timeout=timeout) as resp:
return json.load(resp)
except TimeoutError:
print("请求超时了")
except urllib.error.URLError as e:
print("网络出错:", e.reason)
return None
# 离线部分:一定能跑通
mock = '{"name": "小明", "skills": ["Python", "SQL"]}'
data = json.loads(mock)
print("离线解析结果:", data["name"], data["skills"][0])
# 联网部分:有网时取消下一行注释
# result = fetch("https://httpbin.org/get")
# if result:
# print("你的 IP:", result.get("origin"))
# 真实项目里通常会用 requests 或 httpx,标准库版本用来看懂底层流程。离线解析结果: 小明 Python
超时一定要设;网络请求可能失败,永远不要把"能连上"当成默认前提。
任务 3
FastAPI 最小服务 + 自检清单
自己敲 · 服务 / 验收解题提示:本题主要用到 服务、验收。先对照要求自己敲一遍,卡住了再展开答案。
先 pip install fastapi uvicorn,写 server.py:
app = FastAPI()创建应用。- 用
@app.get("/")写一个返回{"msg": "你好"}的接口。 - 用 Pydantic 模型
class Item(BaseModel)定义name: str和price: float。 - 用
@app.post("/items")接收 Item 并原样返回。 - 运行
uvicorn server:app --reload,浏览器打开http://127.0.0.1:8000/docs看自动文档。
参考答案(先自己敲,再看)
# server.py —— 最小 FastAPI 服务
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI(title="我的第一个 API")
class Item(BaseModel):
name: str
price: float
@app.get("/")
def root():
return {"msg": "你好"}
@app.post("/items")
def create_item(item: Item):
return {"name": item.name, "price": item.price}uvicorn server:app --reload # 另开一个终端测试: curl http://127.0.0.1:8000/
{"msg":"你好"}任务 4
asyncio并发抓取模拟
自己敲 · async / await / gather解题提示:本题主要用到 async / await、gather、asyncio。先对照要求自己敲一遍,卡住了再展开答案。
用 asyncio.gather 并发跑几个"假任务",感受并发写法。
- 定义
async def work(n):内部await asyncio.sleep(0.01),然后返回n * n。 - 在
async def main()里用await asyncio.gather(work(1), work(2), work(3))并发执行。 - 打印结果列表,应是
[1, 4, 9]。 - 用
asyncio.run(main())启动。
提示:
gather 把多个协程一起调度,结果按传入顺序返回。参考答案(先自己敲,再看)
# asyncio 并发抓取模拟
import asyncio
async def work(n):
await asyncio.sleep(0.01) # 模拟耗时的 IO
return n * n
async def main():
results = await asyncio.gather(work(1), work(2), work(3))
print("结果:", results)
asyncio.run(main())结果: [1, 4, 9]
任务 5
JSON响应解析练习
自己敲 · json / 离线解析解题提示:本题主要用到 json.loads、字典取值、异常处理。先对照要求自己敲一遍,卡住了再展开答案。
不联网,直接解析一段模拟的 JSON 响应文本,提取需要的信息。(呼应前面"调 API"的解析环节。)
- 响应文本
raw = '{"code": 0, "data": {"name": "小明", "age": 18}}'。 - 用
json.loads(raw)转成字典。 - 若
code == 0,打印姓名:小明,年龄:18。 - 解析失败时捕获
json.JSONDecodeError并提示。
提示:
json.loads 把 JSON 字符串转成 Python 对象;load 才是读文件。参考答案(先自己敲,再看)
# JSON 响应解析练习
import json
raw = '{"code": 0, "data": {"name": "小明", "age": 18}}'
try:
resp = json.loads(raw)
if resp["code"] == 0:
d = resp["data"]
print(f"姓名:{d['name']},年龄:{d['age']}")
else:
print("接口返回错误码:", resp["code"])
except json.JSONDecodeError as e:
print("解析失败:", e)姓名:小明,年龄:18
「我能写 Python 了」自检清单
| 能力 | 自测方式 | 对应章节 |
|---|---|---|
| 能独立建 .py 并在终端运行 | 写一个带 input 的脚本跑通 | 1 |
| 数字与字符串操作 | 手写格式化与小工具 | 2 |
| 列表/字典推导式 | 不看答案写出成绩筛选 | 3、7 |
| 条件与循环 | 写猜数字游戏 | 4、5 |
| 函数与参数 | 写一个带 *args 的工具函数 | 6 |
| 文件与 JSON | 写带持久化的 TODO | 10、16 |
| 异常处理 | 给 TODO 加输入校验 | 11 |
| 类与对象 | 写一个带 property 的类 | 12 |
| 虚拟环境与包 | 建 venv 并导出 requirements | 14 |
| 测试 | 给一个函数写 3 组参数测试 | 15 |
| 命令行与服务 | argparse 脚本 + FastAPI 最小服务 | P2、P3 |
接下来往哪儿走:回到参考站的 FastAPI 章节,或继续 AI Agents 学习路线(Prompt → Agent → RAG → MCP)。