Exemplo n.º 1
0
def new_widget(request_data: dict) -> dict:
    """ Add the widget to the database and return the new widget object

    'quantity' is an optional attribute and should be set to 0 if not included.
    If the POST data is bad, re-raise the WidgetError with a 400 status code.
    If the widget already exists, raise a WidgetError with a 422 status code.
    """

    # validate that the POST data is any good and get the name and quantity from it
    try:
        utils.validate_data('post_widget', request_data)
        new_widget_name = request_data['name']

        if 'quantity' in request_data:
            new_widget_quantity = request_data['quantity']
        else:
            new_widget_quantity = 0

    except exceptions.WidgetError as err:
        # the only error we're going to get is the validation error at this point
        raise err

    # see if a widget with that name already exists
    try:
        utils.validate_widget_name(new_widget_name)

        # add the new widget to the DB
        logger.debug(f'adding new widget: name: {new_widget_name}, quantity: {new_widget_quantity}')
        db.get_db().insert_widget(widget_name=new_widget_name, widget_quantity=new_widget_quantity)

        return db.get_db().get_widget_by_name(widget_name=new_widget_name)
    
    except db.exceptions.DBError as err:
        logging.error(f'error accessing database: {err}')
        raise exceptions.WidgetError(500, err)
Exemplo n.º 2
0
def post():
    db = get_db()
    resident = db.get_resident()

    driver = create_driver()
    visitors = request.json

    responses = []
    for visitor in visitors:
        fields_to_submit = visitor.copy()
        fields_to_submit.pop("_id")

        if current_app.config["ENV"] == "development":
            succeeded, msg = _fake_submit(visitor)
        else:
            logging.info(f"Submitting parking info for {visitor}")
            succeeded, msg = submit_visitor_info(driver, resident, fields_to_submit)

        response = _create_response(visitor, succeeded, msg)
        responses.append(response)
        logging.debug(response)

        if response["succeeded"]:
            db.add_history(visitor)

    return jsonify(responses)
Exemplo n.º 3
0
def get_by_id(table_name, id_field, id_value, fields=None):
    """
    Check if there is some record on the table with the id.

    Args:
        table_name (str): Name of the table that will be used in the verification.
        if_field (str): Name of the id field that will be used to check the value.
        id_value (int): Value of the id that will be searched on the id field of the table.

    Returns:
        True - id exists.
        False - id not exists.
    """
    if not id_value:
        return None

    cursor = get_db().cursor()

    sql_command = 'SELECT {} FROM {} WHERE {} = {}'.format(
        '*' if not fields else ', '.join(fields), table_name, id_field,
        id_value)
    result = cursor.execute(sql_command).fetchone()

    if result:
        return dict(result)

    return None
Exemplo n.º 4
0
    def save(self):
        """Save the Phone Bill data on the database."""
        db = get_db()
        cursor = db.cursor()

        existent_period = self.exists_period()
        result = None
        if existent_period:
            self.id = existent_period
        else:
            fields = ['phone_number', 'period']

            sql_command = 'INSERT INTO {} ({}) VALUES ({})'.format(
                self.TABLE_NAME, ', '.join(fields),
                ', '.join(['?'] * len(fields)))
            values = [self.phone_number, self.period]
            result = cursor.execute(sql_command, values)

        if result and result.rowcount <= 0:
            return False
        elif result:
            self.id = result.lastrowid

        for call in self.record_calls:
            call.bill_id = self.id
            call.save()

        db.commit()

        return True
Exemplo n.º 5
0
def project_delete(project_id):
    '''Deletes a project'''
    token_data = get_data_from_token(request.headers,
                                     current_app.config['SECRET_KEY'])
    if 'error' in token_data:
        return jsonify({'error':
                        token_data['error']}), token_data['status_code']

    if token_data['type'] != 'access':
        return jsonify({'error': 'Invalid token type'}), 401

    db_conn = get_db(current_app, g)
    project = get_project(db_conn, project_id)

    if project is None:
        return jsonify({'error': 'Project does not exist'}), 400

    if project['user_id'] != token_data['sub']:
        return jsonify({'error':
                        'Forbidden: project belongs to another user'}), 403

    delete_project(db_conn, project_id)
    db_conn.commit()

    return jsonify({'message': 'Success'}), 200
Exemplo n.º 6
0
def test_history(app, client):
    with app.app_context():
        db = get_db()

        # Check that history is empty
        resp = client.get("/permit/history")
        assert resp.status_code == 200
        assert resp.get_json() == []

        # Check that the api can retrieve records
        visitors = [
            _create_dummy_visitor("mike jones"),
            _create_dummy_visitor("carl clarkson"),
            _create_dummy_visitor("sean dew"),
        ]
        for visitor in visitors:
            db.insert_visitor(visitor)
        times = [datetime.now(), datetime.now() - timedelta(3)]
        db.add_history(visitors[0], times[0].timestamp())
        db.add_history(visitors[1], times[0].timestamp())
        db.add_history(visitors[2], times[1].timestamp())
        visitors = [format_generic_record(visitor) for visitor in visitors]
        expected_response = [
            {
                "date": format_history_date(times[0]),
                "visitors": [visitors[0], visitors[1]],
            },
            {"date": format_history_date(times[1]), "visitors": [visitors[2]]},
        ]
        resp = client.get("/permit/history")
        assert resp.status_code == 200
        assert resp.get_json() == expected_response
Exemplo n.º 7
0
def create():
    name = request.json['name']
    phone = request.json['phone']
    email = request.json['email']
    city = request.json['city']
    state = request.json['state']
    street = request.json['street']
    site = request.json['site']
    lat = request.json['lat']
    lng = request.json['lng']

    id = uuid.uuid1()
    rating = 0

    db = get_db()
    db.execute(
        """
        insert into restaurant(id, rating, name, site, email, phone, street, city, state, lat, lng)
        values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);
        """,
        (str(id), rating, name, site, email, phone, street, city, state, lat, lng)
    )
    db.commit()

    response = {
        'status': 'success',
        'message': 'Restaurant added.'
    }

    return jsonify(response)
Exemplo n.º 8
0
def save_project():
    '''Saves a brand new project'''
    token_data = get_data_from_token(request.headers,
                                     current_app.config['SECRET_KEY'])
    if 'error' in token_data:
        return jsonify({'error':
                        token_data['error']}), token_data['status_code']

    if token_data['type'] != 'access':
        return jsonify({'error': 'Invalid token type'}), 401

    json_data = request.get_json()
    db_conn = get_db(current_app, g)

    # return an error if the user already has a project with that name
    if get_project_id(db_conn, token_data['sub'], json_data['name']):
        return jsonify({'error':
                        'A project with that name already exists'}), 400

    project = {
        'name': json_data['name'],
        'user_id': token_data['sub'],
        'shared': json_data['shared'],
        'data': json.dumps(json_data)
    }

    insert_project(db_conn, project)

    project_id = get_project_id(db_conn, token_data['sub'],
                                json_data['name'])[0]

    db_conn.commit()

    return jsonify({'message': 'Success', 'projectId': project_id}), 201
Exemplo n.º 9
0
def majors():
    db = get_db()
    data = db.child('majors').get().val()
    if not data:
        data = {}

    return jsonify(message=data), 200
Exemplo n.º 10
0
def login():
    if request.method == "POST":
        username = request.form["username"]
        password = request.form["password"]

        db = get_db()
        error = None

        user = db.execute("SELECT * FROM user where username = ?",
                          (username, )).fetchone()

        if user is None:
            error = "Incorrect username."
        elif not check_password_hash(user["password"], password):
            error = "Incorrect password."

        if error is None:
            session.clear()
            session["user_id"] = user["id"]
            #return redirect(url_for("index"))
            return redirect(url_for("login"))

        flash(error)

    return render_template("auth/login.html")
Exemplo n.º 11
0
def get_details(email):
    print email
    d = db.get_db()
    cursor = d.cursor()
    cursor.execute(
        'SELECT `id`, `username`, `about`, `isAnonymous`, `name` FROM `user` '
        + 'WHERE `email` = %s;', [
            email,
        ])
    user = cursor.fetchone()
    if user is None:
        return json.dumps({'code': 1, 'response': 'Such user wasn\'t found.'})
    user_id = user[0]
    return json.dumps({
        'code': 0,
        'response': {
            'id': user_id,
            'email': email,
            'username': user[1],
            'about': user[2],
            'isAnonymous': bool(user[3]),
            'name': user[4],
            'followers': get_user_followers(user_id, d),
            'following': get_user_following(user_id, d),
            'subscriptions': [],
        }
    })
Exemplo n.º 12
0
def upcoming_events():
    db = get_db()
    user_uid = session.get('user_uid')
    events = db.child('event_user').child(user_uid).get().val()

    data = []
    if events:
        for event in events:
            event_info_ord = db.child('events').child(event).get().val()
            event_timeEnd = datetime.strptime(event_info_ord['timeEnd'],
                                              '%H:%M %d %B %Y')

            if event_timeEnd >= datetime.now():
                event_info = dict(event_info_ord)
                event_info.update({'id': event})

                org_info = db.child('orgs').child(
                    event_info['org']).get().val()
                event_info.update({'avatar': org_info['avatar']})

                convos_data = get_convo_event(db, user_uid, event)
                event_info.update({'convos': convos_data})

                data.append(event_info)

    return jsonify(message=data), 200
Exemplo n.º 13
0
def avail_events_org(org_uid):
    db = get_db()
    user_uid = session.get('user_uid')
    events_users = db.child('event_user').child(user_uid).get().val()
    events_orgs = db.child('event_org').child(org_uid).get().val()

    data = []
    if events_orgs:
        if not events_users:
            events_users = {}

        events = set(events_orgs) - set(events_users)

        for event in events:
            event_info_ord = db.child('events').child(event).get().val()
            event_timeDeadline = datetime.strptime(
                event_info_ord['timeDeadline'], '%H:%M %d %B %Y')

            if event_timeDeadline >= datetime.now():
                event_info = dict(event_info_ord)
                event_info.update({'id': event})

                data.append(event_info)

    return jsonify(message=data), 200
Exemplo n.º 14
0
def project_update():
    '''Makes changes to an existing project'''
    token_data = get_data_from_token(request.headers,
                                     current_app.config['SECRET_KEY'])
    if 'error' in token_data:
        return jsonify({'error':
                        token_data['error']}), token_data['status_code']

    if token_data['type'] != 'access':
        return jsonify({'error': 'Invalid token type'}), 401

    json_data = request.get_json()
    db_conn = get_db(current_app, g)
    project = get_project(db_conn, json_data['id'])

    if project is None:
        return jsonify({'error': 'Project does not exist'}), 404

    if token_data['sub'] != project['user_id']:
        return jsonify({'error':
                        'Forbidden: project belongs to another user'}), 403

    updated_project = {
        'id': json_data['id'],
        'name': json_data['name'],
        'shared': json_data['shared'],
        'data': json.dumps(json_data)
    }

    update_project(db_conn, updated_project)

    db_conn.commit()

    return jsonify({'message': 'Success'}), 200
Exemplo n.º 15
0
def events(event_uid):
    db = get_db()
    user_uid = session.get('user_uid')

    if request.method == 'POST':
        signup_cancel = request.get_json(
            force=True)['new_data']  #...sign up vs cancel?
        print(f'Signup Cancel: {signup_cancel}')
        try:
            event = db.child('events').child(event_uid).get().val()
            event_timeDeadline = datetime.strptime(event['timeDeadline'],
                                                   '%H:%M %d %B %Y')
            if event_timeDeadline >= datetime.now(
            ):  # If deadline has not passed
                if signup_cancel == True:  # User wants to sign up
                    db.child('event_user').child(user_uid).update(
                        {event_uid: True})
                    db.child('user_event').child(event_uid).update(
                        {user_uid: True})
                elif signup_cancel == False:  # User wants to cancel
                    db.child('event_user').child(user_uid).update(
                        {event_uid: None})
                    db.child('user_event').child(event_uid).update(
                        {user_uid: None})
                return jsonify(message=True), 200
            else:
                return jsonify(message=False), 400

        except Exception as e:
            print(e)
            return jsonify(message=False), 400

    data = dict(db.child('events').child(event_uid).get().val())
    data.update({'event_uid': event_uid})
    return jsonify(message=data), 200
Exemplo n.º 16
0
    def get(self):
        """
        Return PointsFeature of all the sites from the survey
        """
        db = get_db()

        query = """
            select *
            from sites_0809;
            """
        cursor = db.execute(query)
        results = cursor.fetchall()

        points = []
        for item in results:
            row = dict(item)
            dd = Feature(
                geometry=Point(
                    (float(row.pop("LON_DD83")), float(row.pop("LAT_DD83")))
                ),
                properties=row,
            )
            points.append(dd)

        return FeatureCollection(points)
Exemplo n.º 17
0
def delete():
    if 'id' not in request.json:
        response = {
            'status': 'error',
            'message': 'No id specified.'
        }

        return jsonify(response)

    restaurant = get_restaurant(request.json['id'])

    if restaurant is None:
        response = {
            'status': 'error',
            'message': 'Restaurant not found.'
        }

        return jsonify(response)

    db = get_db()
    db.execute('DELETE FROM restaurant WHERE id = ?', (request.json['id']))
    db.commit()

    response = {
        'status': 'success',
        'message': 'Restaurant deleted.'
    }

    return jsonify(response)
Exemplo n.º 18
0
def other_orgs(org_uid):
    db = get_db()
    user_uid = session.get('user_uid')
    if request.method == 'POST':
        # code=str(db.child('orgs').child(org_uid).get().val())
        signup_cancel = request.get_json(force=True)['new_data']
        # signup_cancel = request.get_json(force=True)['new_data'][0]
        # input_code=request.get_json(force=True)['new_data'][1]
        try:
            if signup_cancel == True:
                # if input_code==code:
                db.child('org_user').child(user_uid).update({org_uid: True})
                db.child('user_org').child(org_uid).update({user_uid: True})
            elif signup_cancel == False:
                db.child('org_user').child(user_uid).update({org_uid: None})
                db.child('user_org').child(org_uid).update({user_uid: None})
            return jsonify(message=True), 200
        except Exception as e:
            print(e)
            return jsonify(message=False), 400

    data = dict(db.child('orgs').child(org_uid).get().val())
    if data:
        #admin...? Need to edit database later
        data.update({'id': org_uid, 'admin': False})
        org_users = db.child('user_org').child(org_uid).shallow().get().val()
        if org_users and str(user_uid) in org_users:
            data.update({'joined': True})

    elif not data:
        data = {}
    return jsonify(message=data), 200
Exemplo n.º 19
0
def register():
    """When request method is post get body from request object,
       check if any params are missing, if all are good check if
       username is already registered then insert into database if
       none exist"""
    if request.method == 'POST':
        username = request.form['username']
        email = request.form['email']
        password = request.form['password']
        db = get_db()
        error = None

        if not username:
            error = 'Username is required'
        elif not password:
            error = 'Password is required'
        elif not email:
            error = 'Email 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:
            db.execute(
                'INSERT INTO user (username, email, password) VALUES (?, ?, ?)',
                (username, email, generate_password_hash(password)))
            db.commit()
            return redirect(url_for('auth.login'))
        flash(error)

    return render_template('auth/register.html')
Exemplo n.º 20
0
def register():
    '''Register a new user'''
    json_data = request.get_json()
    if not json_data:
        return jsonify({'error': 'Request body must be json.'}), 400

    if not all(k in json_data for k in ('email', 'password')):
        return jsonify({'error': 'Request must contain email and password'}), 400

    if len(json_data['password']) < 6:
        return jsonify({'error': 'Password must be at least six characters'}), 400

    try:
        v_email = validate_email(json_data['email'])
        email = v_email['email']
    except EmailNotValidError as err:
        return jsonify({'error': str(err)}), 400

    db_conn = get_db(current_app, g)

    if email_exists(db_conn, email):
        return jsonify({'error': 'A user with that email already exists'}), 400

    json_data['email'] = email

    add_user(db_conn, json_data)
    return jsonify({'message': 'Success', 'email': json_data['email']}), 201
Exemplo n.º 21
0
def get_widget(widget_id: int) -> dict:
    """ Return the widget object with the corresponding integer ID

    If the widget doesn't exist, return a WidgetError with a 404 status code.
    If the ID isn't an integer, return a TypeError.
    If the ID is smaller than 1, return a ValueError.
    """
    
    # check to make sure the widget_id is valid
    if type(widget_id) is not int:
        logger.debug(f'{widget_id} is not an integer')
        raise TypeError('widget_id must be a positive integer greater than zero')

    if widget_id < 1:
        logger.debug(f'{widget_id} is an integer but is smaller than one')
        raise ValueError('widget_id must be a positive integer greater than zero')

    try:
        widget = db.get_db().get_widget_by_id(widget_id=widget_id)
    
    except db.exceptions.DBError as err:
        logging.error(f'error accessing database: {err}')
        raise exceptions.WidgetError(500, err)

    if widget is None:
        raise exceptions.WidgetError(404, f'widget with ID {widget_id} not found')
    else:
        return widget
Exemplo n.º 22
0
def test_save_visitor(app, client):
    with app.app_context():
        db = get_db()

        visitor = _create_dummy_visitor()
        resp = client.post("/visitor", json=visitor)
        assert resp.status_code == 201
        assert len(db.get_visitors()) == 1
Exemplo n.º 23
0
def get_item(id):
    item = get_db().execute(
        'SELECT id, name, price, description, stock'
        ' FROM item WHERE id = ?', (id, )).fetchone()

    if item is None:
        abort(404, f"Item id {id} doesn't exist")
    return item
Exemplo n.º 24
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()
Exemplo n.º 25
0
def test_save_resident(app, client):
    with app.app_context():
        db = get_db()

        resident = _create_dummy_resident()
        resp = client.post("/resident", json=resident)
        assert resp.status_code == 201
        assert db.get_resident()
Exemplo n.º 26
0
def load_logged_in_user():
    """checks to see if user exists in session"""
    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()
Exemplo n.º 27
0
def inc_image(img_id, type):
    db = get_db()
    image = db.execute('SELECT * FROM image WHERE id = (?)',
                       (img_id, )).fetchone()
    db.execute(f'UPDATE image SET {type} = (?) WHERE id = (?)', (
        int(image[type] + 1),
        img_id,
    ))
    db.commit()
    return ''
Exemplo n.º 28
0
def load_logged_in_user():
    user_id = session.get("user_id")

    if user_id is None:
        g.user = None
    else:

        db = get_db()
        g.user = db.execute("SELECT * FROM user where id = ",
                            (user_id, )).fetchone()
Exemplo n.º 29
0
def get_restaurant(id):
    restaurant = get_db().execute(
        """
        select name, phone, email, city, state, street, site, lat, lng
        from restaurant
        where id = ?;
        """,
        (id)
    ).fetchone()

    return restaurant
Exemplo n.º 30
0
def get_user_followers(user_id, d=None):
    if d is None:
        d = db.get_db()
    cursor = d.cursor()
    cursor.execute(
        'SELECT `user`.`email` FROM `following` JOIN `user` ' +
        'ON `user`.`id` = `following`.`follower` WHERE `following`.`followee` = %s;',
        [
            user_id,
        ])
    d.commit()
    return [user[0] for user in cursor.fetchall()]