あなたはフラスコを使用している場合、あなたはすでにUUID
を扱うflask.json
で定義された拡張JSONEncoderを持っていますが、ないDecimal
。これは、@ univerioの答えのようにjson_serializer
のparamとSQLAlchemyのエンジンにマップすることができます。
from flask import json
engine = create_engine(
app.config['SQLALCHEMY_DATABASE_URI'],
convert_unicode=True,
json_serializer=json.dumps,
)
あなたは、さらに次のようにdecimal.Decimal
をサポートするために、フラスコJSONEncoder
を拡張することができます
import decimal
from flask import json
class CustomJSONEncoder(json.JSONEncoder):
"""
Override Flask's JSONEncoder with the single method `default`, which
is called when the encoder doesn't know how to encode a specific type.
"""
def default(self, obj):
if type(obj) is decimal.Decimal:
return str(obj)
else:
# raises TypeError: obj not JSON serializable
return json.JSONEncoder.default(self, obj)
def init_json(app):
"""
Use custom JSON encoder with Flask
"""
app.json_encoder = CustomJSONEncoder
恐ろしいです。ドキュメントのその部分を逃した。明日それを試し、それに応じて答えを受け入れます。ありがとう!! –