因为python main.py不启动asgi服务器,fastapi的路由、中间件、依赖注入和async/await逻辑均失效;uvicorn是专为asgi设计的服务器,能正确调度异步事件循环,且--reload支持热重载,开发必须使用uvicorn main:app --reload。

为什么用 uvicorn --reload 而不是 python main.py
因为 python main.py 会直接执行脚本,不启动 ASGI 服务器,FastAPI 的路由、中间件、依赖注入全失效;uvicorn 是专为 ASGI 设计的服务器,能正确调度 async/await 逻辑。开发时必须用 uvicorn main:app --reload,否则修改代码后得手动重启,且异步协程根本不会被事件循环接管。
常见错误现象:RuntimeError: There is no current event loop in thread 'MainThread' —— 多半是误用 python main.py 或在顶层写了 asyncio.run(...)。
-
--reload只在开发阶段启用,它监听文件变化并热重载整个 app,但会重新初始化全局变量(比如数据库连接池需在依赖中懒加载) - 别加
--workers到开发命令里:多 worker 会触发多个独立事件循环,容易导致RuntimeError: There is no current event loop - 确保
main.py同级没有__init__.py,否则 uvicorn 可能误判包结构,找不到app
VS Code 调试配置要绕过 uvicorn 子进程陷阱
直接点「运行」按钮调试 main.py 会失败——因为 uvicorn 启动后 fork 出子进程,VS Code 默认只 attach 主进程,断点全失效。必须用 launch.json 显式指定入口和参数。
实操建议:在项目根目录建 .vscode/launch.json,内容如下:
python-docx Skill功能概述python-docx Skill是一项面向实际任务的技能,主要用于本Skill提供使用python-docx生成专业Word文档的标准方法和最佳实践;生成安全服务方案文档;核心要点生成技术架构设计文档;生成任何需要专业排版的Word文档;核心库 : python-docx;使用与执行辅助库 : docx.shared , docx.enum , docx.oxml.ns;标准代码模板;1. 文档初始化;2. 字体设置(必须!它将相关步骤、工具调用和结果整理方式集
{
"version": "0.2.0",
"configurations": [
{
"name": "FastAPI (debug)",
"type": "python",
"request": "launch",
"module": "uvicorn",
"args": [
"--host", "127.0.0.1",
"--port", "8000",
"--reload",
"main:app"
],
"console": "integratedTerminal",
"justMyCode": true
}
]
}
- 用
"module": "uvicorn"而非"program",让 VS Code 启动 uvicorn 模块本身,而非 shell 命令 -
"justMyCode": true避免断点跳进 uvicorn 内部源码 - 如果用了
fastapi dev(FastAPI CLI),它底层仍是 uvicorn,但调试支持不稳定,优先用原生命令
Pydantic v2 模型与类型提示必须严格匹配
FastAPI 依赖 Pydantic 解析请求体、生成 OpenAPI 文档。v2 版本(FastAPI ≥ 0.104)对类型检查更严格:字段缺失、类型不符、嵌套模型未实例化都会直接 422 报错,而不是静默转换。
例如写 class Item(BaseModel): name: str = None 会报错,必须写 name: Optional[str] = None 并导入 from typing import Optional。
- 所有路径参数、查询参数、请求体字段都需明确标注类型,
int和str不能混用(比如id: int却传字符串 "123") - 返回值类型提示必须可序列化:
-> dict、-> List[Item]或-> Item,不能写-> str然后 return JSON 字符串 - 若用
JSONResponse手动构造响应,就绕过 Pydantic 校验,但会丢失自动文档和类型安全,不推荐
异步测试必须用 httpx.AsyncClient + ASGITransport
用 TestClient(来自 starlette.testclient)跑异步接口会卡死或报 RuntimeError: asyncio.run() cannot be called from a running event loop,因为它本质是同步客户端,无法 await。
正确方式是组合 httpx.AsyncClient 和 ASGITransport,直接对接 ASGI 接口,不走真实网络栈:
import pytest
from httpx import ASGITransport, AsyncClient
from main import app
@pytest.mark.anyio
async def test_root():
async with AsyncClient(
transport=ASGITransport(app=app),
base_url="http://test"
) as ac:
response = await ac.get("/")
assert response.status_code == 200
- 必须加
@pytest.mark.anyio,否则 pytest 不识别async def函数 -
base_url可任意填(如"http://test"),因为 ASGI 传输不发 HTTP 请求,只是模拟调用 - 别漏掉
async with上下文管理器,否则连接不释放,多次测试后可能报ConnectionResetError
大量免费API接口:立即使用
涵盖生活服务API、金融科技API、企业工商API、等相关的API接口服务。免费API接口可安全、合规地连接上下游,为数据API应用能力赋能!










