mirror of
https://github.com/long2ice/fastapi-cache.git
synced 2026-03-25 04:57:54 +00:00
feat: add more type hints
This commit is contained in:
@@ -2,7 +2,7 @@ import datetime
|
||||
import json
|
||||
import pickle # nosec:B403
|
||||
from decimal import Decimal
|
||||
from typing import Any
|
||||
from typing import Any, Dict, Union
|
||||
|
||||
import pendulum
|
||||
from fastapi.encoders import jsonable_encoder
|
||||
@@ -15,7 +15,7 @@ CONVERTERS = {
|
||||
|
||||
|
||||
class JsonEncoder(json.JSONEncoder):
|
||||
def default(self, obj):
|
||||
def default(self, obj: Any) -> Any:
|
||||
if isinstance(obj, datetime.datetime):
|
||||
return {"val": str(obj), "_spec_type": "datetime"}
|
||||
elif isinstance(obj, datetime.date):
|
||||
@@ -26,42 +26,42 @@ class JsonEncoder(json.JSONEncoder):
|
||||
return jsonable_encoder(obj)
|
||||
|
||||
|
||||
def object_hook(obj):
|
||||
def object_hook(obj: Any) -> Any:
|
||||
_spec_type = obj.get("_spec_type")
|
||||
if not _spec_type:
|
||||
return obj
|
||||
|
||||
if _spec_type in CONVERTERS:
|
||||
return CONVERTERS[_spec_type](obj["val"])
|
||||
return CONVERTERS[_spec_type](obj["val"]) # type: ignore
|
||||
else:
|
||||
raise TypeError("Unknown {}".format(_spec_type))
|
||||
|
||||
|
||||
class Coder:
|
||||
@classmethod
|
||||
def encode(cls, value: Any):
|
||||
def encode(cls, value: Any) -> Union[str, bytes]:
|
||||
raise NotImplementedError
|
||||
|
||||
@classmethod
|
||||
def decode(cls, value: Any):
|
||||
def decode(cls, value: Any) -> Any:
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
class JsonCoder(Coder):
|
||||
@classmethod
|
||||
def encode(cls, value: Any):
|
||||
def encode(cls, value: Any) -> str:
|
||||
return json.dumps(value, cls=JsonEncoder)
|
||||
|
||||
@classmethod
|
||||
def decode(cls, value: Any):
|
||||
def decode(cls, value: Any) -> str:
|
||||
return json.loads(value, object_hook=object_hook)
|
||||
|
||||
|
||||
class PickleCoder(Coder):
|
||||
@classmethod
|
||||
def encode(cls, value: Any):
|
||||
def encode(cls, value: Any) -> Union[str, bytes]:
|
||||
return pickle.dumps(value)
|
||||
|
||||
@classmethod
|
||||
def decode(cls, value: Any):
|
||||
def decode(cls, value: Any) -> Any:
|
||||
return pickle.loads(value) # nosec:B403,B301
|
||||
|
||||
Reference in New Issue
Block a user