uvicorn main.py 命令说明

uvicorn main.py 命令说明

bash

复制代码
uvicorn main.py

等价于:

bash

复制代码
uvicorn main:app

规则:文件名:实例对象main.py 里面必须有变量叫 app(FastAPI/Starlette 实例)

常用完整命令

bash

复制代码
# 基础启动,默认 127.0.0.1:8000
uvicorn main:app

# 外部可访问,0.0.0.0,端口8000,开启热重载(开发用)
uvicorn main:app --host 0.0.0.0 --port 8000 --reload

# 指定工作进程数(生产环境,不要加 --reload)
uvicorn main:app --host 0.0.0.0 --port 8000 --workers 4

main.py 最小示例

python

运行

复制代码
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def hello():
    return {"msg": "hello uvicorn"}

常见报错

  1. uvicorn: command not found

bash

复制代码
# 方式1:全局安装
pip install uvicorn
# 或者用 python -m 调用,不用加到PATH
python -m uvicorn main:app --reload
  1. AttributeError: module 'main' has no attribute 'app'
  • main.py 没有定义 app = FastAPI()
  • 或者写错变量名,比如叫 api,那就要写 uvicorn main:api
  1. --reload 仅开发使用,生产环境禁止开启 reload

python -m uvicorn 写法(推荐,环境隔离不容易踩 PATH 坑)

bash

复制代码
python -m uvicorn main:app --host 0.0.0.0 --port 8000 --reload
相关推荐
巴啦啦小魔仙变身1 天前
FastAPI 01 Create Demo
python·fastapi
李昊哲小课3 天前
fastapi sse websocket 奶茶店实时订单看板
人工智能·python·websocket·网络协议·fastapi·sse
李昊哲小课3 天前
fastapi sse websocket 智能家居实时控制台
python·websocket·智能家居·fastapi·sse
赵广陆3 天前
SQLAlchemy ORM 超全教程
python·fastapi
为啥全要学3 天前
fastapi websocket全双工通信
websocket·网络协议·fastapi
这就是佬们吗3 天前
企业Agent落地为什么需要RAG?
人工智能·python·fastapi
鲨鱼辣钊4 天前
【FastAPI 筑基 - Day2】彩色日志封装 + Python 装饰器精讲
fastapi
Muselit4 天前
Python 泛型:把 list[User] 讲明白
python·fastapi
赵广陆4 天前
FastAPI零基础完整实战
前端·chrome·fastapi