Пример #1
0
def update_session_info():
    log.info("/update_session_info")
    pretty_print_POST(request)
    response = json.loads(request.data)
    session_id = response["session_id"]
    answers = response["answers"]
    start_ts,end_ts = response["start"],response["end"]
    if not response["date"]:
        date = str(datetime.datetime.now()).split(' ')[0]
    else:
        date = response["date"]
    start_ts = ' '.join([date,start_ts])
    end_ts = ' '.join([date,end_ts])
    start = datetime.datetime.strptime(start_ts, '%Y-%m-%d %H:%M:%S')
    end   = datetime.datetime.strptime(end_ts, '%Y-%m-%d %H:%M:%S')
    duration = math.ceil(float((end-start).seconds/60.0))
    for ans in answers:
        if ans["q_id"] == "0":
            rating = ans["val"]

    statement = query.update_session_info1.format(start,end,duration,rating,session_id)
    log.info("query: {}".format(statement))
    ok_1 = db_insup(statement)

    ok_2 = True
    for ans in answers:
        statement = query.update_session_info2.format(ans["val"],session_id,ans["q_id"])
        log.info("query: {}".format(statement))
        ok = db_insup(statement)
        ok_2 = ok_2 and ok

    return Response(json.dumps({"insert":ok_1 and ok_2}), headers=HEADER, status=200, mimetype='application/json')   
Пример #2
0
def add_day_data():
    log.info("/add_day_data")
    pretty_print_POST(request)
    response = json.loads(request.data)
    ok_add, ok_once, ok_inc = False, False, False
    if len(db_fetch(query.add_day_data_check_rows.format(response["date"],response["userid"]))) == 0:
        log.info("adding row for date {} for user {}".format(response["date"],response["userid"]))
        statement = query.add_day_data_add_row.format(response["date"],response["userid"])
        log.info("query: {}".format(statement))
        ok_add = db_insup(statement)
    
    if response["add_type"] == "once":
        statement = query.add_day_data_set_value_once.format(response["type"],response["value"],response["date"],response["userid"])
        log.info("query: {}".format(statement))
        ok_once = db_insup(statement)

    if response["add_type"] == "increment":
        statement = query.add_day_data_fetch_value.format(response["type"],response["date"],response["userid"])
        log.info("query: {}".format(statement))
        result = db_fetch(statement)
        new_val = float(response["value"])
        if result[0][0]:
            new_val += float(result[0][0])
        log.info("updating value")
        statement = query.add_day_data_set_value_once.format(response["type"],new_val,response["date"],response["userid"])
        log.info("query: {}".format(statement))
        ok_inc = db_insup(statement)

    return Response(json.dumps({"inserted": ok_add or ok_once or ok_inc}), headers=HEADER, status=200, mimetype='application/json')
Пример #3
0
def update_procurement(upd_qty):
    log.info("upd_qty = {}".format(upd_qty))
    for resource_id, qty in upd_qty.items():
        statement = "select current_inventory, deficit from resource where id='{}'".format(
            resource_id)
        res = db_fetch(statement)
        current_inventory = str(int(res[0][0]) + qty)
        deficit = str(int(res[0][1]) - qty)
        statement = "update resource set current_inventory='{}', deficit='{}' where id='{}'"\
        .format(current_inventory,deficit,resource_id)
        log.info("update statement: {}".format(statement))
        db_insup(statement)
Пример #4
0
def insert_procurement(doner_id, addr, items):
    log.info("in update function {}, {}, {}".format(doner_id, addr, items))
    for key, val in items.items():
        statement = "select id from resource where name='{}'".format(key)
        result = db_fetch(statement)
        if result:
            resource_id = result[0][0]
            #log.info("addr = {}".format(addr))
            coordinate = str(addr['lat']) + "," + str(addr['lng'])
            statement = "INSERT INTO public.procurement (resource_id, quantity, donor_id, coordinate, status) \
            VALUES('{}','{}','{}','{}','{}')".format(resource_id, str(val),
                                                     doner_id, coordinate, 'N')
            log.info("statement to execute: {}".format(statement))
            db_insup(statement)
        else:
            raise ValueError('No result found for {}'.format(key))
Пример #5
0
def update_user_info():
    pretty_print_POST(request)
    log.info("/update_user_info")
    response = json.loads(request.data)
    uid = response["userid"]
    statement_update_users = query.update_user_info_1.format(response["name"],response["email"],uid)
    log.info("query: {}".format(statement_update_users))
    ok_users = db_insup(statement_update_users)

    statement_update_user_info = query.update_user_info_2.format(response["age"],response["gender"],\
                                 response["height"],response["weight"],response["sport_id"],\
                                 response["organization"],response["role"],uid)
    log.info("query: {}".format(statement_update_user_info))
    ok_user_information = db_insup(statement_update_user_info)
    ok = ok_users and ok_user_information

    return Response(json.dumps({"update":ok}), headers=HEADER, status=200, mimetype='application/json')
Пример #6
0
def register_device_key():
    log.info("/register_device_key")
    pretty_print_POST(request)
    response = json.loads(request.data)
    statement = query.register_device_key.format(response["device_key"],response["user_id"])
    log.info("query: {}".format(statement))
    ok = db_insup(statement)

    return Response(json.dumps({"msg": ok}), headers=HEADER, status=200, mimetype='application/json')
Пример #7
0
def register_app_instance():
    log.info("/register_app_instance")
    pretty_print_POST(request)
    response = json.loads(request.data)
    statement = query.register_app_instance.format(response["userid"],response["appid"])
    log.info("query: {}".format(statement))
    ok = db_insup(statement)

    return Response(json.dumps({"event_created": ok}), headers=HEADER, status=200, mimetype='application/json')
Пример #8
0
def login_info():
    log.info('/login_info')
    pretty_print_POST(request)
    response = json.loads(request.data)
    for_users_table_vals = "('{}','{}','{}','{}','{}')".format(response["name"],response["email"],response\
                                                   ["userid"],response["password"],generate_device_key())
    statement = query.login_info.format(for_users_table_vals)
    log.info("query: {}".format(statement))
    ok = db_insup(statement)

    return Response(json.dumps({"msg": ok}), headers=HEADER, status=200, mimetype='application/json')
Пример #9
0
def insert_session_data():
    f = open('session_data.csv', 'rb')
    reader = csv.reader(f)
    q = "insert into sessions values ({},'{}','{}',NULL,NULL,'{}','{}','{}','{}','{}','{}','{}','{}')"
    for i,row in enumerate(reader):
        if i==0:
            continue
        statement = q.format(generate_session_id(),row[0],row[1],row[4],row[5],row[6],row[7],row[8],row[9],\
        row[10],row[11])
        log.info("query: {}".format(statement))
        ok = db_insup(statement)
        log.info("row {}: {}".format(i,ok))
Пример #10
0
def save_response():
    log.info("/save_response")
    pretty_print_POST(request)
    response = json.loads(request.data)
    uid = response["user_id"]
    val = ""
    for a in response["answers"]:
        val += ",('{}','{}','{}','{}')".format(uid,a["qid"],a["ans"],str(datetime.datetime.now()).split('.')[0])
    log.info("query: {}".format(query.save_response_ins.format(val[1:])))
    ok = db_insup(query.save_response_ins.format(val[1:]))

    return Response(json.dumps({"msg": ok}), headers=HEADER, status=200, mimetype='application/json')
Пример #11
0
def register_coach_student():
    log.info("/register_coach_student")
    pretty_print_POST(request)
    response = json.loads(request.data)
    send_data = []
    for ath in response["athlete_ids"]:
        statement = query.register_coach_student.format(ath,response["userid"],\
                    str(datetime.datetime.now()).split('.')[0],response["type_id"])   
        log.info("query: {}".format(statement))
        if db_insup(statement):
            send_data.append(ath)

    return Response(json.dumps({"inserted": send_data}), headers=HEADER, status=200, mimetype='application/json')
Пример #12
0
def register_user_info():
    log.info("/register_user_info")
    pretty_print_POST(request)
    response = json.loads(request.data)
    for_users_info_table_vals = "('{}',{},'{}',{},{},'{}','{}',{})".\
                                format(response["userid"],response["age"],\
                                response["gender"],response["height"],response["weight"],\
                                response["s_id"],response["org"],response["role"])
    statement = query.register_user_info.format(for_users_info_table_vals)
    log.info("query: {}".format(statement))
    ok = db_insup(statement)

    return Response(json.dumps({"register": ok}), headers=HEADER, status=200, mimetype='application/json')
Пример #13
0
def pickup_item():
    resp = {"msg": "OK"}
    contents = request.json
    upd_qty = {}
    for pickup in contents["scheduled_pickups"]:
        statement = "select resource_id, quantity from procurement \
        where donor_id='{}' and status='N'".format(pickup["doner_id"])
        result = db_fetch(statement)
        statement = "update procurement set status='P' where donor_id='{}'"\
        .format(pickup["doner_id"])
        ## TODO update pickup schedule in db
        db_insup(statement)
        for res in result:
            if res[0] not in upd_qty:
                upd_qty[res[0]] = int(res[1])
            else:
                upd_qty[res[0]] += int(res[1])
    update_procurement(upd_qty)
    return Response(json.dumps(resp),
                    headers=HEADER,
                    status=200,
                    mimetype='application/json')
Пример #14
0
def compute_resource_helper(disaster):
    ''' Computes required resources based on calamity and required resources'''
    disaster_type = disaster['disaster_type']
    category = disaster['category']
    population = int(disaster['population'])
    items = templates.resource_requirements[disaster_type][category]["items"]
    recovery_time = templates.resource_requirements[disaster_type][category][
        "recovery_time"]
    required_items = {}
    for item, qty in items.iteritems():
        required_items[item] = int(population * qty * recovery_time)
        log.info("required_items: {}".format(required_items[item]))
    query = "select name, deficit, current_inventory, storage_id from resource where name in (" + str(
        items.keys())[1:-1:] + ") and storage_id = '1'"
    log.info("compite_resource_query_fetch: {}".format(query))
    result = db_fetch(query)
    for row in result:
        if (required_items[row[0]] < row[2]):
            query = "update resource set deficit=" + \
                str(int(row[2]) + required_items[row[0]]) + \
                " where name='" + row[0] + "';"
            log.info("compute_resource_query_insup: {}".format(query))
            db_insup(query)
Пример #15
0
def edit_qstn_response():
    pretty_print_POST(request)
    log.info("/edit_qstn_response")
    response = json.loads(request.data)
    uid = response["user_id"]
    send_response = []
    for a in response["answers"]:
        statement = query.edit_qstn_response.format(a["ans"],uid,a["qid"])
        log.info("query: {}".format(statement))
        ok = db_insup(statement)
        if ok:
            send_response.append(a["qid"])

    return Response(json.dumps({"updated_qids":send_response}), headers=HEADER, status=200, mimetype='application/json')
Пример #16
0
def register_injury():
    log.info("/register_injury")
    pretty_print_POST(request)
    response = json.loads(request.data)
    if response["date"]:
        date = response["date"]
    else:
        date = str(datetime.datetime.now()).split('.')[0]
    val = "('{}','{}','{}','{}','{}','{}',{})".format(response["userid"],response["desc"],\
          date,response["type"],response["location"],response["region"],response["intensity"])
    statement = query.register_injury.format(val)
    log.info("query: {}".format(statement))
    ok = db_insup(statement)

    return Response(json.dumps({"msg": ok}), headers=HEADER, status=200, mimetype='application/json')
Пример #17
0
def post_event():
    log.info("/post_event")
    pretty_print_POST(request)
    response = json.loads(request.data)
    start_date = '-'.join([response["start"]["year"],response["start"]["month"],response["start"]["day"]])
    start_time = ':'.join([response["start"]["hours"],response["start"]["minutes"],response["start"]["seconds"]])
    start = ' '.join([start_date,start_time])
    end_date = '-'.join([response["end"]["year"],response["end"]["month"],response["end"]["day"]])
    end_time = ':'.join([response["end"]["hours"],response["end"]["minutes"],response["end"]["seconds"]])
    end = ' '.join([end_date,end_time])
    created = str(datetime.datetime.now()).split('.')[0]
    
    vals = "('{}','{}','{}','{}','{}','{}')".format(start,created,response["desc"],response["title"],end,response["userid"])
    statement = query.post_event.format(vals)
    log.info("query: {}".format(statement))
    ok = db_insup(statement)

    return Response(json.dumps({"event_created": ok}), headers=HEADER, status=200, mimetype='application/json')
Пример #18
0
def insert_user_health_stats(userid=None, do_scale=False):
    f = open('One_Year_of_FitBitChargeHR_Data.csv', 'rb')
    reader = csv.reader(f)
    q = "insert into health_metrics values ('{}','{}','{}','{}','{}','{}','{}','{}','{}','{}','{}')"
    for i,row in enumerate(reader):
        scale = 1.0
        if i==0:
            continue
        if do_scale:
            scale = random.uniform(0.5,1.0)

        date = '-'.join([row[0].split('-')[1],row[0].split('-')[0],row[0].split('-')[2]])
        calorie,steps,dist,floors,m_sitting,m_slow,m_mod,m_int,cal_act = convert_float(row[1],scale),\
        convert_float(row[2],scale),convert_float('.'.join(row[3].split(',')),scale),convert_float(row[4],scale),\
        convert_float(row[5],scale),convert_float(row[6],scale),convert_float(row[7],scale),convert_float(row[8],scale),\
        convert_float(row[9],scale)
        
        statement = q.format(date,userid,calorie,steps,floors,dist,m_sitting,m_slow,m_mod,m_int,cal_act)
        log.info("query: {}".format(statement))
        ok = db_insup(statement)
        log.info("row {}: {}".format(i,ok))