Skip to content

Support more object types #9

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Mar 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions TODO.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# TODO List

These below are from Issues or PRs in the original repository.

- Add ability to manually expire a cache entry
(<https://github.com/a-luna/fastapi-redis-cache/issues/63>)
- Add support for caching non-FastAPI functions
(<https://github.com/a-luna/fastapi-redis-cache/pull/66>)
- Take a look at other issues in the original repository to see if any need to be
added here.
39 changes: 29 additions & 10 deletions fastapi_redis_cache/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,12 @@
import json
from datetime import date, datetime
from decimal import Decimal
from typing import Any, Union
from enum import Enum
from typing import Any, Callable, Union
from uuid import UUID

from dateutil import parser
from pydantic import BaseModel

DATETIME_AWARE = "%m/%d/%Y %I:%M:%S %p %z"
DATE_ONLY = "%m/%d/%Y"
Expand All @@ -22,21 +25,37 @@
str(Decimal): Decimal,
}

HandlerType = Callable[[Any], Union[dict[str, str], str]]


class BetterJsonEncoder(json.JSONEncoder):
"""Subclass the JSONEncoder to handle more types."""

def default(self, obj: Any) -> Union[dict[str, str], Any]: # noqa: ANN401
"""Return a serializable object for the JSONEncoder to use."""
if isinstance(obj, datetime):
return {
"val": obj.strftime(DATETIME_AWARE),
"""Return a serializable object for the JSONEncoder to use.

This is re-written from the original code to handle more types, and not
end up with a mass of if-else and return statements.
"""
type_mapping: dict[type, HandlerType] = {
datetime: lambda o: {
"val": o.strftime(DATETIME_AWARE),
"_spec_type": str(datetime),
}
if isinstance(obj, date):
return {"val": obj.strftime(DATE_ONLY), "_spec_type": str(date)}
if isinstance(obj, Decimal):
return {"val": str(obj), "_spec_type": str(Decimal)}
},
date: lambda o: {
"val": o.strftime(DATE_ONLY),
"_spec_type": str(date),
},
Decimal: lambda o: {"val": str(o), "_spec_type": str(Decimal)},
BaseModel: lambda o: o.model_dump(),
UUID: lambda o: str(o),
Enum: lambda o: str(o.value),
}

for obj_type, handler in type_mapping.items():
if isinstance(obj, obj_type):
return handler(obj)

return super().default(obj)


Expand Down
4 changes: 0 additions & 4 deletions fastapi_redis_cache/version.py

This file was deleted.

2 changes: 1 addition & 1 deletion requirements-dev.txt
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ pydantic-extra-types==2.6.0 ; python_version >= "3.9" and python_version < "4.0"
pydantic-settings==2.2.1 ; python_version >= "3.9" and python_version < "4.0"
pydantic==2.6.4 ; python_version >= "3.9" and python_version < "4.0"
pyfakefs==5.3.5 ; python_version >= "3.9" and python_version < "4.0"
pymarkdownlnt==0.9.17 ; python_version >= "3.9" and python_version < "4.0"
pymarkdownlnt==0.9.18 ; python_version >= "3.9" and python_version < "4.0"
pytest-asyncio==0.21.1 ; python_version >= "3.9" and python_version < "4.0"
pytest-cov==4.1.0 ; python_version >= "3.9" and python_version < "4.0"
pytest-env==1.1.3 ; python_version >= "3.9" and python_version < "4.0"
Expand Down