2

Background:

I'm trying to encode my string of a username and password to base 64 for a SOAP request in python 3.5.2.

Code:

username = 'Universal API/uAPI7054626850-8a6c09f0'
password = 'gaghw3d5WCw3QCzTMh3QJ5fDp'
base64string = '%s:%s' % (username, password)
resultValue = base64string.encode('base64', 'strict')

This code has been exactly copied from the example at: https://www.tutorialspoint.com/python/string_encode.htm

Error:

Traceback (most recent call last):
File "soapRequests.py", line 44, in <module>
    resultValue = base64string.encode('base64', 'strict')
LookupError: 'base64' is not a text encoding; use codecs.encode() to handle arbitrary codecs

Attempts:

Attempt 1: using the base64 codec
base64string = base64.encodestring(base64string).replace('\n', '')
Result: TypeError: expected bytes-like object, not str

If you have any idea how to encode a string to the base64 codec please let me know. Thanks

Answer:

Little did I know that the error came from the replace function being used after encoding the string. Use b64encode so that you don't have to write your own replace function to replace the new lines.

IFH
  • 161
  • 1
  • 2
  • 14

2 Answers2

4

Try this:

base64string = base64.b64encode( bytes(base64string, "utf-8") )
spa900
  • 927
  • 9
  • 19
  • Thanks a lot! My issue was because of the replace function trying to replace strings on a byte value. This is the answer because b64encode removes the '\n' – IFH Nov 06 '16 at 21:09
1

An alternative to base64:

import codecs

codecs.encode(bytes("mystring", 'utf8'), 'base64')
Marat
  • 15,215
  • 2
  • 39
  • 48