Mar*_*tyn 3 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">
Run Code Online (Sandbox Code Playgroud)
我的代码是使用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
Run Code Online (Sandbox Code Playgroud)
我的代码(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()
Run Code Online (Sandbox Code Playgroud)
正如您所看到的那样非常简单,但是当从客户端解析到服务器的unicode字符串时,我得到'字典键必须是字符串'.但是,服务器似乎很高兴并产生以下反馈,这表明它已访问我的pickle字典(返回文档编号和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 -
Run Code Online (Sandbox Code Playgroud)
如果我这样做:输入(查询)结果是:
我也试过reload(sys),前缀u'unicode_string',u"".join(unicode_string)和query.decode('utf-8')`,但仍然得到这个错误,或者最终得到更多与unicode/ascii解码有关的错误.
有没有人有任何想法如何解决这个错误?或者是否有XMLPRPCServer的替代方法,用于在Python 2.6中的服务器实例和客户端之间提供数据?
提前谢谢了.
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())
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4020 次 |
| 最近记录: |