
- FastAPI 教程
- FastAPI - 首页
- FastAPI - 简介
- FastAPI - Hello World
- FastAPI - OpenAPI
- FastAPI - Uvicorn
- FastAPI - 类型提示
- FastAPI - IDE 支持
- FastAPI - REST 架构
- FastAPI - 路径参数
- FastAPI - 查询参数
- FastAPI - 参数验证
- FastAPI - Pydantic
- FastAPI - 请求体
- FastAPI - 模板
- FastAPI - 静态文件
- FastAPI - HTML 表单模板
- FastAPI - 访问表单数据
- FastAPI - 上传文件
- FastAPI - Cookie 参数
- FastAPI - 头部参数
- FastAPI - 响应模型
- FastAPI - 嵌套模型
- FastAPI - 依赖项
- FastAPI - CORS
- FastAPI - CRUD 操作
- FastAPI - SQL 数据库
- FastAPI - 使用 MongoDB
- FastAPI - 使用 GraphQL
- FastAPI - WebSockets
- FastAPI - FastAPI 事件处理器
- FastAPI - 挂载子应用
- FastAPI - 中间件
- FastAPI - 挂载 Flask 应用
- FastAPI - 部署
- FastAPI 有用资源
- FastAPI - 快速指南
- FastAPI - 有用资源
- FastAPI - 讨论
FastAPI - Uvicorn
与 Flask 框架不同,FastAPI 不包含任何内置的开发服务器。因此,我们需要 **Uvicorn**。它实现了 **ASGI** 标准并且速度极快。ASGI 代表 **异步服务器网关接口**。
**WSGI**(Web 服务器网关接口 - 旧标准)兼容的 Web 服务器不适合 **asyncio** 应用程序。实现 ASGI 规范的 Python Web 框架(如 FastAPI)提供了高速性能,与使用 Node 和 Go 构建的 Web 应用程序相当。
Uvicorn 使用 **uvloop** 和 **httptools** 库。它还提供了对 HTTP/2 和 WebSockets 的支持,而这些是 WSGI 无法处理的。**uvloop** 类似于内置的 **asyncio** 事件循环。**httptools** 库处理 http 协议。
如前所述,Uvicorn 的安装将以最少的依赖项进行安装。但是,标准安装还将安装基于 **cython** 的依赖项以及其他一些库。
pip3 install uvicorn(standard)
这样,**WebSockets** 协议将得到支持。此外,还将安装 **PyYAML** 以允许您提供 .yaml 文件。
如前所述,应用程序在 Uvicorn 服务器上使用以下命令启动 -
uvicorn main:app –reload
**--reload** 选项启用调试模式,以便 **app.py** 中的任何更改都会自动反映,并且客户端浏览器上的显示也会自动刷新。此外,可以使用以下命令行选项 -
序号 | 命令及描述 |
---|---|
1 | --host TEXT 将套接字绑定到此主机。[默认值 127.0.0.1] |
2 | --port INTEGER 将套接字绑定到此端口。[默认值 8000] |
3 | --uds TEXT 绑定到 UNIX 域套接字。 |
4 | --fd INTEGER 绑定到来自此文件描述符的套接字。 |
5 | --reload 启用自动重新加载。 |
6 | --reload-dir PATH 显式设置重新加载目录,默认为当前工作目录。 |
7 | --reload-include TEXT 在监视时包含文件。默认情况下包含 '*.py' |
8 | -reload-exclude TEXT 在监视文件时排除。 |
9 | --reload-delay FLOAT 上次检查和下次检查之间延迟,默认为 0.25 |
10 | -loop [auto|asyncio|uvloop] 事件循环实现。[默认值 auto] |
11 | --http [auto|h11|httptools] HTTP 协议实现。[默认值 auto] |
12 | --interface auto|asgi|asgi|wsgi 选择应用程序接口。[默认值 auto] |
13 | --env-file PATH 环境配置文件。 |
14 | --log-config PATH 日志配置文件。支持的格式 .ini、.json、.yaml。 |
15 | --version 显示 uvicorn 版本并退出。 |
16 | --app-dir TEXT 在指定的目录中查找 APP,默认为当前目录 |
17 | --help 显示此消息并退出。 |
除了从命令行启动 Uvicorn 服务器之外,还可以以编程方式启动它。
示例
在 Python 代码中,使用上面列出的任何参数调用 **uvicorn.run()** 方法 -
import uvicorn from fastapi import FastAPI app = FastAPI() @app.get("/") async def index(): return {"message": "Hello World"} if __name__ == "__main__": uvicorn.run("main:app", host="127.0.0.1", port=8000, reload=True)
现在,将此 **app.py** 作为 Python 脚本运行,如下所示 -
(fastapienv) C:\fastapienv>python app.py
因此,Uvicorn 服务器将在调试模式下启动。