Movatterモバイル変換


[0]ホーム

URL:


Ana içeriğe geç
Join theFastAPI Cloud waiting list 🚀
Follow@fastapi onX (Twitter) to stay updated
FollowFastAPI onLinkedIn to stay updated
Subscribe to theFastAPI and friends newsletter 🎉
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor

Encoders -jsonable_encoder

fastapi.encoders.jsonable_encoder

jsonable_encoder(obj,include=None,exclude=None,by_alias=True,exclude_unset=False,exclude_defaults=False,exclude_none=False,custom_encoder=None,sqlalchemy_safe=True,)

Convert any object to something that can be encoded in JSON.

This is used internally by FastAPI to make sure anything you return can beencoded as JSON before it is sent to the client.

You can also use it yourself, for example to convert objects before saving themin a database that supports only JSON.

Read more about it in theFastAPI docs for JSON Compatible Encoder.

PARAMETERDESCRIPTION
obj

The input object to convert to JSON.

TYPE:Any

include

Pydantic'sinclude parameter, passed to Pydantic models to set thefields to include.

TYPE:IncEx | NoneDEFAULT:None

exclude

Pydantic'sexclude parameter, passed to Pydantic models to set thefields to exclude.

TYPE:IncEx | NoneDEFAULT:None

by_alias

Pydantic'sby_alias parameter, passed to Pydantic models to define ifthe output should use the alias names (when provided) or the Pythonattribute names. In an API, if you set an alias, it's probably because youwant to use it in the result, so you probably want to leave this set toTrue.

TYPE:boolDEFAULT:True

exclude_unset

Pydantic'sexclude_unset parameter, passed to Pydantic models to defineif it should exclude from the output the fields that were not explicitlyset (and that only had their default values).

TYPE:boolDEFAULT:False

exclude_defaults

Pydantic'sexclude_defaults parameter, passed to Pydantic models to defineif it should exclude from the output the fields that had the same defaultvalue, even when they were explicitly set.

TYPE:boolDEFAULT:False

exclude_none

Pydantic'sexclude_none parameter, passed to Pydantic models to defineif it should exclude from the output any fields that have aNone value.

TYPE:boolDEFAULT:False

custom_encoder

Pydantic'scustom_encoder parameter, passed to Pydantic models to definea custom encoder.

TYPE:dict[Any,Callable[[Any],Any]] | NoneDEFAULT:None

sqlalchemy_safe

Exclude from the output any fields that start with the name_sa.

This is mainly a hack for compatibility with SQLAlchemy objects, theystore internal SQLAlchemy-specific state in attributes named with_sa,and those objects can't (and shouldn't be) serialized to JSON.

TYPE:boolDEFAULT:True

Source code infastapi/encoders.py
112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
defjsonable_encoder(obj:Annotated[Any,Doc("""            The input object to convert to JSON.            """),],include:Annotated[IncEx|None,Doc("""            Pydantic's `include` parameter, passed to Pydantic models to set the            fields to include.            """),]=None,exclude:Annotated[IncEx|None,Doc("""            Pydantic's `exclude` parameter, passed to Pydantic models to set the            fields to exclude.            """),]=None,by_alias:Annotated[bool,Doc("""            Pydantic's `by_alias` parameter, passed to Pydantic models to define if            the output should use the alias names (when provided) or the Python            attribute names. In an API, if you set an alias, it's probably because you            want to use it in the result, so you probably want to leave this set to            `True`.            """),]=True,exclude_unset:Annotated[bool,Doc("""            Pydantic's `exclude_unset` parameter, passed to Pydantic models to define            if it should exclude from the output the fields that were not explicitly            set (and that only had their default values).            """),]=False,exclude_defaults:Annotated[bool,Doc("""            Pydantic's `exclude_defaults` parameter, passed to Pydantic models to define            if it should exclude from the output the fields that had the same default            value, even when they were explicitly set.            """),]=False,exclude_none:Annotated[bool,Doc("""            Pydantic's `exclude_none` parameter, passed to Pydantic models to define            if it should exclude from the output any fields that have a `None` value.            """),]=False,custom_encoder:Annotated[dict[Any,Callable[[Any],Any]]|None,Doc("""            Pydantic's `custom_encoder` parameter, passed to Pydantic models to define            a custom encoder.            """),]=None,sqlalchemy_safe:Annotated[bool,Doc("""            Exclude from the output any fields that start with the name `_sa`.            This is mainly a hack for compatibility with SQLAlchemy objects, they            store internal SQLAlchemy-specific state in attributes named with `_sa`,            and those objects can't (and shouldn't be) serialized to JSON.            """),]=True,)->Any:"""    Convert any object to something that can be encoded in JSON.    This is used internally by FastAPI to make sure anything you return can be    encoded as JSON before it is sent to the client.    You can also use it yourself, for example to convert objects before saving them    in a database that supports only JSON.    Read more about it in the    [FastAPI docs for JSON Compatible Encoder](https://fastapi.tiangolo.com/tutorial/encoder/).    """custom_encoder=custom_encoderor{}ifcustom_encoder:iftype(obj)incustom_encoder:returncustom_encoder[type(obj)](obj)else:forencoder_type,encoder_instanceincustom_encoder.items():ifisinstance(obj,encoder_type):returnencoder_instance(obj)ifincludeisnotNoneandnotisinstance(include,(set,dict)):include=set(include)# type: ignore[assignment]ifexcludeisnotNoneandnotisinstance(exclude,(set,dict)):exclude=set(exclude)# type: ignore[assignment]ifisinstance(obj,BaseModel):obj_dict=obj.model_dump(mode="json",include=include,exclude=exclude,by_alias=by_alias,exclude_unset=exclude_unset,exclude_none=exclude_none,exclude_defaults=exclude_defaults,)returnjsonable_encoder(obj_dict,exclude_none=exclude_none,exclude_defaults=exclude_defaults,sqlalchemy_safe=sqlalchemy_safe,)ifdataclasses.is_dataclass(obj):assertnotisinstance(obj,type)obj_dict=dataclasses.asdict(obj)returnjsonable_encoder(obj_dict,include=include,exclude=exclude,by_alias=by_alias,exclude_unset=exclude_unset,exclude_defaults=exclude_defaults,exclude_none=exclude_none,custom_encoder=custom_encoder,sqlalchemy_safe=sqlalchemy_safe,)ifisinstance(obj,Enum):returnobj.valueifisinstance(obj,PurePath):returnstr(obj)ifisinstance(obj,(str,int,float,type(None))):returnobjifisinstance(obj,PydanticUndefinedType):returnNoneifisinstance(obj,dict):encoded_dict={}allowed_keys=set(obj.keys())ifincludeisnotNone:allowed_keys&=set(include)ifexcludeisnotNone:allowed_keys-=set(exclude)forkey,valueinobj.items():if((notsqlalchemy_safeor(notisinstance(key,str))or(notkey.startswith("_sa")))and(valueisnotNoneornotexclude_none)andkeyinallowed_keys):encoded_key=jsonable_encoder(key,by_alias=by_alias,exclude_unset=exclude_unset,exclude_none=exclude_none,custom_encoder=custom_encoder,sqlalchemy_safe=sqlalchemy_safe,)encoded_value=jsonable_encoder(value,by_alias=by_alias,exclude_unset=exclude_unset,exclude_none=exclude_none,custom_encoder=custom_encoder,sqlalchemy_safe=sqlalchemy_safe,)encoded_dict[encoded_key]=encoded_valuereturnencoded_dictifisinstance(obj,(list,set,frozenset,GeneratorType,tuple,deque)):encoded_list=[]foriteminobj:encoded_list.append(jsonable_encoder(item,include=include,exclude=exclude,by_alias=by_alias,exclude_unset=exclude_unset,exclude_defaults=exclude_defaults,exclude_none=exclude_none,custom_encoder=custom_encoder,sqlalchemy_safe=sqlalchemy_safe,))returnencoded_listiftype(obj)inENCODERS_BY_TYPE:returnENCODERS_BY_TYPE[type(obj)](obj)forencoder,classes_tupleinencoders_by_class_tuples.items():ifisinstance(obj,classes_tuple):returnencoder(obj)ifis_pydantic_v1_model_instance(obj):raisePydanticV1NotSupportedError("pydantic.v1 models are no longer supported by FastAPI."f" Please update the model{obj!r}.")try:data=dict(obj)exceptExceptionase:errors:list[Exception]=[]errors.append(e)try:data=vars(obj)exceptExceptionase:errors.append(e)raiseValueError(errors)fromereturnjsonable_encoder(data,include=include,exclude=exclude,by_alias=by_alias,exclude_unset=exclude_unset,exclude_defaults=exclude_defaults,exclude_none=exclude_none,custom_encoder=custom_encoder,sqlalchemy_safe=sqlalchemy_safe,)

[8]ページ先頭

©2009-2026 Movatter.jp