Esempio n. 1
0
def register_whClient():
    if request.method == 'POST':
        clientUrl = request.json['clientUrl']
        error = None

        if not clientUrl:
            error = 'Webhook client url required'

        if error is not None:
            return (error, 400)

        else:
            db = get_db()
            db.execute('INSERT INTO webhook_clients (url) VALUES (?)',
                       (clientUrl, ))
            db.commit()
    if request.method == 'DELETE':
        clientUrl = request.json['clientUrl']
        error = None

        if not clientUrl:
            error = 'Webhook client url required'

        if error is not None:
            return (error, 400)

        else:
            # en caso de que no exista el registro, notificarlo
            db = get_db()
            db.execute('DELETE FROM webhook_clients WHERE url = ?',
                       (clientUrl, ))
            db.commit()

    return ("Client registry deleted", 200)
Esempio n. 2
0
def manage_people():
    if request.method == 'POST':
        macaddr = request.json['macaddr']
        name = request.json['name']
        error = None

        if not macaddr or not name:
            error = 'Mac address and device name are required'

        if error is not None:
            return (error, 400)
        
        else:
            db = get_db()
            db.execute(
                'INSERT INTO people (macaddr, name) VALUES (?, ?)',
                (macaddr, name)
            )
            db.commit()
            return("Person successfuly registered", 200)
    if request.method == 'GET':
        error = None
        db = get_db()
        cursor = db.cursor()
        cursor.execute(
            'SELECT * FROM people'
        )
        rows = cursor.fetchall()
        data = []
        for row in rows:
            data.append({"macaddr":row['macaddr'], 
                         "name":row['name']
                         })
        return json.dumps(data)
        if error is not None:
            return (error, 400)

            
    if request.method == 'DELETE':
        macaddr = request.json['macaddr']
        name = request.json['name']
        error = None

        if not macaddr or not name:
            error = 'Mac address and person name are required'

        if error is not None:
            return (error, 400)
        
        else:
            db = get_db()
            db.execute(
                'DELETE FROM people  WHERE macaddr = ? AND  name = ?',
                (macaddr, name)
            )
            db.commit()
            return("Person registry deleted", 200)

    return("Server error", 500)
def delete_record(record_id):
    # TODO: Sanitychecks, i.e. if recordid exists
    db = get_db()
    db.execute('DELETE FROM record WHERE id = ?', (record_id, ))
    db.commit()
    flash(u'The record has been deleted!', 'success')
    return get_records()
Esempio n. 4
0
def qsub():
    db = get_db()
    qsub_data = request.get_json()
    db.execute('insert into job (name, command) values (?, ?)',
               (qsub_data['name'], qsub_data['command']))
    db.commit()
    return "OK"
Esempio n. 5
0
def create_mongo_indexes():
    '''
  Index the tables in Mongo to optimize query performance
  '''
    db = get_db()
    db.testimonies.create_index('testimony_id')
    db.tokens.create_index('testimony_id')
Esempio n. 6
0
def register():
    """Register a new user.
    Validates that the username is not already taken. Hashes the
    password for security.
    """
    if request.method == "POST":
        username = request.form["username"]
        password = request.form["password"]
        gender = request.form["gender"]
        birthday = request.form['birthday']
        db = get_db()
        error = None
        if not username:
            error = 'Username is required.'
        elif not password:
            error = 'Password is required.'
        elif  db.execute(
            'SELECT UserId FROM storeowner WHERE username = ?', (username,)
        ).fetchone() is not None:
            error = 'User {} is already registered.'.format(username)

        if error is None:
            db.execute(
                "INSERT INTO storeowner (username, password,Gender, Birthday) VALUES (?,?,?,?)",
                (username, generate_password_hash(password),gender,birthday)
            )
            db.commit()
            return 'success'
        return error
    else:
        return render_template("auth/register.html")
Esempio n. 7
0
def generate_slice_report():
    if request.method == 'GET':
        error = None
        db = get_db()
        cursor = db.cursor()
        try:
            date_hour = request.args['date_hour']
            cursor.execute('SELECT * FROM slice WHERE date_hour = ?',
                           (date_hour, ))
        except:
            cursor.execute('SELECT * FROM slice')
        rows = cursor.fetchall()
        data = []
        for row in rows:
            data.append({
                "date_hour": row['date_hour'],
                "floor0": row['floor0'],
                "floor1": row['floor1'],
                "floor2": row['floor2'],
                "floor3": row['floor3']
            })
        return json.dumps(data)
        if error is not None:
            return (error, 400)
    return ("Server error", 500)
Esempio n. 8
0
def set_user_love():
    if request.method == 'POST':
        user_id = session.get('user_id')
        store_id = request.form['storeid']
        db = get_db()

        res = db.execute(
            'SELECT * FROM user_loves_store WHERE user_UserId=? and store_StoreId=?',
            (
                user_id,
                store_id,
            )).fetchone()
        if not res:
            db.execute(
                'INSERT INTO user_loves_store (store_StoreId, user_UserId) VALUES(?,?)',
                (
                    store_id,
                    user_id,
                ))
            db.commit()
        else:
            db.execute('DELETE FROM user_loves_store WHERE ID=?',
                       (res['ID'], ))
            db.commit()
        return 'success'
    return 'error'
Esempio n. 9
0
def items():
    '''Fetch tree data'''
    db = get_db()
    try:
        return jsonify(list(db.fragments.find({}, {'_id': 0})))
    except Exception:  #pylint: disable=broad-except
        return jsonify({'err': 'tree fragment fetch error'})
Esempio n. 10
0
def slice_table_helper(locationdata):
    db = get_db()
    date_hour = datetime.datetime.now().strftime("%Y-%m-%d %H")
    exists = db.execute("SELECT EXISTS(SELECT 1 FROM slice WHERE date_hour=?)",
                        (date_hour, ))
    if (exists.fetchone()[0] == 0):
        db.execute('INSERT INTO slice (date_hour)'
                   ' VALUES (?)', (date_hour, ))
        db.commit()

    print("{} tiene {} dispositivos".format(
        locationdata["data"]["apFloors"][0],
        len(locationdata['data']['observations'])))
    print(locationdata["data"]["apFloors"][0] == "Planta Baja")
    if (locationdata["data"]["apFloors"][0] == "Planta Baja"):
        db.execute('UPDATE slice SET floor0 = ? WHERE date_hour = ?',
                   (len(locationdata['data']['observations']), date_hour))
        db.commit()
    elif (locationdata["data"]["apFloors"][0] == "Piso 1"):
        db.execute('UPDATE slice SET floor1 = ? WHERE date_hour = ?',
                   (len(locationdata['data']['observations']), date_hour))
        db.commit()
    elif (locationdata["data"]["apFloors"][0] == "Piso 2"):
        db.execute('UPDATE slice SET floor2 = ? WHERE date_hour = ?',
                   (len(locationdata['data']['observations']), date_hour))
        db.commit()
    elif (locationdata["data"]["apFloors"][0] == "Piso 3"):
        db.execute('UPDATE slice SET floor3 = ? WHERE date_hour = ?',
                   (len(locationdata['data']['observations']), date_hour))
        db.commit()
    else:
        print("No esta registrado este piso")

    return
Esempio n. 11
0
def register():
    """Register a new user.

    Validates that the username is not already taken. Hashes the
    password for security.
    """
    if request.method == "POST":
        username = request.form["username"]
        password = request.form["password"]
        db = get_db()
        error = None

        if not username:
            error = "Username is required."
        elif not password:
            error = "Password is required."
        elif (db.execute("SELECT id FROM user WHERE username = ?",
                         (username, )).fetchone() is not None):
            error = f"User {username} is already registered."

        if error is None:
            # the name is available, store it in the database and go to
            # the login page
            db.execute(
                "INSERT INTO user (username, password) VALUES (?, ?)",
                (username, generate_password_hash(password)),
            )
            db.commit()
            return redirect(url_for("auth.login"))

        flash(error)

    return render_template("auth/register.html")
Esempio n. 12
0
def filter_testimonies():
    '''Get the distinct levels of each field used in filtering'''
    db = get_db()
    # initialize distinct value arrays
    collections = set()
    genders = set()
    ghetto_names = set()
    camp_names = set()
    recording_years = set()
    interviewee_names = set()
    testimony_ids = set()
    # build the search using any requested filters
    args = get_filter_query(request.args)
    # add each distinct level to the sets initialized above
    for i in db.testimonies.find(args, projections['filters']):
        collections.add(i['collection'])
        genders.add(i['gender'])
        interviewee_names.add(i['interviewee_name'])
        testimony_ids.add(i['testimony_id'])
        recording_years.add(i['recording_year'])
        # handle list fields
        for j in i['ghetto_names']:
            ghetto_names.add(j)
        for j in i['camp_names']:
            camp_names.add(j)
    return jsonify({
        'collections': list(collections),
        'genders': list(genders),
        'ghetto_names': list(ghetto_names),
        'camp_names': list(camp_names),
        'recording_years': list(recording_years),
        'interviewee_names': list(interviewee_names),
        'testimony_ids': list(testimony_ids)
    })
Esempio n. 13
0
def generate_general_report():
    if request.method == 'GET':
        error = None
        db = get_db()
        cursor = db.cursor()
        name = None
        try:
            name = request.args['name']
            cursor.execute('SELECT * FROM visits WHERE name = ?', (name, ))
        except:
            cursor.execute('SELECT * FROM visits')
        rows = cursor.fetchall()
        data = []
        for row in rows:
            data.append({
                "macaddr": row['macaddr'],
                "name": row['name'],
                "timesseen": row['timesseen'],
                "maxstay": row["maxstay"],
                "maxdate": row["maxdate"],
                "minsstay": row["minstay"],
                "mindate": row["mindate"],
                "averagestay": row['averagestay']
            })
        return json.dumps(data)
        if error is not None:
            return (error, 400)
    return ("Server error", 500)
Esempio n. 14
0
def update_question(test_id, question_id, statement, option_a, option_b,
                    option_c, option_d, correct_option):
    db = get_db()
    db.execute(
        "UPDATE questions SET statement = ?, option_a = ?, option_b = ?, option_c = ?, option_d = ?, correct_option = ? WHERE test_id = ? AND question_id = ?",
        (statement, option_a, option_b, option_c, option_d, correct_option,
         test_id, question_id))
    db.commit()
Esempio n. 15
0
def get_records():
    db = get_db()
    records = db.execute(
        'SELECT record.id, sensor.sensorname, timepoint, temperature, humidity, pressure FROM record INNER JOIN sensor on record.sensor_id = sensor.id; '
    ).fetchall()
    return render_template('record/recordlist.html',
                           records=records,
                           showsensorname=True)
Esempio n. 16
0
def testimony():
    '''Fetch a transcript'''
    db = get_db()
    args = {'testimony_id': request.args.get('testimony_id')}
    result = list(db.testimonies.find(args, projections['testimony']))
    if result:
        return jsonify(result[0])
    return jsonify([])
Esempio n. 17
0
def index():
    db = get_db()
    posts = db.execute(
        'SELECT p.id, title, body, created, author_id, username'
        ' FROM post p JOIN user u ON p.author_id = u.id'
        ' ORDER BY created DESC'
    ).fetchall()
    return render_template('records/index.html', posts=posts)
Esempio n. 18
0
def add_question(test_id, question_id, statement, option_a, option_b, option_c,
                 option_d, correct_option):
    db = get_db()
    db.execute(
        "INSERT INTO questions(test_id, question_id, statement, option_a, option_b, option_c, option_d, correct_option) VALUES(?, ?, ?, ?, ?, ?, ?, ?)",
        (test_id, question_id, statement, option_a, option_b, option_c,
         option_d, correct_option))
    db.commit()
Esempio n. 19
0
def load_logged_in_user():
    user_id = session.get('user_id')

    if user_id is None:
        g.user = None
    else:
        g.user = get_db().execute('SELECT * FROM user WHERE id = ?',
                                  (user_id, )).fetchone()
Esempio n. 20
0
def load_logged_in_user():
    user_id = session.get('user_id')
    db = get_db()
    if user_id is None:
        g.user = None
    else:
        g.user = db.execute(
            'SELECT * FROM storeowner WHERE UserId = ?', (user_id,)
        ).fetchone()
Esempio n. 21
0
def load_logged_in_user():
    """If a user id is stored in the session, load the user object from
    the database into ``g.user``."""
    user_id = session.get("user_id")

    if user_id is None:
        g.user = None
    else:
        g.user = (get_db().execute("SELECT * FROM user WHERE id = ?",
                                   (user_id, )).fetchone())
Esempio n. 22
0
def delete_sensor(sensorname):
    db = get_db()
    if sensor_exists(db, sensorname):
        db.execute('DELETE FROM sensor WHERE sensorname = ?', (sensorname, ))
        db.commit()
        flash(u'The sensor has been deleted!', 'success')
        return getsensors()
    else:
        flash(u'The sensor does not exist!', 'error')
        return getsensors()
Esempio n. 23
0
def get_records_for_sensorname(sensorname):
    db = get_db()
    if sensor_exists(db, sensorname):
        records = db.execute(
            'SELECT id, timepoint, temperature, humidity, pressure FROM record WHERE sensor_id = ?',
            (get_sensor_id(db, sensorname), )).fetchall()
        return render_template('record/recordlist.html', records=records)
    else:
        flash(u'The sensor does not exist. Showing all records instead!',
              'error')
        return get_records()
Esempio n. 24
0
def typeahead():
    '''Given a field and a string, return all values
  in the given field that contain the string'''
    db = get_db()
    field = request.args.get('field', None)
    query = request.args.get('query', '')
    if not field:
        return jsonify(['Error: a field is required'])
    search = {field: {'$regex': query}}
    results = db.testimonies.find(search).distinct(field)
    return jsonify(results)
def generate_dummy_data():
    from secrets import choice
    import random
    db = get_db()

    def generate_dummy_sensors():
        names = ['alan', 'adam', 'collin', 'ethan', 'frank', 'homer']
        rooms = ['garage', 'livingroom', 'kitchen', 'bath']
        extender = ['final', 'new', 'old']
        generated_sensors = []
        for i in range(10):
            generated_sensor = "{}_{}".format(choice(names), choice(rooms))
            while generated_sensor in generated_sensors:
                generated_sensor = "{}_{}".format(generated_sensor,
                                                  choice(extender))
            generated_sensors.append(generated_sensor)
        for sensor in generated_sensors:
            db.execute(
                'INSERT INTO sensor (sensorname, description) VALUES (?, "Dummy Sensor!")',
                (sensor, ))
        db.commit()
        return generated_sensors

    def generate_dummy_entries(sensors):
        from time import strftime, localtime
        import datetime

        for sensor in sensors:
            _time = datetime.datetime.now()
            sensor_id = get_sensor_id(db, sensor)
            temperature = random.randint(20, 35)
            humidity = random.random()
            pres = random.randint(900, 1500)
            for i in range(10):
                temperature = temperature + random.uniform(-5, 5)
                humidity = humidity + random.uniform(-0.1, 0.1)
                pres = pres + random.uniform(-10, 10)
                _time = _time - datetime.timedelta(minutes=10)

                # sanity checks
                if humidity > 1:
                    humidity = 1
                elif humidity < 0:
                    humidity = 0

                db.execute(
                    'INSERT INTO record (sensor_id, temperature, humidity, pressure, timepoint) VALUES (?, ?, ?, ?, ?)',
                    (sensor_id, temperature, humidity, pres, _time))
            db.commit()

    sensors = generate_dummy_sensors()
    generate_dummy_entries(sensors)
    flash('The dummy entries have been generated', 'success')
    return render_template('settings/default.html')
Esempio n. 26
0
    def add_link(token):
        db = get_db()

        # Retrieve the link
        body = request.json

        db.execute('INSERT INTO history (person_token, link) VALUES (?, ?)',
                   (token, body["link"]))
        db.commit()

        return "Success"
Esempio n. 27
0
def find_user(email):
    if email is None:
        raise ValueError(
            'Email must be provided to find_user method to make a lookup')

    db = get_db()
    cursor = db.cursor()

    cursor.execute("SELECT * FROM users WHERE email=?", (email, ))

    return cursor.fetchone()
Esempio n. 28
0
def get_sensors(limit = 100):
    db = get_db()
    records = db.execute(
        'SELECT timepoint, AVG(temperature) AS temperature, AVG(humidity) AS humidity, AVG(pressure) AS pressure FROM record GROUP BY strftime(\'%Y-%m-%dT%H:%M:00.000\', timepoint) ORDER BY timepoint DESC LIMIT ?',
        (limit, )
    ).fetchall()
    data = dict()
    data['temperature'] = [record['temperature'] for record in records]
    data['humidity'] = [record['humidity'] for record in records]
    data['pressure'] = [record['pressure'] for record in records]
    data['dates'] = [record['timepoint'] for record in records]
    return render_template('vis/base.html', data=data, sensors = get_all_sensors(db))
Esempio n. 29
0
def delete_user(id):
    if id is None:
        raise ValueError('Id must be provided to delete user')

    db = get_db()
    cursor = db.cursor()

    cursor.execute("DELETE FROM users WHERE id=?", (id, ))

    db.commit()
    # test comment
    return cursor.fetchone()
Esempio n. 30
0
def artists():
    db = get_db()

    sightings = Table('sightings')
    q = Query.from_(sightings).select(
            'artist'
        ).where(
            sightings.user_id == g.user['id']
        ).orderby('artist').distinct()

    results = db.execute(q.get_sql()).fetchall()

    return render_template('sightings/artists.html', results=results)