我想要一些建议。我在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提供了一个迷你搜索引擎的一部分。在Python3中,一切都像梦一样运行,但是Django在Python3中不可用,所以我需要回溯我的代码,这就是问题的来源。
我的代码(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 -如果我这样做: type(query),结果是:
我还尝试了reload(sys)、前缀u'unicode_string'、u"".join(unicode_string)和query.decode('utf-8')`,但仍然收到此错误,或者最终出现更多与unicode/ascii解码相关的错误。
有没有人知道我该如何避免这个错误?或者,在Python2.6中,有没有XMLPRPCServer的替代方案用于在服务器实例和客户端之间提供数据?
在此之前,非常感谢您。
发布于 2011-08-09 21:12:24
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())https://stackoverflow.com/questions/6996585
复制相似问题