简体   繁体   English

Base64解码

[英]Base64 decoding

I'm trying to decode some text in base 64, and I don't understand why I get an error while trying to do that: 我正在尝试解码base 64中的一些文本,我不明白为什么我在尝试这样做时出错:

b'Zm9v'.decode('base64_codec')

The exception raised is: TypeError: expected bytes, not memoryview 引发的异常是: TypeError: expected bytes, not memoryview

PS: I know there's an alternative using the base64 module. PS:我知道有一个使用base64模块的替代方案。 But I'm interested in knowing the answer, just out of curiosity. 但出于好奇,我有兴趣知道答案。

Thanks! 谢谢!

Unfortunately, the bytes.decode() and str.encode() methods (rightly) only support codecs that also convert between types; 不幸的是, bytes.decode()str.encode()方法(正确地)只支持也在类型之间转换的编解码器; bytes.decode() must always return a str object, while str.encode() must return bytes ; bytes.decode()必须始终返回一个str对象,而str.encode()必须返回bytes ; see the original issue that introduced these codecs : 看看介绍这些编解码器原始问题

Codecs can work with arbitrary types, it's just that the helper methods on unicode and bytes objects only support one combination of types in Python 3.x. 编解码器可以使用任意类型,只是unicode和bytes对象上的辅助方法只支持Python 3.x中的一种类型组合。

So the specific error you see is caused by the fact that the bytes.decode() method always expects to return a value of type str . 因此,您看到的具体错误是由bytes.decode()方法总是希望返回str类型的值引起的。 Similarly, the str.encode() method balks at codecs that do not return bytes as a return value: 类似地, str.encode()方法在不返回bytes作为返回值的编解码器上运行:

>>> 'Ceasar'.encode('rot_13')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: encoder did not return a bytes object (type=str)

As such, for bytes-to-bytes and str-to-str codecs, you need to use the codecs module directly: 因此,对于字节到字节和str到str的编解码器,您需要直接使用codecs模块:

import codecs

codecs.getdecoder('base64_codec')(b'Zm9v')[0]

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

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