def query(self,args):
     """
     Run a query against the API.
     """
     
     from bookwormDB.general_API import SQLAPIcall
     import json
     
     query = json.loads(args.APIcall)
     caller = SQLAPIcall(query)
     print caller.execute()
Exemple #2
0
    def query(self, args):
        """
        Run a query against the API.
        """

        from bookwormDB.general_API import SQLAPIcall
        import json

        query = json.loads(args.APIcall)
        caller = SQLAPIcall(query)
        print caller.execute()
Exemple #3
0
def main(JSONinput):

    query = json.loads(JSONinput)
    # Print appropriate HTML headers
    headers(query['method'])
    # Set up the query.
    p = SQLAPIcall(query)
    #run the query.
    print p.execute() 

    return True
def main(JSONinput):

    query = json.loads(JSONinput)
    # Set up the query.
    p = SQLAPIcall(query)

    # run the query.
    resp = p.execute()

    if query['method'] == 'data' and 'format' in query and query['format'] == 'json':
        try:
            resp = json.loads(resp)
        except:
            resp = dict(status="error", code=500,
                        message="Internal error: server did not return json")

        # Print appropriate HTML headers
        if 'status' in resp and resp['status'] == 'error':
            code = resp['code'] if 'code' in resp else 500
            headers(query['method'], errorcode=code)
        else:
            headers(query['method'])
        print json.dumps(resp)
    else:
        headers(query['method'])
        print resp

    return True
Exemple #5
0
def main(JSONinput):

    query = json.loads(JSONinput)
    # Set up the query.
    p = SQLAPIcall(query)

    # run the query.
    resp = p.execute()

    if query['method'] == 'data' and 'format' in query and query[
            'format'] == 'json':
        try:
            resp = json.loads(resp)
        except:
            resp = dict(status="error",
                        code=500,
                        message="Internal error: server did not return json")

        # Print appropriate HTML headers
        if 'status' in resp and resp['status'] == 'error':
            code = resp['code'] if 'code' in resp else 500
            headers(query['method'], errorcode=code)
        else:
            headers(query['method'])
        print json.dumps(resp)
    else:
        headers(query['method'])
        print resp

    return True
def main(JSONinput):

    query = json.loads(JSONinput)

    p = SQLAPIcall(query)
    result = p.execute()

    if (query['method'] == 'data' and 'format' in query
            and query['format'] == 'json'):
        # New format for response
        jresp = json.loads(result)
        resp = jsonify(jresp)
        if jresp['status'] == 'error':
            resp.status_code = jresp['code'] if 'code' in jresp else 500
    else:
        resp = Response(result)

    if query['method'] == "return_tsv":
        resp.headers['Content-Type'] = "text; charset=utf-8"
        resp.headers["Content-Disposition"] = "filename=Bookworm-data.txt"
        resp.headers["Pragma"] = "no-cache"
        resp.headers["Expires"] = 0
    elif query['method'] in ['return_json', 'return_pickle']:
        resp.headers['Content-Type'] = "text/html"

    resp.headers['Access-Control-Allow-Origin'] = '*'
    resp.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, OPTIONS'
    resp.headers['Access-Control-Allow-Headers'] = 'Origin, Accept, '\
        'Content-Type, X-Requested-With, X-CSRF-Token'

    return resp
def main(JSONinput):

    query = json.loads(JSONinput)

    p = SQLAPIcall(query)
    result = p.execute()

    if (query['method'] == 'data' and 'format' in query and
            query['format'] == 'json'):
        # New format for response
        jresp = json.loads(result)
        resp = jsonify(jresp)
        if jresp['status'] == 'error':
            resp.status_code = jresp['code'] if 'code' in jresp else 500
    else:
        resp = Response(result)

    if query['method'] == "return_tsv":
        resp.headers['Content-Type'] = "text; charset=utf-8"
        resp.headers["Content-Disposition"] = "filename=Bookworm-data.txt"
        resp.headers["Pragma"] = "no-cache"
        resp.headers["Expires"] = 0
    elif query['method'] in ['return_json', 'return_pickle']:
        resp.headers['Content-Type'] = "text/html"

    resp.headers['Access-Control-Allow-Origin'] = '*'
    resp.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, OPTIONS'
    resp.headers['Access-Control-Allow-Headers'] = 'Origin, Accept, '\
        'Content-Type, X-Requested-With, X-CSRF-Token'

    return resp
Exemple #8
0
def application(environ, start_response, logfile="bookworm_queries.log"):
    # Starting with code from http://wsgi.tutorial.codepoint.net/parsing-the-request-post
    try:
        request_body_size = int(environ.get('QUERY_STRING', 0))
    except (ValueError):
        request_body_size = 0

    # When the method is POST the variable will be sent
    # in the HTTP request body which is passed by the WSGI server
    # in the file like wsgi.input environment variable.

    q = environ.get('QUERY_STRING')
    try:
        ip = environ.get('HTTP_X_FORWARDED_FOR')
#       logging.debug("Request from {}".format(ip))
    except:
        ip = environ.get('REMOTE_ADDR')
    if ip is None:
        ip = environ.get('REMOTE_ADDR')
    query = unquote(q)

    headers = {
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': 'GET, POST, PUT, OPTIONS',
        'Access-Control-Allow-Headers':
        'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token',
        'charset': 'utf-8'
    }

    logging.debug("Received query {}".format(query))
    start = datetime.now()

    # Backward-compatability: we used to force query to be
    # a named argument.
    query = query.strip("query=")
    query = query.strip("queryTerms=")

    try:
        query = json.loads(query)
        query['ip'] = ip
    except:
        response_body = "Unable to read JSON"
        status = '404'
        start_response(status, list(headers.items()))
        return [
            b'{"status":"error", "message": "You have passed invalid JSON to the Bookworm API"}'
        ]

    process = SQLAPIcall(query)
    response_body = process.execute()

    # It might be binary already.
    headers['Content-type'] = content_type(query)

    if headers['Content-type'] != 'application/octet-stream':
        response_body = bytes(response_body, 'utf-8')

    headers['Content-Length'] = str(len(response_body))
    status = '200 OK'
    start_response(status, list(headers.items()))

    query['time'] = start.timestamp()
    query['duration'] = datetime.now().timestamp() - start.timestamp()
    # This writing isn't thread-safe; but generally we're not getting more than a couple queries a second.
    with open(logfile, 'a') as fout:
        json.dump(query, fout)
        fout.write("\n")
    logging.debug("Writing to log: \n{}\n".format(json.dumps(query)))
    return [response_body]