JSON Uyumlu Encoder¶
🌐 Translation by AI and humans
This translation was made by AI guided by humans. 🤝
It could have mistakes of misunderstanding the original meaning, or looking unnatural, etc. 🤖
You can improve this translation by helping us guide the AI LLM better.
Bazı durumlarda, bir veri tipini (örneğin bir Pydantic model) JSON ile uyumlu bir şeye (örneğin dict, list vb.) dönüştürmeniz gerekebilir.
Örneğin, bunu bir veritabanında saklamanız gerekiyorsa.
Bunun için FastAPI, jsonable_encoder() fonksiyonunu sağlar.
jsonable_encoder Kullanımı¶
Yalnızca JSON ile uyumlu veri kabul eden bir veritabanınız olduğunu düşünelim: fake_db.
Örneğin bu veritabanı, JSON ile uyumlu olmadıkları için datetime objelerini kabul etmez.
Dolayısıyla bir datetime objesinin, ISO formatında veriyi içeren bir str'e dönüştürülmesi gerekir.
Aynı şekilde bu veritabanı bir Pydantic model'i (attribute'lara sahip bir obje) de kabul etmez; yalnızca bir dict kabul eder.
Bunun için jsonable_encoder kullanabilirsiniz.
Bir Pydantic model gibi bir obje alır ve JSON ile uyumlu bir versiyonunu döndürür:
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
🤓 Other versions and variants
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
Bu örnekte, Pydantic model'i bir dict'e, datetime'ı da bir str'e dönüştürür.
Bu fonksiyonun çağrılmasıyla elde edilen sonuç, Python standardındaki json.dumps() ile encode edilebilecek bir şeydir.
JSON formatında (string olarak) veriyi içeren büyük bir str döndürmez. Bunun yerine, tüm değerleri ve alt değerleri JSON ile uyumlu olacak şekilde, Python’un standart bir veri yapısını (örneğin bir dict) döndürür.
Not
jsonable_encoder, aslında FastAPI tarafından veriyi dönüştürmek için internal olarak kullanılır. Ancak birçok farklı senaryoda da oldukça faydalıdır.