繁体   English   中英

如何将来自 Suds 的 base64 编码字段内容写入 Python 3 中的文件

[英]How to write a base64 encoded field content coming from Suds to a file in Python 3

Stackoverflow 上有很多关于 Python 3 的字符串到字节转换问题,每一个都处理略有不同的情况,由于我找不到这个具体的问题,我将在这里回答我自己的问题。

网络服务的某些字段,例如传输文件(如 PDF 文档)的字段,可能会使用 base64 编码。

它在 Python 2 中确实有效:

with open(filepath, 'w') as file_:
    file_.write(my_content.decode('base64'))

现在,在 Python 3 上的 Suds 中,等效项是:

from base64 import b64decode
file_.write(b64decode(my_content))

但这会导致错误: a bytes-like object is required, not 'Text'

原因是 Suds 返回一个自定义类型Text ,它对于b64encode意外地不像str那样反应(尽管它是子类化它)。 所以它必须首先显式转换为str

from base64 import b64decode
file_.write(b64decode(str(my_content)))

暂无
暂无

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

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