Beispiel #1
0
def post_pet(user_id):
    """
    Creates a new Pet
    """
    user = storage.get(User, user_id)

    if not user:
        abort(404)

    if not request.get_json():
        abort(400, description="Not a JSON")

    if 'name' not in request.get_json():
        abort(400, description="Missing name")

    data = request.get_json()
    data["user_id"] = user_id

    pet = Pet(**data)
    pet.save()

    # creating the instance Picture for this pet
    picture = Picture(pet_id=pet.id)
    picture.save()

    return make_response(jsonify(pet.to_dict()), 201)
class PetTest(unittest.TestCase):
    def setUp(self):
        owner = Owner('Jack',
                      'White',
                      '*****@*****.**',
                      '487239847',
                      True,
                      id=4)
        vet = Vet('White', 'Jack', 3)
        self.pet = Pet('Smokey', dt.date(2020, 7, 24), '', 'cat', owner, vet,
                       'randomString', 'dkfjd', 3)

    def test_name(self):
        self.assertEqual('Smokey', self.pet.name)

    def test_dob(self):
        self.assertEqual(dt.date(2020, 7, 24), self.pet.dob)

    def test_yo(self):
        self.pet.dob_to_yo(self.pet.dob)
        self.assertEqual(0.04, self.pet.yo)

    def test_type(self):
        self.assertEqual('cat', self.pet.type)

    def test_owner(self):
        self.assertEqual(4, self.pet.owner.id)

    def test_vet(self):
        self.assertEqual(3, self.pet.vet.id)

    def test_image(self):
        self.assertEqual('randomString', self.pet.image64)
 def setUp(self):
     owner = Owner('Jack',
                   'White',
                   '*****@*****.**',
                   '487239847',
                   True,
                   id=4)
     vet = Vet('White', 'Jack', 3)
     self.pet = Pet('Smokey', dt.date(2020, 7, 24), '', 'cat', owner, vet,
                    'randomString', 'dkfjd', 3)
    def select_all(self):
        pets = []
        sql = f"SELECT * FROM {self.table}"
        results = run_sql(sql)

        for row in results:
            owner = OwnerRep().select(row['owner_id'])
            vet = VetRep().select(row['vet_id'])
            pet = Pet(row["pet_name"], row["dob"], row["yo"],
                      row['animal_type'], owner, vet, row['img'],
                      row['img_type'], row['id'])
            pet.update_age()
            pets.append(pet)
        return pets
    def select(self, id):
        pet = None
        sql = f"SELECT * FROM {self.table} " + "WHERE id = %s"
        values = [id]
        result = run_sql(sql, values)[0]

        if result is not None:
            owner = OwnerRep().select(result['owner_id'])
            vet = VetRep().select(result['vet_id'])
            pet = Pet(result["pet_name"], result["dob"], result["yo"],
                      result['animal_type'], owner, vet, result['img'],
                      result['img_type'], result['id'])
            pet.update_age()
        return pet
Beispiel #6
0
    def get_pets(self, owner_id):
        pets = []
        sql = "SELECT * FROM pets WHERE owner_id = %s"
        values = [owner_id]
        results = run_sql(sql, values)

        for row in results:
            owner = self.select(row['owner_id'])
            vet = self._select_vet(row['vet_id'])
            pet = Pet(row['pet_name'], row['dob'], row['yo'],
                      row['animal_type'], owner, vet, row['img'],
                      row['img_type'], row['id'])
            pet.update_age()
            pets.append(pet)
        return pets
    def test_put_create_a_pet(self):
        category = Category(2, "Dogs")
        tag = Tag(5, "Red")
        pet = Pet(888888, "avaliable", "Rose", category.__dict__, ["string"],
                  [tag.__dict__])
        body = json.dumps(pet.__dict__)  # .replace('"', '\"')
        headers = {'Content-Type': 'application/json'}

        response = requests.put(self.base_url + "/pet",
                                headers=headers,
                                data=body)

        assert response.status_code == 200
        json_response = json.loads(response.text)
        pet_name = json_response["name"]
        pet_id = json_response["id"]

        assert pet_name == "Rose"
        assert pet_id == 888888

        response = requests.request("GET", self.get_url(888888))
        assert response.status_code == 200

        json_response = json.loads(response.text)

        pet_name = json_response["name"]
        pet_id = json_response["id"]

        assert pet_name == "Rose"
        assert pet_id == 888888
Beispiel #8
0
def delete_pet(id):

    pet = Pet.find(id)
    if pet is None:
        return jsonify({'message': 'pet doesn\'t exist'}), 404

    if pet.delete():
        return jsonify({'message': 'pet has been successfully deleted'}), 200
    return jsonify({'message': 'oops! something went wrong'}), 500
def pets(owner):
    pets = []

    sql = "SELECT * FROM pets WHERE owner_id = %s"
    values = [owner_id]
    results = run_sql(sql, values)

    for row in results:
        pet = Pet(row['name'], row['owner_id'], row['species'], row['age'])
        pets.append(pet)
    return pets
 def setUp(self):
     owner = Owner('Jack',
                   'White',
                   '*****@*****.**',
                   '487239847',
                   True,
                   id=3)
     vet = Vet('White', 'Jack', 3)
     pet = Pet('dummy pet', dt.date(2020, 2, 2), '1', 'dog', owner, vet,
               'dkfj', 'what', 2)
     treatment = Treatment('kadjf', 'a description', 1)
     self.pet_treatment = PetTreatment(pet, treatment, 3)
Beispiel #11
0
def update_pet(id):
    pet_name = request.form['Pet name']
    date_of_birth = request.form['Date of birth']
    pet_type = request.form['Pet type']
    owner_name = request.form['Owner name']
    treatment_notes = request.form['Treatment']
    vet = vet_repository.select(request.form['vet_id'])
    pet = Pet(pet_name, date_of_birth, pet_type, owner_name, treatment_notes,
              vet, id)
    print(pet.vet.vet_name)
    pet_repository.update(pet)
    return redirect('/pets')
Beispiel #12
0
def select(id):
    pet = None
    sql = "SELECT * FROM pets WHERE id = %s"
    values = [id]
    result = run_sql(sql, values)[0]

    if result is not None:
        vet = vet_repository.select(result['vet_id'])
        pet = Pet(result['pet_name'], result['date_of_birth'],
                  result['pet_type'], result['owner_name'],
                  result['treatment_notes'], vet, result['id'])
    return pet
Beispiel #13
0
def select_all():
    pets = []

    sql = "SELECT * FROM pets"
    results = run_sql(sql)

    for row in results:
        vet = vet_repository.select(row['vet_id'])
        pet = Pet(row['pet_name'], row['date_of_birth'], row['pet_type'],
                  row['owner_name'], row['treatment_notes'], vet, row['id'])
        pets.append(pet)
    return pets
def add_pet(body):
    """
    Add a new pet to the store
    
    :param body: Pet object that needs to be added to the store
    :type body: dict | bytes

    :rtype: None
    """
    if connexion.request.is_json:
        body = Pet.from_dict(connexion.request.get_json())
    return 'do some magic!'
Beispiel #15
0
def add_pet(body):
    """
    Add a new pet to the store
    
    :param body: Pet object that needs to be added to the store
    :type body: dict | bytes

    :rtype: None
    """
    if connexion.request.is_json:
        body = Pet.from_dict(connexion.request.get_json())
    return 'do some magic!'
Beispiel #16
0
    def test_update_pet(self):
        """
        Test case for update_pet

        Update an existing pet
        """
        body = Pet()
        response = self.client.open('/v2/pet',
                                    method='PUT',
                                    data=json.dumps(body),
                                    content_type='application/json')
        self.assert200(response,
                       "Response body is : " + response.data.decode('utf-8'))
Beispiel #17
0
    def test_add_pet(self):
        """
        Test case for add_pet

        Add a new pet to the store
        """
        body = Pet()
        response = self.client.open('/v2/pet',
                                    method='POST',
                                    data=json.dumps(body),
                                    content_type='application/json')
        self.assert200(response,
                       "Response body is : " + response.data.decode('utf-8'))
def pets(vet):
    pets = []

    sql = "SELECT * FROM pets WHERE vet_id = %s"
    values = [vet.id]
    results = run_sql(sql, values)

    for row in results:
        pet = Pet(row['pet_name'], row['date_of_birth'], row['pet_type'],
                  row['owner_name'], row['treatment_notes'], row['vet_id'],
                  row['id'])
        pets.append(pet)
    return pets
Beispiel #19
0
def store_pet():
    #check = reqparse.RequestParser()	#checks are missing
    data = request.get_json()
    pet = Pet()

    exists = Pet.where('name', '=', data['name'])
    if exists.__getattr__ is None:
        return jsonify({'message': 'pet is already stored'}), 404

    pet.name = data['name']
    pet.type = data['type']
    pet.age = data['age']
    pet.specie = data['specie']
    if pet.save():
        return jsonify(data)
    return jsonify({'message': 'oops! something went wrong'}), 500
Beispiel #20
0
def select(pet_id):
    # Create the SQL query, pass in the data and run it
    sql = "SELECT * FROM pet WHERE id = %s"
    values = [pet_id]
    result = run_sql(sql, values)

    # Create object if data is found in the database
    if len(result) > 0:
        pet_type = PTR.select(result[0]['type_id'])
        owner = OR.select(result[0]['owner_id'])
        vet = VR.select(result[0]['vet_id'])
        new_pet = Pet(result[0]['name'], result[0]['dob'], owner, pet_type, vet, result[0]['id'])
    
    return new_pet
Beispiel #21
0
def update_pet(id):
    #check = reqparse.RequestParser()	#checks are missing
    data = request.get_json()
    pet = Pet.find(id)

    if pet is None:
        return jsonify({'message': 'pet doesn\'t exist'}), 404

    pet.name = data['name']
    pet.type = data['type']
    pet.age = data['age']
    pet.specie = data['specie']
    if pet.update():
        return jsonify({'message': 'pet has been successfully updated'}), 200
    return jsonify({'message': 'oops! something went wrong'}), 500
Beispiel #22
0
    def get_pets(self, treatment_id):
        pets = []
        sql = """
        SELECT pets.* FROM pets
        INNER JOIN pets_treatments ON pet.id = pets_treatments.pet_id 
        INNER JOIN treatments ON pets_treatments.treatment_id = treatment.id
        WHERE treatments.id = %s 
        """
        values = [treatment_id]
        results = run_sql(sql, values)

        for row in results:
            pet = Pet(row['name'], row['dob'], row['yo'], row['type'],
                      row['owner_id'], row['vet_id'], row['image'], row['id'])
            pets.append(pet)
        return pets
Beispiel #23
0
def update(id):
    # Get the data from the form
    name = request.form['pet_name']
    dob = request.form['pet_age']
    type_id = request.form['pet_type']
    owner_id = request.form['pet_owner']
    vet_id = request.form['pet_vet']

    # Find the correct data for the Pet object
    pet_type = PTR.select(type_id)
    owner = OR.select(owner_id)
    vet = VR.select(vet_id)

    # Create new Pet object to be saved to db
    pet = Pet(name, dob, owner, pet_type, vet, id)
    PR.update(pet)

    return redirect('/pets/' + id)
Beispiel #24
0
def edit_pets_POST(owner_id, pet_id):
    
    # getting form data
    name = request.form.get('name')
    dob_string = request.form.get('dob')
    yo_string = request.form.get('yo')
    type_s = request.form.get('type')
    vet_id = request.form.get('vet')
    image = request.files['image']

    vet = VetRep().select(vet_id)
    owner = OwnerRep().select(owner_id)
    # date time logic
    if dob_string != '':
        dob = string_to_date(dob_string)
    else: 
        dob = False
    try:
        yo = float(yo_string.replace(',', '.'))
    except ValueError:
        yo = False
        
        

    # image logic
    new_image_string = False
    new_image_type = image.content_type
    if image.filename != '': # image was given
        new_image_string = base64.b64encode(image.read()).decode('utf-8')
        # write_to_file(new_image_string, new_image_type) 

    # if pet already has an image and an image was not given
    pet = PetRep().select(pet_id)
    if pet.image64 != '' and image.filename == '':
        new_image_string = pet.image64
        new_image_type = pet.image_type

    # if a new date was given in the form of yo and this is not a dash
    if yo and float(pet.yo) != float(yo):
        dob = False
    pet = Pet(name, dob, yo, type_s, owner, vet, new_image_string, new_image_type, pet_id)
    PetRep().update(pet)

    return redirect('/owners/'+owner_id+'/pets')
Beispiel #25
0
def select_all():
    # Create list of pet objects and set == empty list
    pets = []

    # Create the SQL query && input data before running it
    sql = "SELECT * FROM pet"
    results = run_sql(sql)

    # Loop through all the results and append the objects to a list
    for row in results:
        # Get the objects to create the pet object
        pet_type = PTR.select(row['type_id'])
        owner = OR.select(row['owner_id'])
        vet = VR.select(row['vet_id'])

        # Create new pet object && append to pets list
        new_pet = Pet(row['name'], row['dob'], owner, pet_type, vet, row['id'])
        pets.append(new_pet)

    return pets
Beispiel #26
0
def select_by_owner(owner_id):
    # Create list of pets == empty list
    pets = []

    # Create SQL query, input data && run
    sql = "SELECT * FROM pet WHERE owner_id = %s"
    values = [owner_id]
    results = run_sql(sql, values)

    # Loop through the results
    for row in results:
        # Get the objects to create the pet object
        pet_type = PTR.select(row['type_id'])
        owner = OR.select(row['owner_id'])
        vet = VR.select(row['vet_id'])

        # Create new pet object && append to pets list
        new_pet = Pet(row['name'], row['dob'], owner, pet_type, vet, row['id'])
        pets.append(new_pet)

    return pets
Beispiel #27
0
def test_add_pet_positive(input, output):
    new_pet = Pet().create(**input)
    with allure.step('check valid input data'):
        assert new_pet.status_code == output
    if 'id' in input:
        with allure.step(
                'check if object with specified id was created with find_by_id method'
        ):
            assert Pet().find_by_id(str(
                input['id'])).json()['id'] == input['id']
    if 'status' in input:
        with allure.step(
                'check if object with specified status was created with find_by_status method'
        ):
            assert new_pet.json() in Pet().find_by_status(
                new_pet.json()['status']).json()
Beispiel #28
0
def create_pet_POST(owner_id):
    
    # getting form data
    name = request.form.get('name')
    dob_string = request.form.get('dob')
    yo_string = request.form.get('yo')
    type_s = request.form.get('type')
    vet_id = request.form.get('vet')
    image = request.files['image']
    
    vet = VetRep().select(vet_id)
    owner = OwnerRep().select(owner_id)    
    
    # date time logic
    if dob_string != '':
        dob = string_to_date(dob_string)
        yo = False
    else: 
        dob = False
        try:
            yo = float(yo_string.replace(',', '.'))
        except ValueError:
            yo = False
            
    # image logic
    new_image_string = False
    new_image_type = image.content_type
    if image.filename != '': # image was given
        new_image_string = base64.b64encode(image.read()).decode('utf-8')
        # write_to_file(new_image_string, new_image_type) 

    pet = Pet(name, dob, yo, type_s, owner, vet, new_image_string, new_image_type)
    PetRep().save(pet)

    # owner = OwnerRep().select(owner_id)
    # pets = OwnerRep().get_pets(owner_id)
    return redirect('/owners/'+owner_id+'/pets')
    def test_post_create_a_pet(self):
        # body = {
        #     "id": 77777,
        #     "category": {
        #         "id": 0,
        #         "name": "string"
        #     },
        #     "name": "doggie",
        #     "photoUrls": [
        #         "string"
        #     ],
        #     "tags": [
        #         {
        #             "id": 0,
        #             "name": "string"
        #         }
        #     ],
        #     "status": "available"
        # }
        category = Category(2, "Dogs")
        tag = Tag(5, "Red")
        pet = Pet(888888, "avaliable", "Dasye", category.__dict__, ["string"],
                  [tag.__dict__])
        body = json.dumps(pet.__dict__)  # .replace('"', '\"')
        headers = {'Content-Type': 'application/json'}

        response = requests.post(self.base_url + "/pet",
                                 headers=headers,
                                 data=body)

        assert response.status_code == 200
        json_response = json.loads(response.text)
        pet_name = json_response["name"]
        pet_id = json_response["id"]

        assert pet_name == "Dasye"
        assert pet_id == 888888
Beispiel #30
0
def save():
    # Get the data from the form
    name = request.form['pet_name']
    dob = request.form['pet_age']
    type_id = request.form['pet_type']
    owner_id = request.form['pet_owner']
    vet_id = request.form['pet_vet']

    if len(name) > 64:
        return_error('ap-1')  # Return error code 1: Name too long

    # Find the correct data for the Pet object
    pet_type = PTR.select(type_id)
    owner = OR.select(owner_id)
    vet = VR.select(vet_id)

    if (owner.registered == False):
        return_error(
            'ap-5')  # Return error code 5: Cannot add as owner not registered

    # Create new Pet object to be saved to db
    pet = Pet(name, dob, owner, pet_type, vet)
    PR.save(pet)
    return redirect('/pets')
vet3 = Vet('Melissa', 'Dudley')
melissa_obj = VetRep().save(vet3)

vet4 = Vet('John', 'Martin')
john_obj = VetRep().save(vet4)

vet5 = Vet('Elena', 'Gherri')
elena_obj = VetRep().save(vet5)

vet6 = Vet('Martin', 'Corley')
martin_obj = VetRep().save(vet6)
###########

# PETS
evi_pet1_img = read_file('pets_images_base64/pet-1.txt')
evi_pet1 = Pet('Dobby', dt.date(2020, 7, 23), False, 'Cat', evi_obj,
               melissa_obj, evi_pet1_img[0], evi_pet1_img[1])
pet_1 = PetRep().save(evi_pet1)

evi_pet2_img = read_file('pets_images_base64/pet-2.txt')
evi_pet2 = Pet('Smokey', dt.date(2020, 3, 23), False, 'Cat', evi_obj,
               melissa_obj, evi_pet2_img[0], evi_pet2_img[1])
pet_2 = PetRep().save(evi_pet2)

evi_pet3_img = read_file('pets_images_base64/pet-3.txt')
evi_pet3 = Pet('Jack', dt.date(2020, 2, 3), False, 'Cat', evi_obj, melissa_obj,
               evi_pet3_img[0], evi_pet3_img[1])
pet_3 = PetRep().save(evi_pet3)

mario_pet1_img = read_file('pets_images_base64/pet-4.txt')
mario_pet1 = Pet('Layla', dt.date(2018, 2, 3), False, 'Cat', marios_obj,
                 john_obj, mario_pet1_img[0], mario_pet1_img[1])