Posts Tagged ‘quote’

BASE64 as URL parameter

January 1, 2018 Leave a comment

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.

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 = ""
>>> import urllib.parse
>>> new = urllib.parse.quote(url)
>>> new
>>> 'https%3A//'    # notice the "/" signs!
>>> urllib.parse.quote(url, safe='')
>>> ''    # no "/" signs!
>>> new = urllib.parse.quote(url, safe='')
>>> urllib.parse.unquote(new)
>>> ''
Categories: python Tags: , , ,

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

Categories: python Tags: , ,

urllib.quote, urllib.unquote

April 10, 2012 Leave a comment
>>> import urllib
>>> urllib.quote('hello world')
>>> urllib.unquote('hello%20world')
'hello world'
Categories: python Tags: , ,


April 3, 2011 Leave a comment

I hear and I forget. I see and I remember. I do and I understand.” – Confucius