Skip to content

๐ŸŽป ๐Ÿ”— ๐Ÿ”ข

๐Ÿ“ค ๐Ÿ’ผ ๐ŸŒโ” ๐Ÿ‘† 5๏ธโƒฃ๐Ÿ“† ๐Ÿ’ช ๐Ÿ—œ ๐Ÿ’ฝ ๐Ÿ†Ž (๐Ÿ’– Pydantic ๐Ÿท) ๐Ÿ•ณ ๐Ÿ”— โฎ๏ธ ๐ŸŽป (๐Ÿ’– dict, list, โ™’๏ธ).

๐Ÿ–ผ, ๐Ÿšฅ ๐Ÿ‘† ๐Ÿ’ช ๐Ÿช โšซ๏ธ ๐Ÿ’ฝ.

๐Ÿ‘ˆ, FastAPI ๐Ÿšš jsonable_encoder() ๐Ÿ”ข.

โš™๏ธ jsonable_encoder

โžก๏ธ ๐ŸŒˆ ๐Ÿ‘ˆ ๐Ÿ‘† โœ”๏ธ ๐Ÿ’ฝ fake_db ๐Ÿ‘ˆ ๐Ÿ•ด ๐Ÿ“จ ๐ŸŽป ๐Ÿ”— ๐Ÿ’ฝ.

๐Ÿ–ผ, โšซ๏ธ ๐Ÿšซ ๐Ÿ“จ datetime ๐ŸŽš, ๐Ÿ‘ˆ ๐Ÿšซ ๐Ÿ”— โฎ๏ธ ๐ŸŽป.

, datetime ๐ŸŽš ๐Ÿ”œ โœ”๏ธ ๐Ÿ—œ str โš— ๐Ÿ’ฝ ๐Ÿ’พ ๐Ÿ“.

๐ŸŽ ๐ŸŒŒ, ๐Ÿ‘‰ ๐Ÿ’ฝ ๐Ÿšซ๐Ÿ”œ ๐Ÿ“จ Pydantic ๐Ÿท (๐ŸŽš โฎ๏ธ ๐Ÿ”ข), ๐Ÿ•ด dict.

๐Ÿ‘† ๐Ÿ’ช โš™๏ธ jsonable_encoder ๐Ÿ‘ˆ.

โšซ๏ธ ๐Ÿ“จ ๐ŸŽš, ๐Ÿ’– Pydantic ๐Ÿท, & ๐Ÿ“จ ๐ŸŽป ๐Ÿ”— โฌ:

from datetime import datetime
from typing import Union

from fastapi import FastAPI
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel

fake_db = {}


class Item(BaseModel):
    title: str
    timestamp: datetime
    description: Union[str, None] = None


app = FastAPI()


@app.put("/items/{id}")
def update_item(id: str, item: Item):
    json_compatible_item_data = jsonable_encoder(item)
    fake_db[id] = json_compatible_item_data
from datetime import datetime

from fastapi import FastAPI
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel

fake_db = {}


class Item(BaseModel):
    title: str
    timestamp: datetime
    description: str | None = None


app = FastAPI()


@app.put("/items/{id}")
def update_item(id: str, item: Item):
    json_compatible_item_data = jsonable_encoder(item)
    fake_db[id] = json_compatible_item_data

๐Ÿ‘‰ ๐Ÿ–ผ, โšซ๏ธ ๐Ÿ”œ ๐Ÿ—œ Pydantic ๐Ÿท dict, & datetime str.

๐Ÿ ๐Ÿค™ โšซ๏ธ ๐Ÿ•ณ ๐Ÿ‘ˆ ๐Ÿ’ช ๐Ÿ—œ โฎ๏ธ ๐Ÿ ๐Ÿฉ json.dumps().

โšซ๏ธ ๐Ÿšซ ๐Ÿ“จ โญ• str โš— ๐Ÿ’ฝ ๐ŸŽป ๐Ÿ“ (๐ŸŽป). โšซ๏ธ ๐Ÿ“จ ๐Ÿ ๐Ÿฉ ๐Ÿ’ฝ ๐Ÿ“Š (โœ… dict) โฎ๏ธ ๐Ÿ’ฒ & ๐ŸŽง-๐Ÿ’ฒ ๐Ÿ‘ˆ ๐ŸŒ ๐Ÿ”— โฎ๏ธ ๐ŸŽป.

Note

jsonable_encoder ๐Ÿค™ โš™๏ธ FastAPI ๐Ÿ”˜ ๐Ÿ—œ ๐Ÿ’ฝ. โœ‹๏ธ โšซ๏ธ โš  ๐Ÿ“š ๐ŸŽ ๐Ÿ˜.