# Buggy code
def download_file(url, filename, session=None, headers=None, **kwargs):  # pylint:disable=too-many-return-statements
    """
    Downloads a file specified

    :param url: Source URL
    :param filename: Target file on filesystem
    :param session: request session to use
    :param headers: override existing headers in request session
    :return: True on success, False on failure
    """

    try:
        hooks, cookies, verify, proxies = request_defaults(kwargs)

        with closing(
            session.get(
                url,
                allow_redirects=True,
                stream=True,
                verify=verify,
                headers=headers,
                cookies=cookies,
                hooks=hooks,
                proxies=proxies,
            )
        ) as resp:
            if not resp.ok:
                logger.log(
                    "Requested download url %s returned status code is %s: %s"
                    % (url, resp.status_code, http_code_description(resp.status_code)),
                    logger.DEBUG,
                )
                return False

            try:
                with io.open(filename, "wb") as fp:
                    for chunk in resp.iter_content(chunk_size=1024):
                        if chunk:
                            fp.write(chunk)
                            fp.flush()

                chmodAsParent(filename)
            except Exception:
                logger.log(
                    "Problem setting permissions or writing file to: %s" % filename,
                    logger.WARNING,
                )

    except (requests.exceptions.HTTPError, requests.exceptions.TooManyRedirects) as e:
        remove_file_failed(filename)
        logger.log(
            "HTTP error %r while loading download URL %s " % (ex(e), url),
            logger.WARNING,
        )
        return False
    except requests.exceptions.ConnectionError as e:
        remove_file_failed(filename)
        logger.log(
            "Connection error %r while loading download URL %s " % (ex(e), url),
            logger.WARNING,
        )
        return False
    except requests.exceptions.Timeout as e:
        remove_file_failed(filename)
        logger.log(
            "Connection timed out %r while loading download URL %s " % (ex(e), url),
            logger.WARNING,
        )
        return False
    except EnvironmentError as e:
        remove_file_failed(filename)
        logger.log("Unable to save the file: %r " % ex(e), logger.WARNING)
        return False
    except Exception:
        remove_file_failed(filename)
        logger.log(
            "Unknown exception while loading download URL %s : %r"
            % (url, traceback.format_exc()),
            logger.ERROR,
        )
        logger.log(traceback.format_exc(), logger.DEBUG)
        return False

    return True


# Traceback (ConnectionError)
DAILYSEARCHER :: [b9d562e] Exception generated in thread DAILYSEARCHER: error HTTPSConnectionPool(host='cdn.pymedusa.com', port=443): Max retries exceeded with url: /sb_network_timezones/network_timezones.txt (Caused by NewConnectionError('<requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x699fdbb0>: Failed to establish a new connection: [Errno -2] Nome ou servi\xc3\xa7o desconhecido',))
Traceback (most recent call last):
File "/home/osmc/SickRage/sickbeard/scheduler.py", line 106, in run
self.action.run(self.force)
File "/home/osmc/SickRage/sickbeard/dailysearcher.py", line 75, in run
update_network_dict()
File "/home/osmc/SickRage/sickbeard/network_timezones.py", line 47, in update_network_dict
url_data = helpers.getURL(url, session=helpers.make_session(), returns='text')
File "/home/osmc/SickRage/sickbeard/helpers.py", line 1423, in getURL
verify=verify)
File "/home/osmc/SickRage/lib/requests/sessions.py", line 475, in request
resp = self.send(prep, **send_kwargs)
File "/home/osmc/SickRage/lib/requests/sessions.py", line 585, in send
r = adapter.send(request, **kwargs)
File "/home/osmc/SickRage/lib/cachecontrol/adapter.py", line 46, in send
resp = super(CacheControlAdapter, self).send(request, **kw)
File "/home/osmc/SickRage/lib/requests/adapters.py", line 467, in send
raise ConnectionError(e, request=request)
ConnectionError: HTTPSConnectionPool(host='cdn.pymedusa.com', port=443): Max retries exceeded with url: /sb_network_timezones/network_timezones.txt (Caused by NewConnectionError('<requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x699fdbb0>: Failed to establish a new connection: [Errno -2] Nome ou servi\xc3\xa7o desconhecido',))

# Fixed code
def download_file(url, filename, session=None, headers=None, **kwargs):  # pylint:disable=too-many-return-statements
    """
    Downloads a file specified

    :param url: Source URL
    :param filename: Target file on filesystem
    :param session: request session to use
    :param headers: override existing headers in request session
    :return: True on success, False on failure
    """

    try:
        hooks, cookies, verify, proxies = request_defaults(kwargs)

        with closing(
            session.get(
                url,
                allow_redirects=True,
                stream=True,
                verify=verify,
                headers=headers,
                cookies=cookies,
                hooks=hooks,
                proxies=proxies,
            )
        ) as resp:
            if not resp.ok:
                logger.log(
                    "Requested download url %s returned status code is %s: %s"
                    % (url, resp.status_code, http_code_description(resp.status_code)),
                    logger.DEBUG,
                )
                return False

            try:
                with io.open(filename, "wb") as fp:
                    for chunk in resp.iter_content(chunk_size=1024):
                        if chunk:
                            fp.write(chunk)
                            fp.flush()

                chmodAsParent(filename)
            except Exception:
                logger.log(
                    "Problem setting permissions or writing file to: %s" % filename,
                    logger.WARNING,
                )

    except requests.exceptions.RequestException as e:
        remove_file_failed(filename)
        logger.log(
            "Error requesting download url: {0}. Error: {1}".format(url, ex(e)),
            logger.WARNING,
        )
        return False
    except EnvironmentError as e:
        remove_file_failed(filename)
        logger.log("Unable to save the file: %r " % ex(e), logger.WARNING)
        return False
    except Exception:
        remove_file_failed(filename)
        logger.log(
            "Unknown exception while loading download URL %s : %r"
            % (url, traceback.format_exc()),
            logger.ERROR,
        )
        logger.log(traceback.format_exc(), logger.DEBUG)
        return False

    return True