Added encoding support for decimal objects

This commit is contained in:
default-303 2021-06-19 15:18:19 +05:30
parent 7161776824
commit dfc74d22f8
3 changed files with 10 additions and 1 deletions

View file

@ -6,7 +6,7 @@ Version 2.1.0
Unreleased Unreleased
- Update Click dependency to >= 8.0. - Update Click dependency to >= 8.0.
- Added support for Decimal objects in JSONEncoder
Version 2.0.2 Version 2.0.2
------------- -------------

View file

@ -1,3 +1,4 @@
import decimal
import io import io
import json as _json import json as _json
import typing as t import typing as t
@ -45,6 +46,8 @@ class JSONEncoder(_json.JSONEncoder):
overriding how basic types like ``str`` or ``list`` are overriding how basic types like ``str`` or ``list`` are
serialized, they are handled before this method. serialized, they are handled before this method.
""" """
if isinstance(o, decimal.Decimal):
return str(o)
if isinstance(o, date): if isinstance(o, date):
return http_date(o) return http_date(o)
if isinstance(o, uuid.UUID): if isinstance(o, uuid.UUID):

View file

@ -1,4 +1,5 @@
import datetime import datetime
import decimal
import io import io
import uuid import uuid
@ -9,6 +10,11 @@ import flask
from flask import json from flask import json
def test_json_encode_decimal():
decimal_ = decimal.Decimal(100)
assert flask.json.JSONEncoder().default(decimal_) == str(decimal_)
@pytest.mark.parametrize("debug", (True, False)) @pytest.mark.parametrize("debug", (True, False))
def test_bad_request_debug_message(app, client, debug): def test_bad_request_debug_message(app, client, debug):
app.config["DEBUG"] = debug app.config["DEBUG"] = debug