コード例 #1
0
def delete_user(user_id):
    """
    Deletes user's records from the database
    Args:
        user_id (str): a users uuid
    Returns:
        None
    Raises:
        BadRequestError: if the user_id isn't a valid uuid
        NotFoundError: if no record can be found for the given user id
    """
    try:
        UUID(user_id)
    except ValueError as e:
        logger.warning("Invalid uuid, received error: {}".format(e))
        raise BadRequestError

    with db_session() as session:
        logger.info("Deleting user data from users and user_data tables...")
        count = session.query(Users).filter_by(user_id=user_id).delete()

        if not count:
            logger.warning(
                "User {} was not found in the database".format(user_id))
            raise NotFoundError

        logger.info("User successfully deleted from database")
        return Response(body=None, status_code=204, headers=dict())
コード例 #2
0
def get_user(user_id):
    """
    Retrieves all of a given users data
    Args:
        user_id (str): a users uuid
    Returns:
        dict: a dictionary containing all of a users information
    Raises:
        BadRequestError: if the user_id isn't a valid uuid
        NotFoundError: if no record can be found for the given user id
    """
    try:
        UUID(user_id)
    except ValueError as e:
        logger.warning("Invalid uuid, received error: {}".format(e))
        raise BadRequestError

    with db_session() as session:
        logger.info("Retrieving user information...")
        result = session.query(UserData.field_type, UserData.field_data,
                               UserData.user_id).filter_by(user_id=user_id)

        if not result.count():
            logger.warning(
                "User {} was not found in the database".format(user_id))
            raise NotFoundError

        logger.info("User data retrieved")
        user_data = User(strict=True).dump(result).data

        return dict(meta=dict(limit=1, offset=0, count=1), data=user_data)
コード例 #3
0
def user_data(request):
    data = [
        UserData(field_type='emailAddress',
                 field_data='*****@*****.**',
                 user_id=user_id_1),
        UserData(field_type='firstName', field_data='Nick', user_id=user_id_1),
        UserData(field_type='lastName', field_data='Plutt', user_id=user_id_1),
        UserData(field_type='address',
                 field_data='200 Grand Avenue',
                 user_id=user_id_1),
        UserData(field_type='emailAddress',
                 field_data='*****@*****.**',
                 user_id=user_id_2),
        UserData(field_type='firstName', field_data='John', user_id=user_id_2),
        UserData(field_type='lastName', field_data='Bones', user_id=user_id_2),
        UserData(field_type='phone number',
                 field_data='612-584-9642',
                 user_id=user_id_2),
        UserData(field_type='emailAddress',
                 field_data='*****@*****.**',
                 user_id=user_id_3),
        UserData(field_type='firstName', field_data='Tim', user_id=user_id_3),
        UserData(field_type='lastName', field_data='Allen', user_id=user_id_3),
        UserData(field_type='emailAddress',
                 field_data='*****@*****.**',
                 user_id=user_id_4),
        UserData(field_type='firstName', field_data='Chew', user_id=user_id_4),
        UserData(field_type='lastName', field_data='Bacca', user_id=user_id_4),
        UserData(field_type='phone number',
                 field_data='612-584-5496',
                 user_id=user_id_4),
        UserData(field_type='emailAddress',
                 field_data='*****@*****.**',
                 user_id=user_id_5),
        UserData(field_type='firstName', field_data='Luke', user_id=user_id_5),
        UserData(field_type='lastName',
                 field_data='Skywalker',
                 user_id=user_id_5),
        UserData(field_type='emailAddress',
                 field_data='*****@*****.**',
                 user_id=user_id_6),
        UserData(field_type='firstName', field_data='Mace', user_id=user_id_6),
        UserData(field_type='lastName', field_data='Windu', user_id=user_id_6)
    ]

    with db_session() as session:
        session.add_all(data)
        session.commit()

    def teardown():
        with db_session() as session:
            session.query(UserData).delete()
            session.commit()

    request.addfinalizer(teardown)
コード例 #4
0
def get_users(query_params):
    """
    Retrieves data for all user's who have an attribute that matches the
    searchText
    Args:
        query_params (dict): a dictionary containing all of the query params
    Returns:
        list: list of dicts containing users information
    Raises:
        None
    """
    query_params = query_params if query_params else dict()
    logger.info(
        "Retrieving user information with query params of {}...".format(
            query_params))

    limit = query_params.get('limit', 25)
    offset = query_params.get('offset', 0)
    search_text = query_params.get('searchText')
    search_field = query_params.get('searchField')

    with db_session() as session:
        logger.info("Constructing text search sub query...")
        search_sub_query = session.query(UserData.user_id)

        if search_text:
            logger.info("Searching fields for text...")
            search_text = unquote(search_text)
            search_sub_query = search(search_sub_query, search_text, sort=True)
        if search_field:
            logger.info("Filtering results by searched field...")
            search_field = unquote(search_field)
            search_sub_query = search_sub_query.filter_by(
                field_type=search_field)

        logger.info("Applying offset and limit on subquery...")
        search_sub_query = search_sub_query.distinct().offset(offset).limit(
            limit).subquery()

        logger.info("Retrieving users info from database...")
        result = session.query(
            UserData.field_type, UserData.field_data, UserData.user_id).filter(
                UserData.user_id == search_sub_query.c.user_id)

        logger.info("Users data retrieved")
        users_data = User(strict=True).dump(result, many=True).data

        return dict(meta=dict(limit=limit,
                              offset=offset,
                              count=len(users_data)),
                    data=users_data)
コード例 #5
0
def create_user(json_body):
    """
    Inserts user into the users table and insert's the user's meta data
    into the meta_data table.
    Args:
        json_body (dict): a dict representing the json body
    Returns:
        chalice.Response: response object with status code and headers
    Raises:
        BadRequestError: if the provided data is malformed or invalid
        ConflictError: if the user already exists or if the user data is malformed
        ChaliceViewError: if something goes wrong when inserting the records
    """
    try:
        logger.info("Validating json body...")
        user_info, user_meta_data = User(strict=True).load(json_body).data
    except ValidationError as e:
        logger.warning("Invalid json body, received error: {}".format(e))
        raise BadRequestError

    with db_session() as session:
        try:
            user_insert = insert(Users)
            user_data_insert = insert(UserData)

            logger.info("Inserting data into the user table...")
            session.execute(user_insert, user_info)

            logger.info("Inserting data into the user_data table...")
            session.execute(user_data_insert, user_meta_data)

            session.commit()
        except IntegrityError as e:
            logger.warning(
                "User or user data already exists, received error: {}".format(
                    e))
            raise ConflictError
        except Exception as e:
            logger.critical("Something went wrong when retrieving user data, "
                            "received error: {}".format(e))
            raise ChaliceViewError

        logger.info("Data successfully inserted")

    return Response(
        body=None,
        status_code=201,
        headers=dict(Location='/users/{}'.format(str(user_info['user_id']))))
コード例 #6
0
def users(request):
    data = [
        Users(user_id=user_id_1,
              email_address='*****@*****.**',
              first_name='nick',
              last_name='plutt'),
        Users(user_id=user_id_2,
              email_address='*****@*****.**',
              first_name='john',
              last_name='bones'),
        Users(user_id=user_id_3,
              email_address='*****@*****.**',
              first_name='tim',
              last_name='allen'),
        Users(user_id=user_id_4,
              email_address='*****@*****.**',
              first_name='chew',
              last_name='bacca'),
        Users(user_id=user_id_5,
              email_address='*****@*****.**',
              first_name='luke',
              last_name='skywalker'),
        Users(user_id=user_id_6,
              email_address='*****@*****.**',
              first_name='mace',
              last_name='weindu')
    ]

    with db_session() as session:
        session.add_all(data)
        session.commit()

    def teardown():
        with db_session() as session:
            session.query(Users).delete()
            session.commit()

    request.addfinalizer(teardown)
コード例 #7
0
 def teardown():
     with db_session() as session:
         session.query(UserData).delete()
         session.commit()