简体   繁体   中英

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

There are many string to bytes conversion question about Python 3 on Stackoverflow, each one treating slightly different cases, and as I couldn't find this specific one, I'll answer my own question here.

Some fields of a webservice, eg those that transport files like a PDF document, may do that base64 encoded.

It Python 2 this did work:

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

Now, in Suds on Python 3 the equivalent would be:

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

But this results in an error: a bytes-like object is required, not 'Text' .

The reason is that Suds returns a custom type Text which for b64encode unexpectedly doesn't react like str (altough it's subclassing it). So it must be converted explicitly to str first:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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