简体   繁体   English

尝试上传具有unicode内容的XML时,Python ftplib UnicodeEncodeError

[英]Python ftplib UnicodeEncodeError when trying to upload an XML with unicode content

I am trying to upload an XML with unicode content to a FTP server using ftplib, but getting the following exception when I try to upload the using storbinary method. 我正在尝试使用ftplib将具有Unicode内容的XML上载到FTP服务器,但是当我尝试使用storbinary方法上载时出现以下异常。 The XML data is properly encoded to unicode (utf-8), I have made sure of that, I am not sure as to why storbinary is trying to encode it to 'ascii' while uploading. XML数据已正确编码为unicode(utf-8),我已经确定了这一点,我不确定为什么storbinary试图在上传时将其编码为“ ascii”。 Can anyone please help? 谁能帮忙吗?

--> 429         ftp.storbinary("STOR file.xml", xml)
    430 
    431     def run(self):

/usr/lib/python2.7/ftplib.pyc in storbinary(self, cmd, fp, blocksize, callback, rest)
    463             buf = fp.read(blocksize)
    464             if not buf: break
--> 465             conn.sendall(buf)
    466             if callback: callback(buf)
    467         conn.close()

/usr/lib/python2.7/socket.pyc in meth(name, self, *args)
    222 
    223 def meth(name,self,*args):
--> 224     return getattr(self._sock,name)(*args)
    225 
    226 for _m in _socketmethods:

UnicodeEncodeError: 'ascii' codec can't encode character u'\xae' in position 3368: ordinal not in range(128)

You should pass a file opened in a binary mode to ftp.storbinary() . 您应该将以二进制模式打开的文件传递给ftp.storbinary() For example, if you want to upload a Unicode string as a filename file: 例如,如果要上载Unicode字符串作为filename文件:

import io

assert isinstance(unicode_string, unicode)
file = io.BytesIO(unicode_string.encode("utf-8"))
ftp.storbinary("STOR filename", file)

If unicode_string contains xml; 如果unicode_string包含xml; make sure that the character encoding used in the xml declaration is consistent with the encoding you use to store the file. 确保xml声明中使用的字符编码与用于存储文件的编码一致。

I was able to find the solution, the comment by @Cairnarvon was partially correct, I was encoding the string, but there were other bits of the string written to the StringIO instance that were not encoded. 我能够找到解决方案,@ Cairnarvon的注释部分正确,我正在编码字符串,但是写入StringIO实例的字符串中还有其他未编码的位。 Finally I ended up creating the XML bit and encoding it as a whole. 最后,我最终创建了XML位并对其进行了整体编码。 You can see my code in the pastebin link below; 您可以在下面的pastebin链接中看到我的代码;

http://pastebin.com/GugTLRQJ http://pastebin.com/GugTLRQJ

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM