Archive
BASE64 as URL parameter
Problem
In a REST API, I wanted to pass a URL as a BASE64-encoded string, e.g. “http://host/api/v2/url/aHR0cHM6...“. It worked well for a while but I got an error for a URL. As it turned out, a BASE64 string can contain the “/” sign, and it caused the problem.
Solution
Replace the “+” and “/” signs with “-” and “_“, respectively. Fortunately, Python has functions for that (see here).
Here are my modified, URL-safe functions:
def base64_to_str(b64):
return base64.urlsafe_b64decode(b64.encode()).decode()
def str_to_base64(s):
data = base64.urlsafe_b64encode(s.encode())
return data.decode()
You can also quote and unquote a URL instead of using BASE64:
>>> url = "https://www.youtube.com/watch?v=V6w24Lg3zTI" >>> >>> import urllib.parse >>> >>> new = urllib.parse.quote(url) >>> >>> new >>> 'https%3A//www.youtube.com/watch%3Fv%3DV6w24Lg3zTI' # notice the "/" signs! >>> >>> urllib.parse.quote(url, safe='') >>> 'https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DV6w24Lg3zTI' # no "/" signs! >>> >>> new = urllib.parse.quote(url, safe='') >>> >>> urllib.parse.unquote(new) >>> 'https://www.youtube.com/watch?v=V6w24Lg3zTI'
Simplicity is the final achievement.
“Simplicity is the final achievement. After one has played a vast quantity of notes and more notes, it is simplicity that emerges as the crowning reward of art.”
Frederic Chopin
urllib.quote, urllib.unquote
>>> import urllib
>>> urllib.quote('hello world')
'hello%20world'
>>> urllib.unquote('hello%20world')
'hello world'
Inspiration
“I hear and I forget. I see and I remember. I do and I understand.” – Confucius


You must be logged in to post a comment.