16
loading...
This website collects cookies to deliver better user experience
x = 4
print(type(4)) # at this moment, x points to an integer
x = "Hello, world"
print(type(x)) # and at this moment, x points to a string
name: str = "world"
def greeting(name: str) -> str:
return "Hello " + name
greeting(name)
: str
聲明 name
為字串,以及在函式我們用 -> str
聲明 greeting()
回傳的也是字串,當然還有更複雜的用法,可以參見〈Python Type Hints 從入門到實踐〉。from pydantic import BaseModel
class EmployeeModel(BaseModel):
name: str
salary: int
EmployeeModel
中,我們聲明了 name
應為字串、salary
應為整數,透過繼承自 BaseModel
的特性,pydantic 會自動幫我們驗證型態的正確性。employee = EmployeeModel(
name='Bar',
salary=1000,
)
employee = EmployeeModel(
name='Bar',
salary='secret',
)
salary
,卻被塞了字串,引發 validation error:Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/leon/Projects/pydantic/.venv/lib/python3.10/site-packages/pydantic/main.py", line 406, in __init__
raise validation_error
pydantic.error_wrappers.ValidationError: 1 validation error for EmployeeModel
salary
value is not a valid integer (type=type_error.integer)
from typing import Optional
from fastapi import FastAPI
from pydantic import BaseModel
class Item(BaseModel):
name: str
description: Optional[str] = None
price: float
tax: Optional[float] = None
app = FastAPI()
@app.post("/items/")
async def create_item(item: Item):
return item
description
與 tax
的 type hints 是 Optional[str]
,而預設值為 None
,Optional[str]
意味著此屬性是選填的,如果建立實例時未填,則屬性值為 None
。create_item(item: Item)
接受一個參數 item
,並且該參數之型態應為前面定義的 Item model,在這樣的的定義與聲明下,前端送過來的 request body 會自動的被 pydantic 解析與驗證,並且那 FastAPI 自動產生的 OpenAPI 文件也會載明該端點的 JSON schema: