FastAPI uses ENCODERS_BY_TYPE (from pydantic.json) to encode some basic data type.
ENCODERS_BY_TYPE: Dict[Type[Any], Callable[[Any], Any]] = {
bytes: lambda o: o.decode(),
Color: str,
datetime.date: isoformat,
datetime.datetime: isoformat,
datetime.time: isoformat,
datetime.timedelta: lambda td: td.total_seconds(),
Decimal: decimal_encoder,
Enum: lambda o: o.value,
so for me to override the default datetime encode, just like
ENCODERS_BY_TYPE[datetime] = lambda date_obj: date_obj.strftime("%Y-%m-%d %H:%M:%S")
Answer from coder vx on Stack OverflowFastAPI uses ENCODERS_BY_TYPE (from pydantic.json) to encode some basic data type.
ENCODERS_BY_TYPE: Dict[Type[Any], Callable[[Any], Any]] = {
bytes: lambda o: o.decode(),
Color: str,
datetime.date: isoformat,
datetime.datetime: isoformat,
datetime.time: isoformat,
datetime.timedelta: lambda td: td.total_seconds(),
Decimal: decimal_encoder,
Enum: lambda o: o.value,
so for me to override the default datetime encode, just like
ENCODERS_BY_TYPE[datetime] = lambda date_obj: date_obj.strftime("%Y-%m-%d %H:%M:%S")
Right now I am using custom encoder within json.dumps like this:
class TestEncoder(JSONEncoder):
def default(self, obj):
if isinstance(obj, EnumTestT):
return TestEncoder.process_enum_test_t(obj)
and response within the FastAPI app would be:
json_str = json.dumps(json_list, cls=TestEncoder).encode('utf-8')
return Response(media_type="application/json", content=json_str)
The problem with FastAPI using custom encoders is that custom encoder is invoked after all the standard encoders have been invoked and there is no way to override that order.
fastapi - reportMissingImports Python error but import works fine - Stack Overflow
Cannot import ENCODERS_BY_TYPE
python - ImportError: cannot import name 'FastAPI' from partially initialized module 'fastapi' : circular import - Stack Overflow
FastAPI ignores json_encoders in the Model
The causes could be:
- The name of the file -
fastapi.py, if you name it in this could way you would get import errors. (Avoid filenames similar to package names) - Installing on other environments. Most of the time it happens when you use both
CondaandPiPon you system. - If you run the code from VS Code, check if the
same interpreteris selected.
Verify the installation:
$ pip list | grep fastapi
Suggestions:
OPT Virtual Environments to avoid these troubles.
Thank you!
Addtional, don't forget using LazyVim extra Python config.
I have the same question when using LazyVim, the solution is venv.
python3 -m venv .venv
source .venv/bin/activate
pip install fastapi
After these commands, the fastapi is correctly imported with LSP.
