2011-08-09 102 views
2

我想要一些建議。我曾經遇到過在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的服務器實例和客戶端之間的數據服務?

非常感謝提前。

回答

4

xmlrpclib狀態,對於通過XML編組Python字典的鍵應該是字符串的文檔:

Python字典。密鑰必須是字符串,值可以是任何適合的類型。用戶定義的類的對象可以傳入; 只有它們的字典屬性被傳輸。

所以,你應該改變你的服務器的搜索方法返回一個字典,字符串作爲鍵:

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()) 
+0

謝謝@mouad,即解決了這個問題,我是從服務器錯誤的一邊接近它。也非常感謝您的快速響應! :-) – Martyn

+0

@Martyn:很高興有幫助: - – mouad

相關問題