Created
June 8, 2013 17:33
-
-
Save ajdavis/5735965 to your computer and use it in GitHub Desktop.
Python 2/3-compatible base64 encoding?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.