【问题标题】:Error b64encode a bytes-like object is required, not 'str' python3错误 b64encode a bytes-like object is required, not 'str' python3
【发布时间】:2020-12-16 18:54:07
【问题描述】:

将base 64转换为python时出现错误,我找不到解决方案

uniq_token_hash = hashlib.sha256(uniq_token_string.encode('UTF-8')).hexdigest()
print ('UNIQ HASH: %s' % uniq_token_hash)
auth_token = b64encode('%s;%s;%s' % (devapp,unix_timestamp, uniq_token_hash))
print ('AUTH TOKEN: %s' % auth_token)

line 58, in b64encode
    encoded = binascii.b2a_base64(s, newline=False)
TypeError: a bytes-like object is required, not 'str'

【问题讨论】:

    标签: python python-3.x token


    【解决方案1】:

    Python 中有两种字符串。第一个由 Unicode 代码点(字符)组成,称为str。第二个是字节序列(从 0 到 255 的小整数),称为bytesb64encode 需要 bytes 作为输入。您已经知道如何将str 转换为bytes,因为您已经使用.encode 完成过一次。

    auth_token = b64encode(('%s;%s;%s' % (devapp,unix_timestamp, uniq_token_hash)).encode('UTF-8'))
    

    【讨论】:

      【解决方案2】:

      您必须将 UTF-8 字符串转换为简单的字节数组,您可以使用以下代码将字符串更改为字节数组

      old_string = "string"
      byte_array = old.string.encode()
      # returns b'string'
      new_string = byte_array.decode()
      

      在最近的 Python 版本中,我会使用 f'string。也许使用这样的东西:

      byte_array = f'{devapp};{unix_timestamp};{uniq_token_hash}'.encode()
      auth_token = b64encode(byte_array)
      

      请记住,您必须仔细处理编码并清楚地知道您如何存储。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-09-24
        • 1970-01-01
        • 2017-05-08
        • 1970-01-01
        • 2020-01-30
        • 2017-11-04
        • 2018-02-19
        • 1970-01-01
        相关资源
        最近更新 更多