xmlrpclib:字典键必须是字符串类型错误

时间:2011-08-09 13:03:52

标签: python unicode dictionary xmlrpclib

我想要一些建议。我在Python 2.6中遇到以下错误:

Traceback (most recent call last):
  File "<pyshell#20>", line 1, in <module>
    s.Search(query)
  File "/usr/lib/python2.6/xmlrpclib.py", line 1199, in __call__
  return self.__send(self.__name, args)
  File "/usr/lib/python2.6/xmlrpclib.py", line 1489, in __request
  verbose=self.__verbose
  File "/usr/lib/python2.6/xmlrpclib.py", line 1253, in request
  return self._parse_response(h.getfile(), sock)
  File "/usr/lib/python2.6/xmlrpclib.py", line 1392, in _parse_response
  return u.close()
  File "/usr/lib/python2.6/xmlrpclib.py", line 838, in close
  raise Fault(**self._stack[0])
  Fault: <Fault 1: "<type 'exceptions.TypeError'>:dictionary key must be string">

我的代码正在使用Django提供迷你搜索引擎的一部分。在Python 3中,一切都像梦一样,但Django不适用于Python 3,所以我需要回溯我的代码,这是问题的来源。

我的代码(client.py):

# -*- coding: utf-8 -*-
from __future__ import unicode_literals # This was suggested elsewhere
import xmlrpclib

s = xmlrpclib.ServerProxy('http://localhost:11210')
data = s.Search('מלאכא') # tried prefixing with 'u'
print data

我的代码(Server.py):

# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import pickle, sys, xmlrpclib
from SimpleXMLRPCServer import SimpleXMLRPCServer
from SimpleXMLRPCServer import SimpleXMLRPCRequestHandler
from collections import defaultdict

docscores = pickle.load(open("docscores.pkl", "rb"))
print ("Everything loaded. No errors.")

# Restrict to a particular path.
class RequestHandler(SimpleXMLRPCRequestHandler):
    rpc_paths = ('/RPC2',)

# Create server
server = SimpleXMLRPCServer(("localhost", 11210), requestHandler=RequestHandler)

server.register_introspection_functions()

def Search(query):
    results = docscores[query]
    return results

server.register_function(Search, 'Search')

# Run the server's main loop
server.serve_forever()

正如您所看到的那样非常简单,但是当从客户端解析到服务器的unicode字符串时,我得到'字典键必须是字符串'。但是,服务器似乎很高兴并产生以下反馈,这表明它已经访问了我的pickle字典(返回一个doc号和ngram的计数):

{160: 3, 417: 1, 35: 1, 133: 1, 376: 1, 193: 1, 380: 1, 363: 1, 364: 1, 126: 1, 47: 1, 145: 1, 147: 1, 382: 1, 246: 3, 121: 4, 440: 1, 441: 1, 444: 1, 280: 1}
 localhost.localdomain - - [09/Aug/2011 13:32:23] "POST /RPC2 HTTP/1.0" 200 -

如果我这样做:    类型(查询) 结果是:
   

我还尝试了reload(sys),前缀为u'unicode_string'u"".join(unicode_string)query。decode('utf-8')`,但仍然出现此错误,或最终导致与unicode / ascii解码相关的更多错误。

有没有人有任何想法如何解决这个错误?或者是否有XMLPRPCServer替代服务器实例和Python 2.6中的客户端之间的数据?

非常感谢提前。

1 个答案:

答案 0 :(得分:5)

xmlrpclib的文档指出,对于要通过XML编组的python字典,键应该是字符串:

  

Python字典。键必须是字符串,值可以是任何值   符合类型。可以传入用户定义类的对象;   只传输 dict 属性。

因此,您应该更改服务器搜索方法以返回包含字符串作为键的字典:

def Search(query):
    results = docscores[query]
    # I believe results is now a dictionary in the form {<integer>: <integer>}
    return dict((str(key), value) for key, value in results.items())