0

i use python 3.4 and django-1.9. ı need int to string and encoding with base64.

code:

new_key = base64.b64encode(str(key))

error:

Traceback (most recent call last):
  File "/home/mehmet/Envs/ets-3/lib/python3.4/site-packages/django/core/handlers/base.py", line 149, in get_response
    response = self.process_exception_by_middleware(e, request)
  File "/home/mehmet/Envs/ets-3/lib/python3.4/site-packages/django/core/handlers/base.py", line 147, in get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/mehmet/Envs/ets-3/lib/python3.4/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
    return view_func(*args, **kwargs)
  File "/home/mehmet/Envs/ets-3/lib/python3.4/site-packages/django/contrib/auth/decorators.py", line 23, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "/home/mehmet/PycharmProjects/Tango/orders/views.py", line 167, in order_info
    subscribe_item_list, mount_subscribe_discount_relation)
  File "/usr/lib/python3.4/contextlib.py", line 30, in inner
    return func(*args, **kwds)
  File "/home/mehmet/PycharmProjects/Tango/operations/order.py", line 94, in new_order
    return encryption(order.id)
  File "/home/mehmet/PycharmProjects/Tango/operations/order.py", line 15, in encryption
    new_key = base64.b64encode(str(key))
  File "/home/mehmet/Envs/ets-3/lib/python3.4/base64.py", line 62, in b64encode
    encoded = binascii.b2a_base64(s)[:-1]
TypeError: 'str' does not support the buffer interface
KAYKISIZ
  • 118
  • 9

1 Answers1

0

In Python 3 base64.b64encode requires a bytes object as its argument, not a str as is currently the case. You can handle this by converting the integer in key to a byte string, and then base64 encoding the byte string:

>>> key = 123456789
>>> new_key = base64.b64encode(bytes(str(key), encoding='ascii'))
>>> print(new_key)
b'MTIzNDU2Nzg5'
>>> key = -443322
>>> new_key = base64.b64encode(bytes(str(key), encoding='ascii'))
>>> print(new_key)
b'LTQ0MzMyMg=='

Here the integer key is first converted to a Python 3 string (type str) and then converted to a byte string (type bytes) using ASCII encoding. Any valid encoding can be used, but ASCII will certainly cover all possible digits and unary -.

For completeness, in Python 2 you can just do this:

>>> key = 123456789
>>> new_key = str(key).encode('base64')
mhawke
  • 84,695
  • 9
  • 117
  • 138
  • This function is inefficient, it first converts the integer into a string array, and then does the base64 conversion. A more efficient solution is described here: https://stackoverflow.com/a/68443789/234270 – speedplane Jul 19 '21 at 16:16