
- 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 - IDE 支持
Python 的类型提示功能在几乎所有IDE(集成开发环境),例如PyCharm和VS Code中得到最有效的利用,以提供动态自动完成功能。
让我们看看 VS Code 如何使用类型提示在编写代码时提供自动完成建议。在下面的示例中,定义了一个名为sayhello的函数,其中 name 作为参数。该函数通过在两者之间添加空格将“Hello”与 name 参数连接起来,从而返回一个字符串。此外,还需要确保 name 的首字母大写。
Python 的str类具有用于此目的的capitalize()方法,但是如果在键入代码时不记得它,则必须在其他地方搜索它。如果在 name 后面加一个点,您期望看到属性列表,但什么也没有显示,因为 Python 不知道 name 变量的运行时类型是什么。

在这里,类型提示派上用场。在函数定义中包含 name 的类型 str。现在,当您在 name 后按点 (.) 时,将出现所有字符串方法的下拉列表,从中可以选择所需的方法(在本例中为 capitalize())。

也可以将类型提示与用户定义的类一起使用。在下面的示例中,定义了一个矩形类,其中包含__init__()构造函数的参数的类型提示。
class rectangle: def __init__(self, w:int, h:int) ->None: self.width=w self.height=h
以下是一个使用上述矩形类的对象作为参数的函数。声明中使用的类型提示是类的名称。
def area(r:rectangle)->int: return r.width*r.height r1=rectangle(10,20) print ("area = ", area(r1))
在这种情况下,IDE 编辑器也提供了自动完成支持,提示实例属性列表。以下是PyCharm编辑器的屏幕截图。

FastAPI广泛使用类型提示。此功能随处可见,例如路径参数、查询参数、头部、主体、依赖项等,以及验证来自传入请求的数据。OpenAPI 文档生成也使用类型提示。
广告