pyeve / eve-sqlalchemy

SQLAlchemy data layer for Eve-powered RESTful APIs
http://eve-sqlalchemy.readthedocs.io
Other
232 stars 70 forks source link

Error: TypeError: Decimal('0.00') is not JSON serializable #50

Closed terrysclaw closed 9 years ago

terrysclaw commented 9 years ago

I get an error when trying to PATCH an object which has a decimal field like this:

CREATE TABLE package ( id int(11) NOT NULL AUTO_INCREMENT, created_ts timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', updated_ts timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, etag varchar(45) DEFAULT NULL, length decimal(20,2) DEFAULT '0.00', width decimal(20,2) DEFAULT '0.00', height decimal(20,2) DEFAULT '0.00',

class Package(CommonColumns): tablename = 'package' length = Column(Numeric(20, 2), default=0.00) width = Column(Numeric(20, 2), default=0.00) height = Column(Numeric(20, 2), default=0.00)

File "C:\Python27\Lib\json\encoder.py", line 184, in default raise TypeError(repr(o) + " is not JSON serializable")

TypeError: Decimal('0.00') is not JSON serializable

terrysclaw commented 9 years ago

when I change the column type from Numeric(20, 2) to DECIMAL(asdecimal=False). It has fixed the problem.

class Package(CommonColumns): tablename = 'package' length = Column(DECIMAL(asdecimal=False), default=0.00) width = Column(DECIMAL(asdecimal=False), default=0.00) height = Column(DECIMAL(asdecimal=False), default=0.00) weight = Column(DECIMAL(asdecimal=False), default=0.00)

amleczko commented 9 years ago

the problem is related to default python json serializer. It doesn't support decimal. Please check http://stackoverflow.com/questions/1960516/python-json-serialize-a-decimal-object. Your suggestion to use asdecimal=False should fix the problem in most of the cases.