Post

FastAPI 공식문서 따라하기[24] - JSON Compatible Encoder

https://fastapi.tiangolo.com/tutorial/encoder/ 공식문서 따라하는 글

☑️ JSON Compatible Encoder¶

어떤한 데이터를 JSON로 바꿔야할 때가 있을 것이다.

FastAPIjsonable_encoder()를 제공하여 손쉽게 JSON변환을 도와준다.

☑️ Using the jsonable_encoder

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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):
    print("original item : ",type(item), "original datetime : ", type(item.timestamp))
    # original item :  <class 'main.Item'> original datetime :  <class 'datetime.datetime'>
    json_compatible_item_data = jsonable_encoder(item)
    print("convert item : ",type(json_compatible_item_data), "convert datetime : ",type(json_compatible_item_data['timestamp']))
    # convert item :  <class 'dict'> convert datetime :  <class 'str'>
    fake_db[id] = json_compatible_item_data
    return fake_db[id]

만약 db가 JSON객체만을 받고 요청을 받아서 객체를 넣는다고 할 때 사용하면 좋다.

저렇게 하면 좋은점이 뭘까?

먼저 저 Item안에 있는 timestampdatetime타입이다. 이를 DB에 넣는데에는 위험이 있다.

또한 Pydantic model타입의 Item도 바로 넣는건 위험하다.

그렇기에 위의 구문을 통해 변환을 하면 자동으로 Pydantic modeldict으로, datetimestr로 변환해주어 데이터를 넣어주도록 한다.

This post is licensed under CC BY 4.0 by the author.