![](/img/trans.png)
[英]UnicodeEncodeError when trying to convert Django models to XML
[英]Python ftplib UnicodeEncodeError when trying to upload an XML with unicode content
我正在尝试使用ftplib将具有Unicode内容的XML上载到FTP服务器,但是当我尝试使用storbinary方法上载时出现以下异常。 XML数据已正确编码为unicode(utf-8),我已经确定了这一点,我不确定为什么storbinary试图在上传时将其编码为“ ascii”。 谁能帮忙吗?
--> 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)
您应该将以二进制模式打开的文件传递给ftp.storbinary()
。 例如,如果要上载Unicode字符串作为filename
文件:
import io
assert isinstance(unicode_string, unicode)
file = io.BytesIO(unicode_string.encode("utf-8"))
ftp.storbinary("STOR filename", file)
如果unicode_string
包含xml; 确保xml声明中使用的字符编码与用于存储文件的编码一致。
我能够找到解决方案,@ Cairnarvon的注释部分正确,我正在编码字符串,但是写入StringIO实例的字符串中还有其他未编码的位。 最后,我最终创建了XML位并对其进行了整体编码。 您可以在下面的pastebin链接中看到我的代码;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.