Archive for January, 2018

What are the built-in functions?

January 19, 2018 Leave a comment

How to figure out the built-in functions in Python? Of course, you can look up the documentation, but now the exercise is to list them in the Python shell.


In [1]: import builtins

In [2]: dir(builtins)
Categories: python Tags:

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: , , ,