From c3be2eca192812440dbbbcda7dbecd6d913c4f9b Mon Sep 17 00:00:00 2001 From: long2ice Date: Sat, 9 Oct 2021 16:51:05 +0800 Subject: [PATCH] Fix default json coder for datetime. --- CHANGELOG.md | 4 ++++ examples/main.py | 14 ++++++++++++++ fastapi_cache/coder.py | 9 +++------ pyproject.toml | 2 +- 4 files changed, 22 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8458787..a4207d5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## 0.1 +### 0.1.7 + +- Fix default json coder for datetime. + ### 0.1.6 - Fix redis cache. diff --git a/examples/main.py b/examples/main.py index 9afcf8a..010496e 100644 --- a/examples/main.py +++ b/examples/main.py @@ -1,3 +1,5 @@ +from datetime import date, datetime + import aioredis import uvicorn from fastapi import FastAPI @@ -31,6 +33,18 @@ async def clear(): return await FastAPICache.clear(namespace="test") +@app.get("/date") +@cache(namespace="test", expire=20) +async def get_data(request: Request, response: Response): + return date.today() + + +@app.get("/datetime") +@cache(namespace="test", expire=20) +async def get_datetime(request: Request, response: Response): + return datetime.now() + + @app.on_event("startup") async def startup(): redis = aioredis.from_url(url="redis://localhost") diff --git a/fastapi_cache/coder.py b/fastapi_cache/coder.py index 6c27b92..a86b95f 100644 --- a/fastapi_cache/coder.py +++ b/fastapi_cache/coder.py @@ -8,7 +8,7 @@ import pendulum from fastapi.encoders import jsonable_encoder CONVERTERS = { - "date": pendulum.parse, + "date": lambda x: pendulum.parse(x, exact=True), "datetime": lambda x: pendulum.parse(x, exact=True), "decimal": Decimal, } @@ -17,12 +17,9 @@ CONVERTERS = { class JsonEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, datetime.datetime): - if obj.tzinfo: - return {"val": obj.strftime("%Y-%m-%d %H:%M:%S%z"), "_spec_type": "datetime"} - else: - return {"val": obj.strftime("%Y-%m-%d %H:%M:%S"), "_spec_type": "datetime"} + return {"val": str(obj), "_spec_type": "datetime"} elif isinstance(obj, datetime.date): - return {"val": obj.strftime("%Y-%m-%d"), "_spec_type": "date"} + return {"val": str(obj), "_spec_type": "date"} elif isinstance(obj, Decimal): return {"val": str(obj), "_spec_type": "decimal"} else: diff --git a/pyproject.toml b/pyproject.toml index bb0db2b..4e406f9 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "fastapi-cache2" -version = "0.1.6" +version = "0.1.7" description = "Cache for FastAPI" authors = ["long2ice "] license = "Apache-2.0"