Skip to content

Instantly share code, notes, and snippets.

@ajdavis
Created June 8, 2013 17:33
Show Gist options
  • Save ajdavis/5735965 to your computer and use it in GitHub Desktop.
Save ajdavis/5735965 to your computer and use it in GitHub Desktop.
Python 2/3-compatible base64 encoding?
import base64
import sys
import unittest
PY3 = sys.version_info[0] >= 3
def base64ify(bytes_or_str):
if PY3 and isinstance(bytes_or_str, str):
input_bytes = bytes_or_str.encode('utf8')
else:
input_bytes = bytes_or_str
output_bytes = base64.urlsafe_b64encode(input_bytes)
if PY3:
return output_bytes.decode('ascii')
else:
return output_bytes
class Test(unittest.TestCase):
def test_bytes_in(self):
self.assertTrue(isinstance(base64ify(b'asdf'), type('hi')))
def test_str_in(self):
self.assertTrue(isinstance(base64ify('asdf'), type('hi')))
if __name__ == '__main__':
unittest.main()
@aecanales
Copy link

Old gist, but thanks a ton, it's exactly what I needed!

Was messing around with the Gmail API (which uses Python 2 in it's documentation) in Python 3 and was totally stuck as to why the base64 encryption wasn't working and how to adapt it to Python 3.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment