我在Python中对JSON的编码有问题,特别是十进制。十进制价值观。我用它来为googleappengine应用程序输出JSON。在
绕过Python中默认的json
模块的异常,告诉我它无法处理十进制。十进制对象,我正在使用此编码器子类:
class DecimalEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, decimal.Decimal):
return float(o)
return super(DecimalEncoder, self).default(o)
在其他应用程序中,这确实有效。在这种情况下,它没有。在经历了很多挫折之后,我发现这会产生奇怪的结果:
^{pr2}$人们会期望id是相同的,因为同一个类对象只在内存中驻留一次是有意义的。因为id不同,isinstance()
不起作用。在
会是那样吗十进制。十进制已经导入到其他地方,例如在App Engine和/或webapp2包中?在
下面的模块在我的系统(OSx 10.10、Python2.7.6、GAESDK1.9.20)上重现了这个错误。只需创建一个GAE应用程序并将其放入主.py公司名称:
import webapp2, decimal, json, MySQLdb, sys
class DecimalEncoder(json.JSONEncoder):
def default(self, o):
print id(decimal.Decimal)
print id(type(o))
if isinstance(o, decimal.Decimal):
return float(o)
return super(DecimalEncoder, self).default(o)
class MainHandler(webapp2.RequestHandler):
def get(self):
db = MySQLdb.connect(unix_socket='/var/mysql/mysql.sock', host='localhost', user='root', db='ssss', charset='utf8')
cursor = db.cursor(MySQLdb.cursors.DictCursor)
cursor.execute("SELECT id, price FROM product WHERE id = 1")
record = cursor.fetchone()
self.response.headers['Content-Type'] = 'application/json'
self.response.write(json.dumps(
record,
cls=DecimalEncoder,
indent=4,
separators=(',', ': ')
))
app = webapp2.WSGIApplication([
('/', MainHandler)
], debug=True)
数据库表:
CREATE TABLE `product` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`price` decimal(10,2) unsigned DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;
INSERT INTO product VALUES(0, 5.00);
看起来,
decimal.Decimal
类是在googleappenginesdk中的某个中修补的(或者模块被重新加载),这是在MySQL转换库导入decimal
和导入相同内容之间完成的。在幸运的是,我们可以通过更新MySQL转换表来解决这个问题:
就这样,上面的代码重置了MySQL类,JSON编码器类型检查成功。在
另一种方法是查找
^{pr2}$MySQLdb
正在使用的类:相关问题 更多 >
编程相关推荐