# Buggy code
def read_last_influxdb(device_id, measure_type, duration_sec=None):
    """
    Query Influxdb for the last entry.

    example:
        read_last_influxdb('00000001', 'temperature')

    :return: list of time and value
    :rtype: list

    :param device_id: What device_id tag to query in the Influxdb
        database (ex. '00000001')
    :type device_id: str
    :param measure_type: What measurement to query in the Influxdb
        database (ex. 'temperature', 'duration')
    :type measure_type: str
    :param duration_sec: How many seconds to look for a past measurement
    :type duration_sec: int
    """
    client = InfluxDBClient(
        INFLUXDB_HOST,
        INFLUXDB_PORT,
        INFLUXDB_USER,
        INFLUXDB_PASSWORD,
        INFLUXDB_DATABASE,
    )

    if duration_sec:
        query = query_string(measure_type, device_id, past_sec=duration_sec)
    else:
        query = query_string(measure_type, device_id, value="LAST")

    last_measurement = client.query(query).raw

    if last_measurement:
        try:
            number = len(last_measurement["series"][0]["values"])
            last_time = last_measurement["series"][0]["values"][number - 1][0]
            last_measurement = last_measurement["series"][0]["values"][number - 1][1]
            return [last_time, last_measurement]
        except KeyError:
            if duration_sec:
                logger.debug(
                    "No measurement available in the past {sec} seconds.".format(
                        sec=duration_sec
                    )
                )
            else:
                logger.debug("No measurement available.")
        except Exception:
            logger.exception("Error parsing the last influx measurement")


# Traceback (ConnectionRefusedError)
2018-02-13 04:49:13,135 - mycodo.math_3 - ERROR - Run Error: HTTPConnectionPool(host='localhost', port=8086): Max retries exceeded with url: /query?db=mycodo_db&amp;q=SELECT+value+FROM+temperature+WHERE+device_id%3D%2773103a85-ca36-4f55-9443-8b18f13792fa%27+AND+time+%3E+now%28%29+-+60s (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0xb4fa2d90>: Failed to establish a new connection: [Errno 111] Connection refused',))
Traceback (most recent call last):
File "/var/mycodo-root/env/lib/python3.5/site-packages/urllib3/connection.py", line 141, in _new_conn
(self.host, self.port), self.timeout, **extra_kw)
File "/var/mycodo-root/env/lib/python3.5/site-packages/urllib3/util/connection.py", line 83, in create_connection
raise err
File "/var/mycodo-root/env/lib/python3.5/site-packages/urllib3/util/connection.py", line 73, in create_connection
sock.connect(sa)
ConnectionRefusedError: [Errno 111] Connection refused

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/var/mycodo-root/env/lib/python3.5/site-packages/urllib3/connectionpool.py", line 601, in urlopen
chunked=chunked)
File "/var/mycodo-root/env/lib/python3.5/site-packages/urllib3/connectionpool.py", line 357, in _make_request
conn.request(method, url, **httplib_request_kw)
File "/usr/lib/python3.5/http/client.py", line 1107, in request
self._send_request(method, url, body, headers)
File "/usr/lib/python3.5/http/client.py", line 1152, in _send_request
self.endheaders(body)
File "/usr/lib/python3.5/http/client.py", line 1103, in endheaders
self._send_output(message_body)
File "/usr/lib/python3.5/http/client.py", line 934, in _send_output
self.send(msg)
File "/usr/lib/python3.5/http/client.py", line 877, in send
self.connect()
File "/var/mycodo-root/env/lib/python3.5/site-packages/urllib3/connection.py", line 166, in connect
conn = self._new_conn()
File "/var/mycodo-root/env/lib/python3.5/site-packages/urllib3/connection.py", line 150, in _new_conn
self, "Failed to establish a new connection: %s" % e)
urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPConnection object at 0xb4fa2d90>: Failed to establish a new connection: [Errno 111] Connection refused

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/var/mycodo-root/env/lib/python3.5/site-packages/requests/adapters.py", line 440, in send
timeout=timeout
File "/var/mycodo-root/env/lib/python3.5/site-packages/urllib3/connectionpool.py", line 639, in urlopen
_stacktrace=sys.exc_info()[2])
File "/var/mycodo-root/env/lib/python3.5/site-packages/urllib3/util/retry.py", line 388, in increment
raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='localhost', port=8086): Max retries exceeded with url: /query?db=mycodo_db&amp;q=SELECT+value+FROM+temperature+WHERE+device_id%3D%2773103a85-ca36-4f55-9443-8b18f13792fa%27+AND+time+%3E+now%28%29+-+60s (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0xb4fa2d90>: Failed to establish a new connection: [Errno 111] Connection refused',))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/var/mycodo-root/mycodo/controller_math.py", line 186, in run
success, measure = self.get_measurements_from_str(self.equation_input)
File "/var/mycodo-root/mycodo/controller_math.py", line 325, in get_measurements_from_str
self.max_measure_age)
File "/var/mycodo-root/mycodo/utils/influx.py", line 141, in read_last_influxdb
last_measurement = client.query(query).raw
File "/var/mycodo-root/env/lib/python3.5/site-packages/influxdb/client.py", line 394, in query
expected_response_code=expected_response_code
File "/var/mycodo-root/env/lib/python3.5/site-packages/influxdb/client.py", line 252, in request
timeout=self._timeout
File "/var/mycodo-root/env/lib/python3.5/site-packages/requests/sessions.py", line 508, in request
resp = self.send(prep, **send_kwargs)
File "/var/mycodo-root/env/lib/python3.5/site-packages/requests/sessions.py", line 618, in send
r = adapter.send(request, **kwargs)
File "/var/mycodo-root/env/lib/python3.5/site-packages/requests/adapters.py", line 508, in send
raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPConnectionPool(host='localhost', port=8086): Max retries exceeded with url: /query?db=mycodo_db&amp;q=SELECT+value+FROM+temperature+WHERE+device_id%3D%2773103a85-ca36-4f55-9443-8b18f13792fa%27+AND+time+%3E+now%28%29+-+60s (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0xb4fa2d90>: Failed to establish a new connection: [Errno 111] Connection refused',))

# Fixed code
def read_last_influxdb(device_id, measure_type, duration_sec=None):
    """
    Query Influxdb for the last entry.

    example:
        read_last_influxdb('00000001', 'temperature')

    :return: list of time and value
    :rtype: list

    :param device_id: What device_id tag to query in the Influxdb
        database (ex. '00000001')
    :type device_id: str
    :param measure_type: What measurement to query in the Influxdb
        database (ex. 'temperature', 'duration')
    :type measure_type: str
    :param duration_sec: How many seconds to look for a past measurement
    :type duration_sec: int
    """
    client = InfluxDBClient(
        INFLUXDB_HOST,
        INFLUXDB_PORT,
        INFLUXDB_USER,
        INFLUXDB_PASSWORD,
        INFLUXDB_DATABASE,
    )

    if duration_sec:
        query = query_string(measure_type, device_id, past_sec=duration_sec)
    else:
        query = query_string(measure_type, device_id, value="LAST")

    try:
        last_measurement = client.query(query).raw
    except requests.exceptions.ConnectionError:
        logger.debug(
            "Failed to establish a new influxdb connection. Ensure influxdb is running."
        )
        last_measurement = None

    if last_measurement:
        try:
            number = len(last_measurement["series"][0]["values"])
            last_time = last_measurement["series"][0]["values"][number - 1][0]
            last_measurement = last_measurement["series"][0]["values"][number - 1][1]
            return [last_time, last_measurement]
        except KeyError:
            if duration_sec:
                logger.debug(
                    "No measurement available in the past {sec} seconds.".format(
                        sec=duration_sec
                    )
                )
            else:
                logger.debug("No measurement available.")
        except Exception:
            logger.exception("Error parsing the last influx measurement")