def sanitize_filename(filename):
    """Sanitize a filename, removing dangerous characters that could be used to 
    escape the uploads directory. Everything except [A-Z a-z 0-9 - _ .] are 
    stripped, along with the pattern '..' which in *nix systems represents going
    up a directory in the filepath.
    """
    filename = filename.replace("..", ".")
    for character in filename:
        if character not in ("ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
                             "abcdefghijklmnopqrstuvwxyz" + 
                             "0123456789" + 
                             "._-"):
            filename = filename.replace(character, "")
    return filename