ExpatError: not well-formed (invalid token) when using SimpleXMLRPCServer caused by diacritic characters

ExpatError: not well-formed (invalid token) when using SimpleXMLRPCServer caused by diacritic characters

我花了很长时间才查明错误的具体原因。我正在编写一个简单的 XML RPC 服务器,它允许您进行目录列表和其他可能的只读操作。我已经做了一个简单的方法来列出所有文件夹和文件并将它们表示为字典:

def list_dir(self, dirname):
    """Returns list of files and directories as a dictionary, where key is name and values is either 'file' or 'dir'"""
    dirname = os.path.abspath(os.path.join(self.server.cwd,dirname))
    #Check that the path doesn't lead above 
    if dirname.find(self.server.cwd)==-1:
        raise SecurityError("There was an attempt to browse in %s wthich is above the root working directory %s."%(dirname, self.server.cwd))
    check_for_valid_directory(dirname)
    #Looping through directory
    files = [i for i in os.listdir(dirname)]
    #Create associative array
    result = {}
    #Iterate through files
    for f in files:
        fullpath = os.path.join(dirname, f)
        #Appending directories
        if os.path.isdir(fullpath):
            result[f] = "dir"
        else:
            result[f] = "file" 

    print "Sending data", result   
    return result

现在,当目录包含名为 Nová složka 的文件(或更确切地说是文件夹)时,客户端会收到错误信息,而不是所需的列表。当我删除有问题的文件名时,我收到了没有错误的数据。我不认为 Python 库有这个权利——要么参数转换应该完成,包括任何 unicode 的东西,要么根本不存在。

但是无论如何,我应该如何对 Python 库无法处理的数据进行编码?

您必须确保文件名和路径是 unicode 对象,并且所有文件名都使用正确的编码。最后一部分可能有点棘手,因为 POSIX 文件名是字节字符串,并且不需要分区上的所有文件名都必须使用相同的编码进行编码。在这种情况下,除了自己解码名称并以某种方式处理错误或 return 将文件名作为二进制数据而不是 (unicode) 字符串之外,您无能为力。

osos.path return unicode 字符串中的文件名相关函数,如果它们将 unicode 字符串作为参数。因此,如果您确保 dirnameunicode 类型而不是 str 类型,那么 os.listdir() 将 return 应该能够通过 [= 传输的 unicode 字符串23=]-RPC.