FastAPI框架學習

1. 什么是FastAPI?

FastAPI 是一個用于構(gòu)建 API 的現(xiàn)代、快速(高性能)的 web 框架,使用 Python 3.6+ 并基于標準的 Python 類型提示,

fastapi 是python最快的web框架。

"""
特性:
1.快速,比肩go
2.編碼快速,開發(fā)快
3.減少人為bug
4.智能,自動補全, 減少調(diào)試時間
5.設計易于學習,文檔簡單
6.簡短: 代碼量小,bug更少
7.健壯:生產(chǎn)場景,生成交互式文檔
8.標準化:基于API的相關的開放標準
"""

2.安裝

pip install fastapi

依賴

pip install uvicorn[standard]

3.最小愛快速示例:

import uvicorn
from typing import Optional, Set
from fastapi import FastAPI, Path, Query
from pydantic import BaseModel

app = FastAPI() # 這里的變量 app 會是 FastAPI 類的一個「實例」,這個實例將是創(chuàng)建你所有API 的主要交互對象,每個接口@app.get/put中的app。

class Item(BaseModel):
name: str
price: float
is_offer: Optional[bool] = None

@app.get("/")
def read_root():
return {"Hello": "World"}

@app.get("/items/{item_id}")
def read_item(item_id: int, q: Optional[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}

3.1 命令運行:

uvicorn main:app --reload

3.2 代碼運行:

if name == 'main':

uvicorn.run(app=app, host="10.148.228.113", port=65500, workers=1)

4.性能優(yōu)異

基于 Uvicorn 運行的 FastAPI 程序是 最快的 Python web框架之一,支持異步和并發(fā)

5.類型提示:

同樣以冒號(:)來聲明這個變量。

6.Pydantic 模型?

Pydantic 是一個用來用來執(zhí)行數(shù)據(jù)校驗的 Python 庫。

7.路徑操作裝飾器

在開發(fā) API 時,你通常使用特定的 HTTP 方法去執(zhí)行特定的行為

POST:創(chuàng)建數(shù)據(jù)。

GET:讀取數(shù)據(jù)。

PUT:更新數(shù)據(jù)。

DELETE:刪除數(shù)據(jù)。

8.fastapi程序的步驟:

導入 FastAPI。

創(chuàng)建一個 app 實例。

編寫一個路徑操作裝飾器(如 @app.get("/"))。

編寫一個路徑操作函數(shù)(如上面的 def root(): ...)。

運行開發(fā)服務器(如 uvicorn main:app --reload)。

9.路徑參數(shù)

路徑參數(shù) item_id 的值將作為參數(shù) item_id 傳遞給你的函數(shù)

由于路徑操作是按順序依次運行的,你需要確保路徑 /users/me 聲明在路徑 /users/{user_id}之前:

否則,/users/{user_id} 的路徑還將與 /users/me 相匹配,"認為"自己正在接收一個值為 "me" 的 user_id 參數(shù)。

10.查詢參數(shù)

聲明不屬于路徑參數(shù)的其他函數(shù)參數(shù)時,它們將被自動解釋為"查詢字符串"參數(shù)

查詢字符串是鍵值對的集合,這些鍵值對位于 URL 的 ? 之后,并以 & 符號分隔。

fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}]

@app.get("/items/")

async def read_item(skip: int = 0, limit: int = 10):

return fake_items_db[skip : skip + limit]

11.請求體參數(shù)

請求體是客戶端發(fā)送給 API 的數(shù)據(jù)。響應體是 API 發(fā)送給客戶端的數(shù)據(jù)。

注意: 要發(fā)送數(shù)據(jù),你必須使用下列方法之一:POST(較常見)、PUT、DELETE 或 PATCH。

"""
使用 Pydantic 模型來聲明請求體
from pydantic import BaseModel
當一個模型屬性具有默認值時,它不是必需的

"""

class Item(BaseModel):
name: str
description: Optional[str] = None
price: float
tax: Optional[float] = None

12.查詢參數(shù)和字符串校驗

當你在使用 Query 且需要聲明一個值是必需的時,可以將 ... 用作第一個參數(shù)值:

"""
通用的校驗和元數(shù)據(jù):
alias
title
description
deprecated
特定于字符串的校驗:
min_length
max_length
regex
"""

13.路徑參數(shù)和數(shù)值校驗

可以使用 Path 為路徑參數(shù)聲明相同類型的校驗和元數(shù)據(jù)。

路徑參數(shù)總是必需的,因為它必須是路徑的一部分。

所以,你應該在聲明時使用 ... 將其標記為必需參數(shù)。

然而,即使你使用 None 聲明路徑參數(shù)或設置一個其他默認值也不會有任何影響,它依然會是必需參數(shù)。

sla_id: str = Path(None, description="SLA的id", example="100191918"))

數(shù)值校驗

gt:大于(greater than)

le:小于等于(less than or equal)

item_id: int = Path(..., title="The ID of the item to get", gt=0, le=1000),

14.請求體--多個參數(shù):

async def update_item(item_id: int, item: Item = Body(..., embed=True)):

這里的 embed 參數(shù)為true時候, 將原本的請求體嵌入到一個鍵中。

'''{
"item": {
"name": "Foo",
"description": "The pretender",
"price": 42.0,
"tax": 3.2
}
}

而不是:
{
"name": "Foo",
"description": "The pretender",
"price": 42.0,
"tax": 3.2
}

'''

15.請求體 - 字段(Pydantic 的 Field)

與使用 Query、Path 和 Body 在路徑操作函數(shù)中聲明額外的校驗和元數(shù)據(jù)的方式相同,

你可以使用 Pydantic 的 Field 在 Pydantic 模型內(nèi)部聲明校驗和元數(shù)據(jù)。

Field 的工作方式和 Query、Path 和 Body 相同,包括它們的參數(shù)等等也完全相同。

16.請求體--嵌套模型

from pydantic import BaseModel, HttpUrl

class Image(BaseModel):
url: HttpUrl
name: str

class Item(BaseModel):
name: str
description: Optional[str] = None
price: float
tax: Optional[float] = None
tags: Set[str] = set()
image: Optional[Image] = None

17.模式的額外信息

class Config:

schema_extra

聲明您的應用可以接收的數(shù)據(jù)示例。

同樣的方法,你可以添加你自己的額外信息,這些信息將被添加到每個模型的JSON模式中,例如定制前端用戶界面,等等。

18.cookie參數(shù)

Cookie 、Path 、Query是兄弟類,它們都繼承自公共的 Param 類

async def read_items(ads_id: Optional[str] = Cookie(None)):

19.Header 參數(shù)

token=Header(..., alias="X-Auth-Token", title="X-Auth-Token", description="請求token"),

不用擔心變量中的下劃線,F(xiàn)astAPI 會負責轉(zhuǎn)換它們。

21.響應模型

在下面的任意的路徑操作中使用 response_model 參數(shù)來聲明用于響應的模型:

@app.get()

@app.post()

@app.put()

@app.delete()

response_model是「裝飾器」方法(get,post 等)的一個參數(shù)。不像之前的所有參數(shù)和請求體,它不屬于路徑操作函數(shù)。

"""
例子:
@api.post(
"/restores/{copy_id}/action/download",
status_code=200,
tags=API_TAG,
description="Download API",
summary="download",
response_model=DownloadResponseSchema
)

"""

22.響應狀態(tài)碼

@app.post("/items/", status_code=201)

會在交互式文檔中展示返回在這里定義的狀態(tài)碼

23.表單數(shù)據(jù) Form

24.文件上傳

from fastapi import FastAPI, File, UploadFile

24.請求表格和文件

async def create_file(

file: bytes = File(...), fileb: UploadFile = File(...), token: str = Form(...)

):

當您需要在同一請求中接收數(shù)據(jù)和文件時File,F(xiàn)orm一起使用和。

25.請注意,response_description特指響應,description泛指路徑操作。

description可以使用長字符串或者多行文本。用于docs中api接口描述;參數(shù)response_description用于響應描述。。

26.tags 參數(shù): 你可以給路徑操作(post, put, get, delete)函數(shù)添加標記,通過tags參數(shù),參數(shù)類型可以是list或者str(一般是一個str):

主要作用就是在docs交互文檔中進行 模塊之間的分割,mysql模塊, filesets 模塊

27.總結(jié)(summary)和描述(description)

28.Json兼容(將對象轉(zhuǎn)化為json)

from typing import Optional
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel
class Item(BaseModel):
title: str
timestamp: str
description: Optional[str] = None

item = Item(title='nanfanfa',timestamp="2021.6.21")
json_compatible_item_data = jsonable_encoder(item)
print(json_compatible_item_data) # {'title': 'nanfanfa', 'timestamp': '2021.6.21', 'description': None}
print(json_compatible_item_data) # {'title': 'nanfanfa', 'timestamp': '2021.6.21', 'description': None}

29.

30.

31.

32.

if name == 'main':
uvicorn.run(app=app, host="10.148.228.113", port=65500, workers=1)

?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容