python 无法编码(marshal) <class 'decimal.Decimal' > 对象

标签 python

我将我的操作系统更新到 Centos 7。现在我有 Python 2.7。

下面的代码在 Python 2.6 中可以工作,但现在不工作了。

OS: Centos 7
Python 2.7.5
Apache/2.4.6

我的 do_POST 是:

def do_POST(self):
    """Handles the HTTP POST request.

    Attempts to interpret all HTTP POST requests as XML-RPC calls,
    which are forwarded to the _dispatch method for handling.
    """

    try:
        # get arguments
        data = self.rfile.read(int(self.headers["content-length"]))
        params, method = xmlrpclib.loads(data)

        # generate response
        try:
            response = self._dispatch(method, params)
            # wrap response in a singleton tuple
            response = (response,)
        except XMLRPCFault:
            # report exception back to server
            response = xmlrpclib.dumps(
                xmlrpclib.Fault(1, "%s" % (sys.exc_info()[1]))
                )
        else:
            response = xmlrpclib.dumps(response, methodresponse=1)
    except:
        logException(LOG_ERROR,"XMLRPCServer")
        # internal error, report as HTTP server error
        self.send_response(500)
        self.end_headers()
    else:
        # got a valid XML RPC response
        self.send_response(200)
        self.send_header("Content-type", "text/xml")
        self.send_header("Content-length", str(len(response)))
        self.end_headers()
        self.wfile.write(response)

        # shut down the connection
        self.wfile.flush()
        self.connection.shutdown(1)

错误是:

2015/08/15-11:49:36 XMLRPCServer
Traceback (most recent call last):
  File "/usr/local/IBSng/core/server/xmlrpcserver.py", line 53, in do_POST
    response = xmlrpclib.dumps(response, methodresponse=1)
  File "/usr/lib64/python2.7/xmlrpclib.py", line 1085, in dumps
    data = m.dumps(params)
  File "/usr/lib64/python2.7/xmlrpclib.py", line 632, in dumps
    dump(v, write)
  File "/usr/lib64/python2.7/xmlrpclib.py", line 654, in __dump
    f(self, value, write)
  File "/usr/lib64/python2.7/xmlrpclib.py", line 735, in dump_struct
    dump(v, write)
  File "/usr/lib64/python2.7/xmlrpclib.py", line 654, in __dump
    f(self, value, write)
  File "/usr/lib64/python2.7/xmlrpclib.py", line 735, in dump_struct
    dump(v, write)
  File "/usr/lib64/python2.7/xmlrpclib.py", line 654, in __dump
    f(self, value, write)
  File "/usr/lib64/python2.7/xmlrpclib.py", line 735, in dump_struct
    dump(v, write)
  File "/usr/lib64/python2.7/xmlrpclib.py", line 646, in __dump
    raise TypeError, "cannot marshal %s objects" % type(value)
TypeError: cannot marshal <class 'decimal.Decimal'> objects

最佳答案

xmlrpclib 模块不支持开箱即用的 decimal.Decimal 对象,不。

您有两个选择:首先将 Decimal 对象转换为 float ,或者扩展编码器以显式处理 Decimal 对象。

转换 Decimal 对象很简单:

from decimal import Decimal

# ..
def convert_decimal_to_float(ob):
    if isinstance(ob, Decimal):
        return float(ob)
    if isinstance(ob, (tuple, list)):
        return [convert_decimal_to_float(v) for v in ob]
    if isinstance(ob, dict):
        return {k: convert_decimal_to_float(v) for k, v in ob.iteritems()}
    return ob

response = self._dispatch(method, params)
response = (convert_decimal_to_float(response),)

向库添加支持如下所示:

from xmlrpclib import Marshaller
from decimal import Decimal

def dump_decimal(self, value, write):
    write("<value><double>")
    write(str(value))
    write("</double></value>\n")

Marshaller.dispatch[Decimal] = dump_decimal

关于python 无法编码(marshal) <class 'decimal.Decimal' > 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32022656/

相关文章:

python:将数据框更新到现有的Excel工作表而不覆盖同一张纸和其他工作表上的内容

python - Numpy:我应该使用 newaxis 还是 None?

python - 在函数之间使用用户输入时遇到问题

python - mysqldb 不写入数据库

检查整数是否适合 64 位的 Pythonic 方法

python - tf.nn_conv2d 和 tf.nn.depthwise_conv2d 之间的区别

python - 图片不显示在网页上(Django)

python - 如何在没有函数的情况下将 executor.map 应用于 for 循环?

python - Django-registration user_activated信号发送两次

Python - 对大文件的小改动