FastAPI framework, high performance, easy to learn, fast to code, ready for production
FastAPI框架,高性能,易于学习,快速编码,准备投入生产。
文档入口: https://fastapi.tiangolo.com.
框架源码: https://github.com/tiangolo/fastapi.
FastAPI是一个现代的、快速的(高性能的)web框架,用于基于标准Python类型提示用Python 3.6+构建api。
主要特点如下:
- 快:非常高的性能,与NodeJS和Go(感谢Starlette和Pydantic)。可用的最快的Python框架之一。
- 快速编码: 提高开发速度约200%到300% 。
- 减少bug : 减少约40%的人为(开发人员)错误。
- 直观: 伟大的编辑器的支持,完成无处不在,更少的时间调试。
- 容易: 设计是为了便于使用和学习。减少阅读文档的时间。
- 短: 最小化代码重复。每个参数声明的多个特性。更少的错误。
- 健壮: 获得生产就绪代码。自动交互文档。
- 基于标准的: 基于(并完全兼容)api的开放标准:OpenAPI(以前称为Swagger)和JSON模式。
Typer, the FastAPI of CLIs
如果您正在构建一个在终端中使用的CLI应用程序,而不是web API,请查看Typer。
开发环境
安装
pip install fastapi
您还需要一个ASGI服务器,用于生产,如Uvicorn或Hypercorn。
pip install uvicorn
Demo例子
新建文件main.py
from fastapi import FastAPI app = FastAPI() @app.get("/") def read_root(): return {"Hello": "World"} @app.get("/items/{item_id}") def read_item(item_id: int, q: str = None): return {"item_id": item_id, "q": q}
️如果你的代码使用 async
/ await
, 使用 async def
:
from fastapi import FastAPI app = FastAPI() @app.get("/") async def read_root(): return {"Hello": "World"} @app.get("/items/{item_id}") async def read_item(item_id: int, q: str = None): return {"item_id": item_id, "q": q}
运行(本地服务器)
uvicorn main:app --reload
命令解析:
- 命令
uvicorn main:app
指的是: main
: 文件main.py
(Python“模块”).app
: 在main.py
中使用app = FastAPI()
创建的对象。--reload
: 在代码更改后重新启动服务器。这样做只是为了开发方便。- 可以自行输入
uvicorn --help
查看命令使用的方法。
测试功能
打开浏览器 复制它:http://127.0.0.1:8000/items/5?q=somequery.
您将看到JSON响应如下:
{"item_id": 5, "q": "somequery"}
你已经创建了一个API:
- 在路径
/
和/items/{item_id}
中接收HTTP
请求。 - 这两条路径都采用
GET
操作(也称为HTTP
方法)。 - path:
/items/{item_id}
有一个路径参数item_id
,它应该是一个整数。 - path
/items/{item_id}
有一个可选的str
查询参数q
。
交互式API文档
那么,现在改变地址为:[http://127.0.0.1:8000/docs] (http://127.0.0.1:8000/docs).
index-01-swagger-ui-simple.png
你会看到自动化的用于交互的API文档(由Swagger UI提供):
其他的API文档
现在,转到http://127.0.0.1:8000/redoc。
你会看到另一个自动文档(由ReDoc提供):
index-02-redoc-simple.png
进阶版-例子(Example)
现在修改文件main.py
,以便从PUT
请求接收主体。
使用标准Python类型声明主体,这得益于Pydantic。
from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: str price: float is_offer: bool = None @app.get("/") def read_root(): return {"Hello": "World"} @app.get("/items/{item_id}") def read_item(item_id: int, q: str = None): return {"item_id": item_id, "q": q} @app.put("/items/{item_id}") def update_item(item_id: int, item: Item): return {"item_name": item.name, "item_id": item_id}
服务器会自动重新加载(因为您添加了--reload
到上面的uvicorn
命令)。
进阶版-交互式文档
现在,前往http://127.0.0.1:8000/docs
- 交互式API文档将自动更新,包括新的主体:
index-03-swagger-02.png
- 点击“Try it out”按钮,可以填写参数,直接与API交互:
index-04-swagger-03.png
- 然后点击“Execute”按钮,用户界面将与您的API进行通信,发送参数,获取结果并显示在屏幕上:
index-05-swagger-04.png
进阶版-其他可选的API文档
然后现在,转到:http://127.0.0.1:8000/redoc
- 文档还将反映新的查询参数和主体:
index-06-redoc-02.png
知识回顾
总之,只需将参数、主体等类型声明为函数参数,使用标准的现代Python类型就可以做到这一点。
您不必学习新的语法、特定库的方法或类,等等。
只需要标准的Python 3.6+版本。
- 比如,一个
int
类型
item_id: int
或者对于更复杂的Item
模型:
item: Item
..有了这种声明,你就可以这样:
- 编辑器支持,包括:
- 智能完成部分代码
- 类型检查
- 验证数据:
- 当数据无效时自动清除错误
- 甚至对深度嵌套的JSON对象进行验证
- 输入数据的转换: 从PC端到Python数据和类型的转换
- JSON
- Path参数
- Query参数
- Cookies - 缓存信息
- Headers - 请求头
- Forms - 表单
- Files - 文件
- 输出数据的转换: 从Python数据和类型转换为PC端数据(JSON格式):
- 转换Python类型(
str
、int
、float
、bool
、list
等) datetime
对象- 对象
UUID
- 数据库模型
- 更多
- 自动化交互式API文档,包括2个交互式文档web接口:
- Swagger UI
- ReDoc
回到前面的代码示例,FastAPI会执行以下操作:
- 验证GET和PUT请求的路径中是否有
item_id
。 - 验证
item_id
的类型为int
,以用于GET和PUT请求。 - 如果不是,客户端将看到一个有用的、明显的错误。
- 检查是否有一个名为
q
的可选查询参数(如http://127.0.0.1:8000/items/foo?q=somequery)用于获取请求。 - 由于
q
参数是用= None
声明的,所以它是可选的。 - 如果没有
None
,它将是必需的(就像PUT中的主体一样)。 - 对于PUT请求到
/items/{item_id}
,将body读取为JSON: - 检查它是否有一个必需的属性名,该属性名应该是str。
- 检查它的
required
属性price
必须是一个浮点数。 - 检查它是否有一个可选属性
is_offer
,如果存在,它应该是一个bool
。 - 所有这些也适用于深度嵌套的JSON对象。
- 自动将其转换为JSON。
- 用OpenAPI记录所有可以使用的东西:
- 交互式文档系统。
- 自动化客户端代码生成系统,适用于多种语言。
- 直接提供2个交互式文档web接口。
我们只是学到了一些最基础最表面的东西,但是您已经了解了它是如何工作的。
你可以尝试着改变某一些行的代码:
return {"item_name": item.name, "item_id": item_id}
从以下这个:
... "item_name": item.name ...
到这些:
... "item_price": item.price ...
…看看你的编辑器将如何自动完成这些属性,并知道他们的类型:
有关包含更多特性的更完整示例,请参阅 教程-用户指南。
本教程 -- 用户指南包括:
-
来自不同地方的参数声明如下:headers, cookies, form fields 以及 files。
-
如何将validation constraints设置为
maximum_length
或regex
。 -
一个非常强大和容易使用的依赖注入系统。
-
安全性和身份验证,包括使用JWT令牌和HTTP基本验证支持OAuth2。
-
更高级(但同样简单)的技术,用于声明深度嵌套的JSON模型(Pydantic的强力支持)。
-
许多额外的功能(
感谢Starlette
)作为:
- WebSockets
- GraphQL
- 基于
request
和pytest
的非常简单的测试 - CORS
- Cookie Sessions - 会话层
- …和更多。
性能 (Performance)
独立的TechEmpower基准测试显示,在Uvicorn下运行的FastAPI应用程序是可用的最快的Python框架之一,仅低于Starlette和Uvicorn本身(由FastAPI内部使用)。(*)
要更多地了解它,请参阅“基准测试”一节。
可选依赖(Optional Dependencies)
使用Pydantic:
ujson
- 用于更快的JSON“解析”。email_validator
- 用于电子邮件验证。
使用Starlette:
request
-- 如果您想要使用TestClient
,那么这是必需的。aiofiles
—如果您想使用FileResponse
或StaticFiles
,则必须使用aiofiles
。jinja2
- 如果你想使用默认的模板配置,jinja2
是必须的。python-multipart
如果希望支持表单“解析”,那么使用request.form()
是必需的。itsdangerous
它是危险的——需要SessionMiddleware
(会话中间件)支持。pyyaml
-需要Starlette的SchemaGenerator
支持(您可能不需要FastAPI)。graphere
——GraphQLApp
支持所需。ujson
- 如果您想使用UJSONResponse
,则必须使用ujson
。
FastAPI / Starlette使用:
uvicorn
- 用于加载和服务您的应用程序的服务器。orjson
- 如果您想使用ORJSONResponse,则必须使用orjson。
您可以用pip install fastapi[all]
安装所有这些东西。
版权声明:除特别注明外,本站所有文章均为王晨曦个人站点原创
转载请注明:出处来自王晨曦个人站点 » FastAPI 快速入门
Cialis 20 Mg Reimport
http://buypropeciaon.com/ - finasterid
Baclofene Mylan
Catalogue Levitra
http://buytadalafshop.com/ - buy cialis 10mg
Cheap Unisom
http://buypriligyhop.com/ - Priligy
Januvia Online Belgium
Buy Amitriptyline Online In Uk
Genaric Viagra Gold
nike england soccer jacket iphone 11 pro max lens case sneaker schwarz lack damen yeezy 700 v2 carbon blue adidas coneo qt schwarz plataformas en yute cloudvisionsys [url=https://www.cloudvisionsys.com/]cloudvisionsys[/url]
puma golf chapeaux amazon apple x charger coque frozen fancy robe costume wvu baseball hat denim ruffle dress samsung note 4 back abdeckung ohsicbd
Luggage Travel Bags Tungsten Tipped ルイヴィトン財布スーパーコピー
pelicans ingram jersey puma cell venom sneakers luka jersey slovenia cold weather soccer clothes air jordan dunk orange kobe 9 negro gris smtlrtcc
ルイヴィトン財布コピー激安代引き Double Dong Sex Furniture
chanclas fila blancas summer abaya dress washington nationals black and charcoal classic 39thirty cap kleider von laona king snapback cappello stetson most expensive cappello farmbeer
dallas mavericks 47 nba kaki 47 clean up casquette 31 xl utility tote new rosso jordan 11 new era casquette flexfit iphone xs max wristlet coque target tank robe brodheim
Drinking Water Bottle ヴィトン財布コピー POU Water Dispenser
Eccentric Butterfly Valve With Electric Actuator Door Frame Automatic Paint Spraying Machine ルイヴィトン財布コピー激安代引き
Mobile Kiosk Charger ルイヴィトン財布コピー激安代引き PVB Film
ルイヴィトンコピー財布 Custom Patches For Clothing 20-100 Square Meters Indoor Playground
alexander mcqueen wedge sneakers nike air max 97 nero rosso verde kids dress online purchase jordan 4s air nike air max thea light blu bianca steph curry the bay jersey cagataycatal
alcantara coque galaxy s9 kittle black jersey nero e bianca bucket cappello adidas yung blanche kenzo tennix scarpe stiefeletten herbst shortnewsposter
ルイヴィトン財布コピー 2MP 4G Wireless SD Card Outdoor IP Bullet Camera Salt Nic Vs Nic
Rechargeable Clipper Best Selling Bear Love Small Daisy Shape Hook ルイヴィトンコピー財布
kleid flowers for friends sale dr martens talla 37 wednesday addams vestido canada tenis diesel only the brave zimmermann eyelet vestido adidas ash pearl slides atrapaniapp
rose croc chaussons black purple wedding dress gorra negra mercedes benz emerald satin maxi dress borse hogan 2017 skechers go walk 4 herren upskirtpussypics
pandora harry potter singapore pandora cherry earrings lebron low 17 black nike magista opus ii white shoes for sale pink summer dresses 2020 michael kors leather smartphone crossbody federalspare
ルイヴィトン財布スーパーコピー Popular Lollipop Pearl And Flower Earrings Portable Solar Station
Spraying Machine For Woodworking New Style Good Price 5-pronged Hyacinth Artificial Boquet For Decoration ルイヴィトン財布スーパーコピー