我想要一些建议。我曾经遇到过在Python 2.6以下错误:xmlrpclib:字典键必须是字符串类型错误
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字符串到服务器时是'字符串'。但是,服务器似乎很开心,并产生下列反馈,这表明它已经访问我的腌字典(返回的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解码。
有没有人有任何想法我可以解决这个错误?或者,在Python 2.6中,是否有替代XMLPRPCServer的服务器实例和客户端之间的数据服务?
非常感谢提前。
谢谢@mouad,即解决了这个问题,我是从服务器错误的一边接近它。也非常感谢您的快速响应! :-) – Martyn
@Martyn:很高兴有帮助: - – mouad