python不能编组<class'teen.decimal'=“”>对象

时间:2015-08-15 07:48:04

标签: python

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

下面的代码在Python 2.6中有效,但现在它还没有用。

for

我的do_POST是:

OS: Centos 7
Python 2.7.5
Apache/2.4.6

错误是:

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)

1 个答案:

答案 0 :(得分:3)

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

您有两种选择:首先将Decimal对象转换为浮点数,或者扩展编组程序以明确处理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