Пример #1
0
def read_all():

    people = Person.query.order_by(Person.lname).all()

    person_schema = PersonSchema(many=True)
    data = person_schema.dump(people)
    return data
def read_one(person_id):
    """
    This function responds to a request for /api/people/{person_id}
    with one matching person from people
    :param person_id:   Id of person to find
    :return:            person matching id
    """
    # Get the person requested
    person = db.session.query(Person).filter(
        Person.id == person_id).one_or_none()

    # Did we find a person?
    if person is not None:

        # Serialize the data for the response
        person_schema = PersonSchema()
        data = person_schema.dump(person)
        return data

    # Otherwise, nope, didn't find that person
    else:
        abort(
            404,
            "Person not found for Id: {person_id}".format(person_id=person_id),
        )
Пример #3
0
def create(person):
    """
    This function creates a new person in the people structure
    based on the passed in person data
    :param person:  person to create in people structure
    :return:        201 on success, 406 on person exists
    """
    fname = person.get("fname")
    lname = person.get("lname")

    existing_person = (Person.query.filter(Person.fname == fname).filter(
        Person.lname == lname).one_or_none())

    # Can we insert this person?
    if existing_person is None:

        # Create a person instance using the schema and the passed in person
        schema = PersonSchema()
        new_person = schema.load(person, session=db.session).data

        # Add the person to the database
        db.session.add(new_person)
        db.session.commit()

        # Serialize and return the newly created person in the response
        data = schema.dump(new_person).data

        return data, 201

    # Otherwise, nope, person exists already
    else:
        abort(409, f"Person {fname} {lname} exists already")
Пример #4
0
def read_one(person_id):
    """
    This function responds to a request for /api/people/{lname}
    with one matching person from people
    :param lname:   last name of person to find
    :return:        person matching last name
    """
    """
    This function responds to a request for /api/people/{person_id}
    with one matching person from people

    :param person_id:   ID of person to find
    :return:            person matching ID
    """
    # Get the person requested
    person = Person.query \
        .filter(Person.person_id == person_id) \
        .one_or_none()

    # Did we find a person?
    if person is not None:

        # Serialize the data for the response
        person_schema = PersonSchema()
        return person_schema.dump(person)

    # Otherwise, nope, didn't find that person
    else:
        abort(
            404,
            'Person not found for Id: {person_id}'.format(person_id=person_id))
Пример #5
0
def update(person_id, person):
    # fname = person.get("fname", None)

    # if lname in PEOPLE and lname is not None:
    #     PEOPLE[lname]["fname"] = person.get("fname", None)
    #     PEOPLE[lname]["timestamp"] = get_timestamp()
    #     return make_response(
    #         "Successfully updated person {lname}".format(lname=lname)
    #     )
    # else:
    #     abort(
    #         404, "Person with {lname} does not exist".format(lname=lname)
    #     )

    fname = person.get("fname", None)
    lname = person.get("lname", None)
    # updated_person = Person.query.filter(Person.person_id == person_id).update(
    #     {Person.fname: fname, Person.lname: lname}
    # )

    schema = PersonSchema()
    update = schema.load(person)
    update.person_id = person_id

    db.session.merge(update)
    db.session.commit()

    return schema.dump(update)
Пример #6
0
def route_two_people():
    try:
        schema = PersonSchema()
        person1 = request.args.get("person1")
        validated_person1 = schema.load(person1)
        person2 = request.args.get("person2")
        person1_details = MONGO.db.people.find_one({"name": validated_person1})
        validated_person2 = schema.load(person2)
        person2_details = MONGO.db.people.find_one({"name": validated_person2})
        person1_response = {
            "username": person1_details["name"],
            "age": person1_details["age"],
            "address": person1_details["address"],
            "phone": person1_details["phone"],
        }
        person2_response = {
            "username": person2_details["name"],
            "age": person2_details["age"],
            "address": person2_details["address"],
            "phone": person2_details["phone"],
        }
        common_friends = find_common_friends(person1_details, person2_details)
        response = {
            "person1": person1_response,
            "person2": person2_response,
            "common_friends": common_friends,
        }
        return jsonify(response)
    except:
        error_response = {
            "status": "Error",
            "message": "An error ocurred while processing this request",
        }
        return jsonify(error_response["message"])
Пример #7
0
def create(person):
    
    fname = person.get("fname")
    lname = person.get("lname")

    existing_person = (
        Person.query.filter(Person.fname == fname)
        .filter(Person.lname == lname)
        .one_or_none()
    )

    if existing_person is None:

        # Create a person instance using the schema and the passed in person
        schema = PersonSchema()
        new_person = schema.load(person, session=db.session)

        # Add the person to the database
        db.session.add(new_person)
        db.session.commit()

        # Serialize and return the newly created person in the response
        data = schema.dump(new_person)

        return data, 201

    # Otherwise, person exists already
    else:
        abort(
            409,
            "Person {fname} {lname} exists already".format(
                fname=fname, lname=lname
            ),
        )
Пример #8
0
def update(person_id, person):
    """
    This function updates an existing person in the persons database
    :param person_id:   ID of person to update in the persons database
    :param person:  person data to update
    :return:        updated person structure
    """
    # Get the person from the db
    update_person = Person.query.filter(
        Person.id == person_id
    ).one_or_none()

    # Abort if we can't find the person
    if update_person is None:
        abort(
            404,
            f"Person not found for Id: {person_id}",
        )

    # turn the passed in person into a db object
    person_schema = PersonSchema()
    updater = person_schema.load(person, session=db.session)

    # Set the id to the person we want to update
    updater.id = update_person.id

    # merge the new object into the old and commit it to the db
    db.session.merge(updater)
    db.session.commit()

    # return updated person in the response
    data = person_schema.dump(update_person)

    return data, 200
Пример #9
0
def create(person):
    """
    This function creates a new person in the persons database
    based on the passed in person data
    :param person:  person to create in persons structure
    :return:        201 on success, 409 on person already exists
    """
    first_name = person.get('first_name')
    last_name = person.get('last_name')
    email = person.get('email')
    age = person.get('age')

    try:
        # Check if person exists already
        existing_person = Person.query \
            .filter(Person.first_name == first_name) \
            .filter(Person.last_name == last_name) \
            .filter(Person.email == email) \
            .filter(Person.age == age) \
            .one_or_none()

        if existing_person is None:
            person_schema = PersonSchema()
            new_person = person_schema.load(person, session=db.session)
            db.session.add(new_person)
            db.session.commit()

            data = person_schema.dump(new_person)
            return data, 201

        abort(409, f"Person with name {first_name} {last_name} already exists")
    except sqlalchemy.exc.SQLAlchemyError as e:
        logging.error(f'SQLAlchemyError: {e}')
Пример #10
0
    def put(self, person_id):
        """
        Defines a unique URL to update an existing order

        :param person_id:
        :return: person object
        """
        json_data = request.get_json()
        if not json_data:
            api.abort(404, 'No input data provided')

        schema = PersonSchema()

        try:
            new_person = schema.load(json_data, session=db.session)
        except ValidationError as err:
            api.abort(400, str(err))
            raise

        existing_person = Person.query \
            .filter(Person.person_id == person_id) \
            .one_or_none()

        if not existing_person:
            self.id_not_found(person_id)

        new_person.person_id = existing_person.person_id

        db.session.merge(new_person)
        db.session.commit()

        return schema.dump(existing_person), 201
Пример #11
0
    def post(self):
        json_data = request.get_json()
        if not json_data:
            api.abort(404, 'No input data provided')

        schema = PersonSchema()

        try:
            new_person = schema.load(json_data, session=db.session)
        except ValidationError as err:
            api.abort(400, str(err))
            raise

        first_name, last_name = new_person.fname, new_person.lname

        existing_person = Person.query \
            .filter(Person.fname == first_name) \
            .filter(Person.lname == last_name) \
            .one_or_none()

        if existing_person:
            api.abort(
                409, 'Person {} {} already exists in the database'.format(
                    first_name, last_name))

        db.session.add(new_person)
        db.session.commit()

        return schema.dump(new_person), 201
Пример #12
0
def create(person):
    """
    This function creates a new person in the users structure
    based on the passed in person data
    :param person:  person to create in users structure
    :return:        201 on success, 406 on person exists
    """
    lname = person.get("lname", None)
    fname = person.get("fname", None)
    age = person.get("age", None)
    job = person.get("job", None)

    existing_person = Person.query.filter(Person.fname == fname,
                                          Person.lname == lname,
                                          Person.age == age,
                                          Person.job == job).one_or_none()

    if not existing_person:
        schema = PersonSchema()
        new_person = schema.load(person, session=db.session).data

        db.session.add(new_person)
        db.session.commit()

        return schema.dump(new_person).data, 201

    else:
        abort(
            406, "Person {lname} {fname} exists already".format(lname=lname,
                                                                fname=fname))
Пример #13
0
def read_all():
    # return a list of Person Python objects as the variable people.
    people = Person.query.order_by(Person.lname).all()
    # if exists many Python objects that need to be serialized at the same time, you need set "many=True"
    person_schema = PersonSchema(many=True)
    # Serialize an object to native Python data types according to this Schema's fields.
    return person_schema.dump(people).data
Пример #14
0
def read_one(person_id):
    """
    This function responds to a request for /api/people/{person_id}
    with one matching person from people.

    This is where the outer join comes in handy. It’s a kind of boolean or operation.
    It returns person data even if there is no associated note data to combine with.
    This is the behavior you want for read_one(person_id) to handle the case of a newly
    created Person object that has no notes yet.

    :param person_id:   Id of person to find
    :return:            person matching id
    """
    # Build the initial query
    person = (
        Person.query.filter(Person.person_id == person_id)
        .outerjoin(Note)  # 外连接
        .one_or_none()
    )

    # Did we find a person?
    if person is not None:

        # Serialize the data for the response
        person_schema = PersonSchema()
        data = person_schema.dump(person).data
        return data

    # Otherwise, nope, didn't find that person
    else:
        abort(404, f"Person not found for Id: {person_id}")
Пример #15
0
def create(person):
    """
    Function responding to requests for creating a new person

    :param person:  person to create in people's structure
    :return: 201 on success, 406 if person already exists
    """
    lname = person.get("lname", None)
    fname = person.get("fname", None)

    existing_person = (Person.query.filter(Person.fname == fname).filter(
        Person.lname == lname).one_or_none())

    if existing_person is None:
        # Create a person instance using schema and passed in person
        schema = PersonSchema()
        new_person = schema.load(person, session=db.session).data

        # Add person to the session and commit to database
        db.session.add(new_person)
        db.session.commit()

        # Serialize and return newly created person in response
        data = schema.dump(new_person).data

        return data, 201
    else:
        abort(
            409,
            "Person {fname} {lname} exists already".format(fname=fname,
                                                           lname=lname),
        )
Пример #16
0
def update(person_id, person):
    """
    Updates person with person_id with passed in person 
    """
    # Get the person requested for update from the db into session
    update_person = Person.query.filter(
        Person.person_id == person_id).one_or_none()

    # Exit if person to update is not present in db
    if update_person is None:
        abort(404, f"Person with id: {person_id} not found")

    # Try to find after updating existing record, would we get a person that
    # already exists in the db
    fname = person.get("fname")
    lname = person.get("lname")

    existing_person = (Person.query.filter(Person.fname == fname).filter(
        Person.lname == lname).one_or_none())

    if existing_person is not None and existing_person.person_id != person_id:
        abort(409, f"Person with {fname} {lname} already exists")

    # Go ahead and update person
    # Turn passed-in person into a db object
    schema = PersonSchema()
    update = schema.load(person, session=db.session)

    update.person_id = update_person.person_id
    # Use .merge() to update record
    db.session.merge(update)
    db.session.commit()

    data = schema.dump(update_person)
    return data, 200
Пример #17
0
def update(person_id, person):
    """
    Function for updating existing person in people's structure

    :param person_id: Id of the person to update in people structure
    :param person: person to update
    :return: updated person structure
    """
    update_person = Person.query.filter(
        Person.person_id == person_id).one_or_none()

    # If person exists
    if update_person is not None:
        # create person from data passed
        schema = PersonSchema()
        update = schema.load(person, session=db.session).data

        # Set the id to the new person
        update.id = update_person.person_id

        # merge the new object in old and commit it to db
        db.session.merge(update)
        db.session.commit()

        # return updated person
        data = schema.dump(update_person).data

        return data, 200

    # Person does not exist
    else:
        abort(
            404,
            "Person not found for Id: {person_id}".format(person_id=person_id),
        )
Пример #18
0
def create(person):
    """
    This function creates a new person in the people structure
    based on the passed in person data

    :param person:  person to create in people structure
    :return:        201 on success, 406 on person exists
    """
    lname = person.get('lname')
    fname = person.get('fname')

    existing_person = Person.query \
        .filter(Person.fname == fname) \
        .filter(Person.lname == lname) \
        .one_or_none()

    if existing_person is None:

        schema = PersonSchema()
        new_person = schema.load(person, session=db.session).data

        db.session.add(new_person)
        db.session.commit()

        return schema.dump(new_person).data, 201

    else:
        abort(409, f'Person {fname} {lname} exists already')
Пример #19
0
def route_person(person_name):
    """ Return details of a single person """
    try:
        schema = PersonSchema()
        validated_person_name = schema.load(person_name)
        user_detail = {}
        person_details = MONGO.db.people.find_one(
            {"name": validated_person_name})
        user_detail.update({"username": person_details["name"]})
        user_detail.update({"age": person_details["age"]})
        favFood = person_details["favouriteFood"]
        favFruit = []
        favVeggie = []
        for each_fooditem in favFood:
            if each_fooditem in fruits:
                favFruit.append(each_fooditem)
            elif each_fooditem in vegetables:
                favVeggie.append(each_fooditem)
        user_detail.update({"fruits": favFruit})
        user_detail.update({"vegetables": favVeggie})
        return jsonify(user_detail)
    except:
        error_response = {
            "status": "Error",
            "message": "An error ocurred while processing this request",
        }
        return jsonify(error_response["message"])
Пример #20
0
def update(person_id, person):
    """
    This function updates an existing person in the people structure

    :param person_id:   Id of the person to update in the people structure
    :param person:  person to update
    :return:        updated person structure
    """
    update_person = Person.query \
        .filter(Person.person_id == person_id) \
        .one_or_none()

    if update_person is not None:

        schema = PersonSchema()
        update = schema.load(person, session=db.session).data

        update.id = update_person.id

        db.session.merge(update)
        db.session.commit()

        data = schema.dump(update_person).data

        return data, 200

    else:
        abort(
            404,
            'Person not found for Id: {person_id}'.format(person_id=person_id))
Пример #21
0
def create(person):
    """
    This function creates a new person in the people structure
    based on the passed in person data
    :param person:  person to create in people structure
    :return:        201 on success, 406 on person exists
    """
    lname = person.get("lname", None)
    fname = person.get("fname", None)

    # Does the person already exist?
    existing_person = (
        Person.query.filter(Person.fname == fname)
        .filter(Person.lname == lname)
        .one_or_none()
    )

    # Can we insert this person
    if existing_person is None:

        # Create a person instance using the schema and the passed in person
        schema = PersonSchema()
        new_person = schema.load(person, session=db.session)

        # Add the person to the database
        db.session.add(new_person)
        db.session.commit()

        # Serialize and return the newly created person in the response
        return schema.dump(new_person), 201
Пример #22
0
def read_one(person_id):
    """
    This function responds to a request for /api/people/{person_id}
    with one matching person from people

    :param person_id:   ID of person to find
    :return:            person matching ID
    """
    # Get the person requested
    person = Person.query.filter(
        Person.person_id == person_id).outerjoin(Note).one_or_none()

    if person is not None:

        # Serialize the data for the response
        person_schema = PersonSchema()
        data = person_schema.dump(person)
        return data

    # otherwise, nope, not found
    else:
        abort(
            404,
            "Person not found for Id: {person_id}".format(person_id=person_id))

    return person
Пример #23
0
def read_all():
    """
    This function responds to a request for /api/people
    with the complete lists of people

    :return:        sorted list of people
    """
    # Create the list of people from our data
    # return [PEOPLE[key] for key in sorted(PEOPLE.keys())]

    # conn = sqlite3.connect('people.db')
    # cur = conn.cursor()
    # cur.execute('select * from person')
    # peoples = cur.fetchall()
    # print(peoples)
    # Create the list of people from our data
    people = Person.query.order_by(Person.lname).all()

    if people is not None:
        # Serialize the data for the response
        person_schema = PersonSchema(many=True)
        return person_schema.dump(people)

    else:
        abort(404, 'No People found')
Пример #24
0
def create(person):
    """
    This function creates a new person in the people structure
    based on the passed-in person data

    :param person:  person to create in people structure
    :return:        201 on success, 406 on person exists
    """
    lname = person.get("lname")
    fname = person.get("fname")

    # Does the person exist already?
    existing_person = Person.query.filter(Person.fname == fname).filter(
        Person.lname == lname).one_or_none()

    if existing_person is None:

        # Create a person instance using the schema and the passed in person
        schema = PersonSchema()
        new_person = schema.load(person, session=db.session)

        # Add the person to the database
        db.session.add(new_person)
        db.session.commit()

        # Serialize and return the newly created person in the response
        data = schema.dump(new_person)

        return data, 201

    else:
        abort(
            409, 'Person {fname} {lname} exists already'.format(fname=fname,
                                                                lname=lname))
Пример #25
0
def update(person_id, person):
    """
    This function updates an existing person in the people structure
    Throws an error if a person with the name we want to update to
    already exists in the database.
    :param person_id:   Id of the person to update in the people structure
    :param person:      person to update
    :return:            updated person structure
    """
    # Get the person requested from the db into session
    update_person = Person.query.filter(
        Person.person_id == person_id
    ).one_or_none()

    # Try to find an existing person with the same name as the update
    fname = person.get("fname")
    lname = person.get("lname")

    existing_person = (
        Person.query.filter(Person.fname == fname)
            .filter(Person.lname == lname)
            .one_or_none()
    )

    # Are we trying to find a person that does not exist?
    if update_person is None:
        abort(
            404,
            "Person not found for Id: {person_id}".format(person_id=person_id),
        )

    # Would our update create a duplicate of another person already existing?
    elif (
            existing_person is not None and existing_person.person_id != person_id
    ):
        abort(
            409,
            "Person {fname} {lname} exists already".format(
                fname=fname, lname=lname
            ),
        )

    # Otherwise go ahead and update!
    else:

        # turn the passed in person into a db object
        schema = PersonSchema()
        update = schema.load(person, session=db.session)

        # Set the id to the person we want to update
        update.person_id = update_person.person_id

        # merge the new object into the old and commit it to the db
        db.session.merge(update)
        db.session.commit()

        # return updated person in the response
        data = schema.dump(update_person)

        return data, 200
Пример #26
0
def read_one(office):
    """
    This function responds to a request for /api/people/{office}
    with one matching person from people

    :param office:   office of person to find
    :return:            person matching id
    """
    # Get the person requested
    person = Person.query.filter(
        Person.office == office).all()  #################################

    # Did we find a person?
    if person is not None:

        # Serialize the data for the response
        person_schema = PersonSchema()
        data = person_schema.dump(person).data
        return data

    # Otherwise, nope, didn't find that person
    else:
        abort(
            404,
            "Person not found for Id: {office}".format(office=office),
        )
Пример #27
0
def read_one(person_id):
    """
    This function responds to a request for /api/people/{person_id}
    with one matching person from people

    :param person_id:   Id of person to find
    :return:            person matching id
    """
    # Build the initial query
    person = (
        Person.query.filter(Person.person_id == person_id)
        .outerjoin(Note)
        .one_or_none()
    )

    # Did we find a person?
    if person is not None:

        # Serialize the data for the response
        person_schema = PersonSchema()
        data = person_schema.dump(person).data
        return data

    # Otherwise, nope, didn't find that person
    else:
        abort(404, f"Person not found for Id: {person_id}")
Пример #28
0
def update(person_id, person):
    """
    This function updates an existing person in the people structure

    :param person_id:   Id of the person to update in the people structure
    :param person:      person to update
    :return:            updated person structure
    """
    # Get the person requested from the db into session
    update_person = Person.query.filter(Person.person_id == person_id).one_or_none()
    # Did we find an existing person?
    if update_person is not None:
        update_person.lname = person.get("lname")
        update_person.fname = person.get("fname")
        # commit it to the db
        db.session.commit()

        # return updated person in the response
        schema = PersonSchema()
        data = schema.dump(update_person)

        return data, 200

    # Otherwise, nope, didn't find that person
    else:
        abort(404, f"Person not found for Id: {person_id}")
Пример #29
0
def update(person_id, person):
    """
    This function updates an existing person in the people structure
    :param person_id:   Id of the person to update in the people structure
    :param person:      person to update
    :return:            updated person structure
    """
    # Get the person requested from the db into session
    update_person = Person.query.filter(
        Person.person_id == person_id).one_or_none()

    # Did we find an existing person?
    if update_person is not None:

        # turn the passed in person into a db object
        schema = PersonSchema()
        update = schema.load(person, session=db.session).data

        # Set the id to the person we want to update
        update.person_id = update_person.person_id

        # merge the new object into the old and commit it to the db
        db.session.merge(update)
        db.session.commit()

        # return updated person in the response
        data = schema.dump(update_person).data

        return data, 200

    # Otherwise, nope, didn't find that person
    else:
        abort(404, f"Person not found for Id: {person_id}")
Пример #30
0
def create(person):
    """
    This function creates a new person in the people list based on the passed in person data

    :param person:  person to create in the people list
    :return:    201 on success, 406 on person exist
    """
    lname = person.get("lname", None)
    fname = person.get("fname", None)

    # Existing person
    existing_person = Person.query.filter(Person.fname==fname).filter(Person.lname==lname).one_or_none()

    # does the person exist already
    if existing_person is None:

        # Create the person instance using the schema and the person data that is passed in
        person_schema = PersonSchema()
        new_person = person_schema.load(person, session=db.session)

        # Add the person to the database
        db.session.add(new_person)
        db.session.commit()

        # Serialize and return the newly created person as response
        data = person_schema.dump(new_person)
        return data, 201
    else:
        abort(
            406, f"Person {fname} {lname} already exists"
        )