Ejemplo n.º 1
0
def api_data(stream, request, query):
    ''' Get data stored on the local database '''
    since, until = -1, -1
    test = ''

    dictionary = cgi.parse_qs(query)

    if "test" in dictionary:
        test = str(dictionary["test"][0])
    if "since" in dictionary:
        since = int(dictionary["since"][0])
    if "until" in dictionary:
        until = int(dictionary["until"][0])

    if test == 'bittorrent':
        table = table_bittorrent
    elif test == 'speedtest':
        table = table_speedtest
    elif test == 'raw':
        table = table_raw
    else:
        table = None

    indent, mimetype, sort_keys = None, "application/json", False
    if "debug" in dictionary and utils.intify(dictionary["debug"][0]):
        indent, mimetype, sort_keys = 4, "text/plain", True

    response = Message()

    if table:
        lst = table.listify(DATABASE.connection(), since, until)

    #
    # TODO We should migrate all the tests to use the new
    # generic interface. At that point, we can also change
    # the API to access "pages" of data by index.
    #
    # Until we change the API, we have an API that allows
    # the caller to specify date ranges. For this reason
    # below we emulate the date-ranges semantics provided
    # by database-based tests.
    #
    # Note: we assume that, whatever the test structure,
    # there is a field called "timestamp".
    #
    else:
        lst = []
        indexes = [None]
        indexes.extend(range(16))
        for index in indexes:
            tmp = BACKEND.walk_generic(test, index)
            if not tmp:
                break
            found_start = False
            for elem in reversed(tmp):
                if until >= 0 and elem["timestamp"] > until:
                    continue
                if since >= 0 and elem["timestamp"] < since:
                    found_start = True
                    break
                lst.append(elem)
            if found_start:
                break

    body = json.dumps(lst, indent=indent, sort_keys=sort_keys)
    response.compose(code="200", reason="Ok", body=body, mimetype=mimetype)
    stream.send_response(request, response)