Exemplo n.º 1
0
def get_all_animals():
    with sqlite3.connect('./kennels.db') as conn:
        conn.row_factory = sqlite3.Row
        db_cursor = conn.cursor()

        db_cursor.execute("""
        SELECT
            a.id,
            a.name,
            a.breed,
            a.status,
            a.location_id,
            a.customer_id,
            l.name location_name,
            l.address location_address
        FROM Animal a
        JOIN Location l
            ON l.id = a.location_id
        """)

        animals = []

        dataset = db_cursor.fetchall()

        for row in dataset:
            animal = Animal(row['id'], row['name'], row['breed'],
                            row['status'], row['location_id'],
                            row['customer_id'])
            location = Location(id=row['location_id'],
                                address=row['location_address'],
                                name=row['location_name'])
            animal.location = location.__dict__
            animals.append(animal.__dict__)

    return json.dumps(animals)
Exemplo n.º 2
0
def save_animals():
    try:
        payload = request.get_json()
        animal_to_add = payload.get('animal')
        devices_to_add = payload.get('devices')
        attributes_to_add = payload.get('attributes')
    except Exception:
        return jsonify(error='Invalid JSON.')
    validation = animals_validate_required(animal_to_add)
    if validation['errors']:
        return jsonify(error={
            'name': 'invalid_model',
            'errors': validation['errors']
        }), 400
    animal = Animal(**animal_to_add)
    if devices_to_add:
        list_devices = []
        for item in devices_to_add:
            tmp = AnimalDevice(**item)
            list_devices.append(tmp)
        animal.animal_devices = list_devices
    if attributes_to_add:
        list_attributes = []
        for item in attributes_to_add:
            tmp = AnimalAttribute(**item)
            list_attributes.append(tmp)
        animal.animal_attributes = list_attributes
    try:
        db.session.add(animal)
        db.session.commit()
        return jsonify(animal.json())
    except (IntegrityError, Exception) as e:
        traceback.print_exc()
        db.session.rollback()
Exemplo n.º 3
0
    def post_animal(payload):

        try:
            data = request.get_json()

            name = data.get('name')
            gender = data.get('gender')
            age = data.get('age')
            species = data.get('species')
            breed = data.get('breed')
            shelter_id = data.get('shelter_id')

            if ((name == '') or (species == '') or (breed == '')):
                abort(422)

            animal = Animal(name=name,
                            gender=gender,
                            age=age,
                            species=species,
                            breed=breed,
                            shelter_id=shelter_id)
            animal.insert()
        except BaseException as e:
            print(e)
            abort(422)

        formatted_animals = [animal.format()]

        return jsonify({'success': True, 'animals': formatted_animals}), 200
Exemplo n.º 4
0
def get_all_animals():
    # Open a connection to the database
    with sqlite3.connect("./kennel.db") as conn:

        # Just use these. It's a Black Box.
        conn.row_factory = sqlite3.Row
        db_cursor = conn.cursor()

        # Write the SQL query to get the information you want
        db_cursor.execute("""
        SELECT
        a.id,
        a.name,
        a.breed,
        a.status,
        a.location_id,
        a.customer_id,
        l.name location_name,
        l.address location_address,
        c.name customer_name,
        c.address customer_address,
        c.email customer_email,
        c.password customer_password
        FROM Animal a
        JOIN Location l
        ON l.id = a.location_id
        JOIN Customer c
        ON c.id = a.customer_id
        """)

        # Initialize an empty list to hold all animal representations
        animals = []

        # Convert rows of data into a Python list
        dataset = db_cursor.fetchall()

        # Iterate list of data returned from database
        for row in dataset:

            # Create an animal instance from the current row
            animal = Animal(row['id'], row['name'], row['breed'],
                            row['status'], row['location_id'],
                            row['customer_id'])

            # Create a Location instance from the current row
            location = Location(row['location_id'], row['location_name'],
                                row['location_address'])
            customer = Customer(row['customer_id'], row['customer_name'],
                                row['customer_address'], row['customer_email'],
                                row['customer_password'])

            # Add the dictionary representation of the location to the animal
            animal.location = location.__dict__
            animal.customer = customer.__dict__

            # Add the dictionary representation of the animal to the list
            animals.append(animal.__dict__)

    # Use `json` package to properly serialize list as JSON
    return json.dumps(animals)
Exemplo n.º 5
0
def seed(db):
    zoos = [
        Zoo(id=1, name="Bronx Zoo",address="Bronx"),
        Zoo(id=2, name="Central Park Zoo", address="Manhattan")
    ]

    species = [
        Species(id=1, colloquial_name="cow", scientific_name="bos taurus", sound="moo"),
        Species(id=2, colloquial_name="pig", scientific_name="sus scrofa", sound="oink oink"),
        Species(id=3, colloquial_name="dog", scientific_name="canis familiaris", sound="bark")
    ]

    animals = [
        Animal(name="Bessie", birthday=datetime.date(2020, 1, 1), zoo_id=1, species_id=1),
        Animal(name="Betty", birthday=datetime.date(2020, 1, 1), zoo_id=1, species_id=1),
        Animal(name="Stanley", birthday=datetime.date(2020, 1, 1), zoo_id=2, species_id=1),
        Animal(name="Manly", birthday=datetime.date(2020, 1, 1), zoo_id=2, species_id=1),
        Animal(name="Wilbur", birthday=datetime.date(2020, 1, 1), zoo_id=1, species_id=2),
        Animal(name="Wendy", birthday=datetime.date(2020, 1, 1), zoo_id=1, species_id=2),
        Animal(name="Candy", birthday=datetime.date(2020, 1, 1), zoo_id=2, species_id=2),
        Animal(name="Dandy", birthday=datetime.date(2020, 1, 1), zoo_id=2, species_id=2),
        Animal(name="Shiloh", birthday=datetime.date(2020, 1, 1), zoo_id=1, species_id=3),
        Animal(name="Sheepdog", birthday=datetime.date(2020, 1, 1), zoo_id=2, species_id=3)
    ]

    db.session.add_all(zoos)
    db.session.add_all(species)
    db.session.add_all(animals)
    db.session.commit()
Exemplo n.º 6
0
 def post(self):
     name = self.request.get('animal')
     
     if name:
         animal = Animal(parent=PARENT, name=name)
         animal.put()
     
     self.redirect('/')
Exemplo n.º 7
0
 def post(self):
     name = self.request.get('animal')
     
     if name:
         animal = Animal(parent=PARENT, name=name)
         animal.put()
     
     self.redirect('/')
Exemplo n.º 8
0
def get_all_animals():
    # Open a connection to the database
    with sqlite3.connect("./kennel.db") as conn:

        # Just use these. It's a black box
        conn.row_factory = sqlite3.Row
        db_cursor = conn.cursor()

        # Write the SQL query to get the info you want
        db_cursor.execute("""
            SELECT
                a.id,
                a.name,
                a.breed,
                a.status,
                a.location_id,
                a.treatment,
                a.customer_id,
                l.name location_name,
                l.address location_address,
                c.name customer_name,
                c.address customer_address,
                c.email customer_email,
                c.password customer_password
            FROM animal a
            JOIN location l
                ON l.id = a.location_id
            JOIN customer c
                ON c.id = a.customer_id
        """)

        # Initialize an empty list to hold all animal representations 
        animals = []

        # Convert rows of data into a Python list
        dataset = db_cursor.fetchall()

        # Iterate list of data returned from database
        for row in dataset:

            # Create an animal instance from the current row.
            # Note that the database fields are specified in
            # the exact order of the parameters defined in the
            # Animal class above
            animal = Animal(row['id'], row['name'], row['breed'], row['status'], row['location_id'], row['treatment'], row['customer_id'])

            location = Locations(row['location_id'], row['location_name'], row['location_address'])

            customer = Customer(row['customer_id'], row['customer_name'], row['customer_address'], row['customer_email'], row['customer_password'])

            animal.location = location.__dict__

            animal.customer = customer.__dict__

            animals.append(animal.__dict__)

        # Use json package to properly serialize list as JSON
        return json.dumps(animals)
Exemplo n.º 9
0
def get_new_animals_from_breeding(count, month):
    for female in range(count):
        gender = get_new_animal_gender()

        born_animal = Animal()
        born_animal.birth_month = month
        born_animal.last_feed_month = month - 1
        born_animal.gender = gender

        yield born_animal
Exemplo n.º 10
0
def get_single_animal(id):
    with sqlite3.connect("../../kennel.db") as conn:
        conn.row_factory = sqlite3.Row
        db_cursor = conn.cursor()

        # Use a ? parameter to inject a variable's value
        # into the SQL statement.
        db_cursor.execute("""
        SELECT
            a.id,
            a.name,
            a.breed,
            a.status,
            a.location_id,
            a.customer_id,
            l.name location_name,
            l.address location_address,
            c.name customer_name,
            c.address customer_address,
            c.email customer_email
        FROM animal a
        JOIN location l
            ON l.id = a.location_id
        JOIN customer c
            ON c.id = a.customer_id
        WHERE a.id = ?
        """, (id, ))

        # Load the single result into memory
        data = db_cursor.fetchone()

        # Create an animal instance from the current row
        animal = Animal(data['id'], data['name'], data['breed'],
                        data['status'], data['location_id'],
                        data['customer_id'])

        location = Location(data['location_id'],
                            data['location_name'], data['location_address'])

        # remove the location id from the results
        del location.__dict__['id']

        animal.location = location.__dict__

        customer = Customer(data['customer_id'], data['customer_name'],
                            data['customer_address'], data['customer_email'])

        # remove the customer id and password field from the results
        del customer.__dict__['id']
        del customer.__dict__['password']

        animal.customer = customer.__dict__

        return json.dumps(animal.__dict__)
Exemplo n.º 11
0
def get_all_animals():
    if request.method == 'POST':
        name = request.form["name"]
        new_animal = Animal(name=name)
        db.session.add(new_animal)
        db.session.commit()
        return jsonify(new_animal.serialize())
    else:
        data = Animal.query.all()
        all_animals = [item.serialize() for item in data]
        return jsonify(all_animals)
Exemplo n.º 12
0
def get_single_animal(id):
    with sqlite3.connect("./kennel.db") as conn:
        conn.row_factory = sqlite3.Row
        db_cursor = conn.cursor()

        # Use a ? parameter to inject a variable's value
        # into the SQL statement.
        db_cursor.execute(
            """
        SELECT
            a.id,
            a.name,
            a.breed,
            a.status,
            a.location_id,
            a.customer_id,
            l.name location_name,
            l.address location_address,
            c.name customer_name,
            c.address customer_address,
            c.email customer_email,
            c.password customer_password
        FROM Animal a

        JOIN Location l
        ON l.id = a.location_id

        JOIN Customer c
        on c.id = a.customer_id
        WHERE a.id = ?
        """, (id, ))

        # Load the single result into memory
        data = db_cursor.fetchone()

        # Create an animal instance from the current row
        animal = Animal(data['id'], data['name'], data['breed'],
                        data['status'], data['location_id'],
                        data['customer_id'])

        location = Location(data['location_id'], data['location_name'],
                            data['location_address'])
        customer = Customer(data['customer_id'], data['customer_name'],
                            data['customer_address'], data['customer_email'],
                            data['customer_password'])

        # Add the dictionary representation of the location to the animal
        animal.location = location.__dict__
        animal.customer = customer.__dict__

        # Add the dictionary representation of the animal to the list
        # animals.append(animal.__dict__)

    return json.dumps(animal.__dict__)
Exemplo n.º 13
0
    def get(self):
        """ASWP-API Animals GET

        Returns:
            type[Response]: Flask JSON Response with list of Animals
        """
        animals = [Animal.to_dict(a) for a in Animal.get_all()]
        if animals:
            for animal in animals:
                if animal["price"] == None:
                    animal["price"] = Specie.get_price(animal["specie"])
        return jsonify(animals=animals)
Exemplo n.º 14
0
    def test_finish_breeding(self):
        simulation_step = SimulationStep()

        animal = Animal()
        animal.gender = GENDER_FEMALE
        animal.gestation_months = 1

        species = Species()
        species.gestation_months = 1

        new_animals = tuple(breed_animals([animal], species, simulation_step))
        self.assertEqual(0, animal.gestation_months)
        self.assertEqual(1, len(new_animals))
Exemplo n.º 15
0
    def test_get_animals(self):
        cat = Animal(center_id=1, name='cat', description='cat in the boots', age=33, species_id=1, price=100500)
        dog = Animal(center_id=2, name='dog', description='husky', age=3, species_id=2, price=300)
        db.session.add(cat)
        db.session.add(dog)
        db.session.commit()

        response = self.app.get('/animals')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.json, json.loads("{\"animals\": [{\"id\": 1, \"name\": \"cat\", "
                                                   "\"description\": \"cat in the boots\", \"age\": 33, "
                                                   "\"price\": 100500.0}, {\"id\": 2, \"name\": \"dog\", "
                                                   "\"description\": \"husky\", \"age\": 3, \"price\": 300.0}]}"))
Exemplo n.º 16
0
    def test_dumpdata_uses_default_manager(self):
        """
        Regression for #11286
        Ensure that dumpdata honors the default manager
        Dump the current contents of the database as a JSON fixture
        """
        management.call_command(
            'loaddata',
            'animal.xml',
            verbosity=0,
            commit=False,
        )
        management.call_command(
            'loaddata',
            'sequence.json',
            verbosity=0,
            commit=False,
        )
        animal = Animal(
            name='Platypus',
            latin_name='Ornithorhynchus anatinus',
            count=2,
            weight=2.2
        )
        animal.save()

        stdout = StringIO()
        management.call_command(
            'dumpdata',
            'fixtures_regress.animal',
            format='json',
            stdout=stdout
        )

        # Output order isn't guaranteed, so check for parts
        data = stdout.getvalue()

        # Get rid of artifacts like '000000002' to eliminate the differences
        # between different Python versions.
        data = re.sub('0{6,}\d', '', data)

        lion_json = '{"pk": 1, "model": "fixtures_regress.animal", "fields": {"count": 3, "weight": 1.2, "name": "Lion", "latin_name": "Panthera leo"}}'
        emu_json = '{"pk": 10, "model": "fixtures_regress.animal", "fields": {"count": 42, "weight": 1.2, "name": "Emu", "latin_name": "Dromaius novaehollandiae"}}'
        platypus_json = '{"pk": %d, "model": "fixtures_regress.animal", "fields": {"count": 2, "weight": 2.2, "name": "Platypus", "latin_name": "Ornithorhynchus anatinus"}}'
        platypus_json = platypus_json % animal.pk

        self.assertEqual(len(data), len('[%s]' % ', '.join([lion_json, emu_json, platypus_json])))
        self.assertTrue(lion_json in data)
        self.assertTrue(emu_json in data)
        self.assertTrue(platypus_json in data)
Exemplo n.º 17
0
    def test_dumpdata_uses_default_manager(self):
        """
        Regression for #11286
        Ensure that dumpdata honors the default manager
        Dump the current contents of the database as a JSON fixture
        """
        management.call_command(
            'loaddata',
            'animal.xml',
            verbosity=0,
            commit=False,
        )
        management.call_command(
            'loaddata',
            'sequence.json',
            verbosity=0,
            commit=False,
        )
        animal = Animal(
            name='Platypus',
            latin_name='Ornithorhynchus anatinus',
            count=2,
            weight=2.2
        )
        animal.save()

        stdout = StringIO()
        management.call_command(
            'dumpdata',
            'fixtures_regress.animal',
            format='json',
            stdout=stdout
        )

        # Output order isn't guaranteed, so check for parts
        data = stdout.getvalue()

        # Get rid of artifacts like '000000002' to eliminate the differences
        # between different Python versions.
        data = re.sub('0{6,}\d', '', data)

        lion_json = '{"pk": 1, "model": "fixtures_regress.animal", "fields": {"count": 3, "weight": 1.2, "name": "Lion", "latin_name": "Panthera leo"}}'
        emu_json = '{"pk": 10, "model": "fixtures_regress.animal", "fields": {"count": 42, "weight": 1.2, "name": "Emu", "latin_name": "Dromaius novaehollandiae"}}'
        platypus_json = '{"pk": %d, "model": "fixtures_regress.animal", "fields": {"count": 2, "weight": 2.2, "name": "Platypus", "latin_name": "Ornithorhynchus anatinus"}}'
        platypus_json = platypus_json % animal.pk

        self.assertEqual(len(data), len('[%s]' % ', '.join([lion_json, emu_json, platypus_json])))
        self.assertTrue(lion_json in data)
        self.assertTrue(emu_json in data)
        self.assertTrue(platypus_json in data)
Exemplo n.º 18
0
    def post(self):
        """ASWP-API Animals POST

        Returns:
            dict: Dictionary with success message
            tuple: Tuple with error message and status code
        """
        data = self.parse_request()
        price = data.get("price", None)
        description = data.get("description", None)
        center_id = get_jwt_identity()["center_id"]
        if not Specie.exists(data["specie"]):
            return {"error": "Specified specie does not exist"}, 409
        Animal.add(center_id, data["name"], description, data["age"],
                   data["specie"], price)
        return {"message": "Animal added successfully"}
Exemplo n.º 19
0
def get_animals_by_status(status):
    with sqlite3.connect('../../kennel.db') as conn:
        conn.row_factory = sqlite3.Row
        db_cursor = conn.cursor()

        db_cursor.execute("""
        SELECT
            a.id,
            a.name,
            a.breed,
            a.status,
            a.location_id,
            a.customer_id
        FROM Animal a
        WHERE a.status = ?
        """, (status,))

        animals = []

        dataset = db_cursor.fetchall()

        for row in dataset:

            # Create an animal instance from the current row.
            # Note that the database fields are specified in
            # exact order of the parameters defined in the
            # Animal class above.
            animal = Animal(row['id'], row['name'], row['breed'],
                            row['status'], row['location_id'], row['customer_id'])

            animals.append(animal.__dict__)

    return json.dumps(animals)
Exemplo n.º 20
0
def get_animals_by_status(status):
    with sqlite3.connect("./kennel.db") as conn:
        conn.row_factory = sqlite3.Row
        db_cursor = conn.cursor()

        db_cursor.execute(
            """
        SELECT
            a.id,
            a.name,
            a.breed,
            a.status,
            a.location_id,
            a.customer_id
        FROM animal a
        WHERE a.status = ?
        """, (status, ))

        animals = []
        dataset = db_cursor.fetchall()

        for row in dataset:
            animal = Animal(row['id'], row['name'], row['breed'],
                            row['status'], row['location_id'],
                            row['customer_id'])
            animals.append(animal.__dict__)

    # Use `json` package to properly serialize list as JSON
    return json.dumps(animals)
Exemplo n.º 21
0
def get_animals_by_location(value):

    with sqlite3.connect("./kennel.db") as conn:
        conn.row_factory = sqlite3.Row
        db_cursor = conn.cursor()

        db_cursor.execute("""
        select
            a.id,
            a.name,
            a.breed,
            a.status,
            a.customer_id,
            a.location_id
        FROM animal a
        WHERE a.location_id = ?
        """, ( value, ))

        # Initialize an empty list to hold all animal representations
        animals = []

        dataset = db_cursor.fetchall()

        for row in dataset:
        # Create an customer instance from the current row
            animal = Animal(row['id'], row['name'], row['breed'], row['status'],
                                row['location_id'], row['customer_id'])
            animals.append(animal.__dict__)

        # Return the JSON serialized Customer object
        return json.dumps(animals)
Exemplo n.º 22
0
    def test_generic_inline_formsets(self):
        GenericFormSet = generic_inlineformset_factory(TaggedItem, extra=1)
        formset = GenericFormSet()
        self.assertEqual(u''.join(form.as_p() for form in formset.forms), u"""<p><label for="id_generic_relations-taggeditem-content_type-object_id-0-tag">Tag:</label> <input id="id_generic_relations-taggeditem-content_type-object_id-0-tag" type="text" name="generic_relations-taggeditem-content_type-object_id-0-tag" maxlength="50" /></p>
<p><label for="id_generic_relations-taggeditem-content_type-object_id-0-DELETE">Delete:</label> <input type="checkbox" name="generic_relations-taggeditem-content_type-object_id-0-DELETE" id="id_generic_relations-taggeditem-content_type-object_id-0-DELETE" /><input type="hidden" name="generic_relations-taggeditem-content_type-object_id-0-id" id="id_generic_relations-taggeditem-content_type-object_id-0-id" /></p>""")

        formset = GenericFormSet(instance=Animal())
        self.assertEqual(u''.join(form.as_p() for form in formset.forms), u"""<p><label for="id_generic_relations-taggeditem-content_type-object_id-0-tag">Tag:</label> <input id="id_generic_relations-taggeditem-content_type-object_id-0-tag" type="text" name="generic_relations-taggeditem-content_type-object_id-0-tag" maxlength="50" /></p>
<p><label for="id_generic_relations-taggeditem-content_type-object_id-0-DELETE">Delete:</label> <input type="checkbox" name="generic_relations-taggeditem-content_type-object_id-0-DELETE" id="id_generic_relations-taggeditem-content_type-object_id-0-DELETE" /><input type="hidden" name="generic_relations-taggeditem-content_type-object_id-0-id" id="id_generic_relations-taggeditem-content_type-object_id-0-id" /></p>""")

        platypus = Animal.objects.create(
            common_name="Platypus", latin_name="Ornithorhynchus anatinus"
        )
        platypus.tags.create(tag="shiny")
        GenericFormSet = generic_inlineformset_factory(TaggedItem, extra=1)
        formset = GenericFormSet(instance=platypus)
        tagged_item_id = TaggedItem.objects.get(
            tag='shiny', object_id=platypus.id
        ).id
        self.assertEqual(u''.join(form.as_p() for form in formset.forms), u"""<p><label for="id_generic_relations-taggeditem-content_type-object_id-0-tag">Tag:</label> <input id="id_generic_relations-taggeditem-content_type-object_id-0-tag" type="text" name="generic_relations-taggeditem-content_type-object_id-0-tag" value="shiny" maxlength="50" /></p>
<p><label for="id_generic_relations-taggeditem-content_type-object_id-0-DELETE">Delete:</label> <input type="checkbox" name="generic_relations-taggeditem-content_type-object_id-0-DELETE" id="id_generic_relations-taggeditem-content_type-object_id-0-DELETE" /><input type="hidden" name="generic_relations-taggeditem-content_type-object_id-0-id" value="%s" id="id_generic_relations-taggeditem-content_type-object_id-0-id" /></p><p><label for="id_generic_relations-taggeditem-content_type-object_id-1-tag">Tag:</label> <input id="id_generic_relations-taggeditem-content_type-object_id-1-tag" type="text" name="generic_relations-taggeditem-content_type-object_id-1-tag" maxlength="50" /></p>
<p><label for="id_generic_relations-taggeditem-content_type-object_id-1-DELETE">Delete:</label> <input type="checkbox" name="generic_relations-taggeditem-content_type-object_id-1-DELETE" id="id_generic_relations-taggeditem-content_type-object_id-1-DELETE" /><input type="hidden" name="generic_relations-taggeditem-content_type-object_id-1-id" id="id_generic_relations-taggeditem-content_type-object_id-1-id" /></p>""" % tagged_item_id)

        lion = Animal.objects.create(common_name="Lion", latin_name="Panthera leo")
        formset = GenericFormSet(instance=lion, prefix='x')
        self.assertEqual(u''.join(form.as_p() for form in formset.forms), u"""<p><label for="id_x-0-tag">Tag:</label> <input id="id_x-0-tag" type="text" name="x-0-tag" maxlength="50" /></p>
<p><label for="id_x-0-DELETE">Delete:</label> <input type="checkbox" name="x-0-DELETE" id="id_x-0-DELETE" /><input type="hidden" name="x-0-id" id="id_x-0-id" /></p>""")
Exemplo n.º 23
0
def get_all_animals():
    # Open a connection to the database
    with sqlite3.connect("./Kennel.db") as conn:

        # Just use these. It's a Black Box.
        conn.row_factory = sqlite3.Row
        db_cursor = conn.cursor()

        # Write the SQL query to get the information you want
        db_cursor.execute("""
        SELECT* 
        FROM Animal
        """)

        # Initialize an empty list to hold all animal representations
        animals = []

        # Convert rows of data into a Python list
        dataset = db_cursor.fetchall()

        # Iterate list of data returned from database
        for row in dataset:

            # Create an animal instance from the current row.
            # Note that the database fields are specified in
            # exact order of the parameters defined in the
            # Animal class above.
            animal = Animal(row['id'], row['name'], row['breed'],
                            row['status'], row['location_id'],
                            row['customer_id'])

            animals.append(animal.__dict__)

    # Use `json` package to properly serialize list as JSON
    return json.dumps(animals)
Exemplo n.º 24
0
def get_animals_by_status(status):
    with sqlite3.connect("./kennel.db") as conn:
        conn.row_factory = sqlite3.Row
        db_cursor = conn.cursor()

        db_cursor.execute(
            """
        SELECT
            a.id,
            a.name,
            a.breed,
            a.status,
            a.location_id,
            a.customer_id
        FROM animal a
        WHERE a.status = ?
        """, (status, ))

        animals = []

        dataset = db_cursor.fetchall()

        for row in dataset:

            # Create an animal instance from the current row
            animal = Animal(row['id'], row['name'], row['breed'],
                            row['status'], row['customer_id'],
                            row['location_id'])
            animals.append(animal.__dict__)

        # Return the JSON serialized Customer object
    return json.dumps(animals)
Exemplo n.º 25
0
def get_single_animal(id):
    with sqlite3.connect("./kennel.db") as conn:
        conn.row_factory = sqlite3.Row
        db_cursor = conn.cursor()

        db_cursor.execute(
            """
        SELECT
            a.id,
            a.name,
            a.breed,
            a.status,
            a.location_id,
            a.customer_id
        FROM animal a

        WHERE a.id = ?
        """, (id, ))

        data = db_cursor.fetchone()

        animal = Animal(data['id'], data['name'], data['breed'],
                        data['status'], data['location_id'],
                        data['customer_id'])

        return json.dumps(animal.__dict__)
Exemplo n.º 26
0
def get_animals_by_status(status):
    with sqlite3.connect("kennel.db") as conn:

        conn.row_factory = sqlite3.Row
        db_cursor = conn.cursor()

        db_cursor.execute(
            """ 
        SELECT
            a.id,
            a.name,
            a.breed,
            a.status,
            a.location_id,
            a.customer_id
            FROM animal a
            WHERE a.status = ?
        """, (status, ))

        animals = []

        dataset = db_cursor.fetchall()

        for row in dataset:
            animal = Animal(row["id"], row["name"], row["breed"],
                            row["status"], row["location_id"],
                            row["customer_id"])

            animals.append(animal.__dict__)

    return json.dumps(animals)
Exemplo n.º 27
0
def get_animals_by_location(location_id):
    with sqlite3.connect("kennel.db") as conn:

        conn.row_factory = sqlite3.Row
        db_cursor = conn.cursor()

        db_cursor.execute(
            """ 
        SELECT
            a.id,
            a.name,
            a.breed,
            a.status,
            a.location_id,
            a.customer_id
        FROM animal a
        WHERE a.location_id = ?
        """, (location_id, ))

        animals = []

        dataset = db_cursor.fetchall()

        for row in dataset:
            animal = Animal(row['id'], row['name'], row['breed'],
                            row['status'], row['location_id'],
                            row['customer_id'])

            animals.append(animal.__dict__)

    return json.dumps(animals)
Exemplo n.º 28
0
def get_single_animal(id):
    with sqlite3.connect("./kennel.db") as conn:
        conn.row_factory = sqlite3.Row
        db_cursor = conn.cursor()

        # Use a ? parameter to inject a variable's value
        # into the SQL statement.
        db_cursor.execute(
            """
        SELECT
            a.id,
            a.name,
            a.breed,
            a.status,
            a.location_id,
            a.customer_id
        FROM animal a
        WHERE a.id = ?
        """, (id, ))

        # Load the single result into memory
        data = db_cursor.fetchone()

        # Create an animal instance from the current row
        animal = Animal(data['id'], data['name'], data['breed'],
                        data['status'], data['location_id'],
                        data['customer_id'])

        return json.dumps(animal.__dict__)
Exemplo n.º 29
0
def get_animals_by_status(status):

    with sqlite3.connect("./kennel.db") as conn:
        conn.row_factory = sqlite3.Row
        db_cursor = conn.cursor()

        # Write the SQL query to get the information you want
        db_cursor.execute(
            """
        select
            a.id,
            a.name,
            a.breed,
            a.status,
            a.location_id,
            a.customer_id
        from Animal a
        WHERE a.status = ?
        """, (status, ))

        animals = []
        dataset = db_cursor.fetchall()

        for row in dataset:
            animal = Animal(row['id'], row['name'], row['breed'],
                            row['status'], row['location_id'],
                            row['customer_id'])
            animals.append(animal.__dict__)

    return json.dumps(animals)
Exemplo n.º 30
0
def get_animals_by_location(location):

    with sqlite3.connect("./kennel.db") as conn:
        conn.row_factory = sqlite3.Row
        db_cursor = conn.cursor()

        # Write the SQL query to get the information you want
        db_cursor.execute(
            """
        select
            c.id,
            c.name,
            c.breed,
            c.status,
            c.location_id
            c.customer_id
        from Animal c
        WHERE c.status = ?
        """, (location, ))

        animals = []

        # get data back from SQL request
        dataset = db_cursor.fetchall()

        for row in dataset:
            animal = Animal(row['id'], row['name'], row['breed'],
                            row['status'], row['location_id'],
                            row['customer_id'])
            # adding dictionaries to animals list / animal.__dict__ creates the dictionaries
            animals.append(animal.__dict__)

    return json.dumps(animals)
Exemplo n.º 31
0
Arquivo: app.py Projeto: dai175/foster
    def create_animal_submission(jwt):
        try:
            types = Type.query.order_by(Type.id).all()
        except exc.SQLAlchemyError:
            abort(422)

        form = AnimalForm()

        #  Add category list to form
        form.type.choices = [(type.id, type.name) for type in types]
        if not form.validate_on_submit():
            return jsonify({'success': False})

        animal = Animal(type_id=int(request.form['type']),
                        name=request.form['name'],
                        sex=int(request.form['sex']),
                        date_of_birth=request.form['date_of_birth'],
                        weight=request.form['weight'],
                        place_of_birth=request.form['place_of_birth'],
                        description=request.form['description'])

        error = False

        try:
            db.session.add(animal)
            db.session.commit()

            # Save images as
            file = request.files['image']
            if file:
                filename = upload_image(file, consts.LEAD_ANIMAL, animal.id)
                animal.image = filename
                db.session.commit()
        except exc.SQLAlchemyError:
            error = True
            db.session.rollback()
        finally:
            db.session.close()

        if not error:
            flash('Animal {} was successfully listed!'.format(
                request.form['name']))
        else:
            flash('An error occurred. Animal {} could not be listed.'.format(
                request.form['name']))

        return jsonify({'success': not error})
Exemplo n.º 32
0
    def delete(self, animal_id):
        """ASWP-API Animal DELETE

        Args:
            animal_id (int): ID of Animal to delete

        Returns:
            dict: Dictionary with success message
            tuple: Tuple with error message and status code
        """
        center_id = get_jwt_identity()["center_id"]
        if not Animal.exists(animal_id):
            return {"error": "Animal not found"}, 404
        if not Animal.is_owner(animal_id, center_id):
            return {"error": "You are not allowed to delete this animal"}, 403
        Animal.delete(animal_id)
        return {"message": "Animal deleted successfully"}
Exemplo n.º 33
0
 def post(self):
     predator = self.request.get('predator')
     prey = self.request.get('prey')
     
     animal = Animal.get_by_id(int(predator), parent=PARENT)
     animal.prey.append(ndb.Key("FoodChain", 1, Animal, int(prey)))
     animal.put()
     
     self.redirect('/')
Exemplo n.º 34
0
def upload(request):
    error_msg = False
    user = get_user(request)
    if user.is_authenticated():
    	if request.method == 'POST':
            form = RegisterForm(request.POST)
            if form.is_valid():
                a = Animal() 
                a.name = request.POST.get("name")
    	        #a.sex = request.POST.get("sex")
                #a.type = request.POST.get("type")
                #a.build = request.POST.get("build")
                #a.age = request.POST.get("age")
                #a.variety = request.POST.get("variety")
                #a.reason = request.POST.get("reason")
                #a.accept_num = request.POST.get("accept_num")
                #a.chip_num = request.POST.get("chip_num")
                #a.is_sterilization = request.POST.get("is_sterilization")
                #a.hair_type = request.POST.get("hair_type")
                a.note = request.POST.get("note")
                a.resettlement = request.POST.get("resettlement")
                a.phone = request.POST.get("phone")
                #a.email = request.POST.get("email")
                #a.childre_anlong = request.POST.get("childre_anlong")
                #a.nimal_anlong = request.POST.get("animal_anlong")
                #a.bodyweight = request.POST.get("bodyweight")
       	        image = request.FILES['photo']
 
	        if not ((name is none) or (note is none) or 
   	                (resettlement is none) or (phone is none) or
		        (image is none)):
                    error_msg = "some requirement fields are not filled in"
                else:
		    head, ext = os.path.splitext(image.name)
                    filename = user.get_username() + datetime.now() + ext
	            with open("src/media/" + filename, "wb") as code:
                        code.write(image)
		    a.image_name = filename
		    thumbnail(filename, "248x350")
		    thumbnail(filename, "248x350", TRUE)
		    a.save()
            else:
                print "invalided"
                error_msg = form.errors
        else:
            print "user authenticated failed"

    return render_to_response('upload.html', {'error_msg': error_msg}, context_instance=RequestContext(request))
Exemplo n.º 35
0
    def test_duplicate_pk(self):
        """
        This is a regression test for ticket #3790.
        """
        # Load a fixture that uses PK=1
        management.call_command(
            'loaddata',
            'sequence',
            verbosity=0,
            commit=False
        )

        # Create a new animal. Without a sequence reset, this new object
        # will take a PK of 1 (on Postgres), and the save will fail.

        animal = Animal(
            name='Platypus',
            latin_name='Ornithorhynchus anatinus',
            count=2,
            weight=2.2
        )
        animal.save()
        self.assertGreater(animal.id, 1)
Exemplo n.º 36
0
def upload(request):
    error_msg = False
    user = get_user(request)
    if request.method == 'POST':
        if not user.is_authenticated():
            return HttpResponseRedirect("/")
        form = UploadForm(request.POST, request.FILES)
        if form.is_valid():
            a = Animal() 
            a.name = request.POST.get("name")
    	    #a.sex = request.POST.get("sex")
            #a.type = request.POST.get("type")
            #a.build = request.POST.get("build")
            #a.age = request.POST.get("age")
            #a.variety = request.POST.get("variety")
            #a.reason = request.POST.get("reason")
            #a.accept_num = request.POST.get("accept_num")
            #a.chip_num = request.POST.get("chip_num")
            #a.is_sterilization = request.POST.get("is_sterilization")
            #a.hair_type = request.POST.get("hair_type")
            a.note = request.POST.get("note")
            a.resettlement = request.POST.get("resettlement")
            a.phone = request.POST.get("phone")
            #a.email = request.POST.get("email")
            #a.childre_anlong = request.POST.get("childre_anlong")
            #a.nimal_anlong = request.POST.get("animal_anlong")
            #a.bodyweight = request.POST.get("bodyweight")
            image = request.FILES['photo']
            head, ext = os.path.splitext(image.name)
            #filename = user.get_username() + str(int(time.time())) + ext.lower()
            filename = str(int(time.time())) + ".jpg"
            savefilename = "src/media/" + filename
            # TODO : try-catch for PIL errors
            with open(savefilename, "wb") as code:
                code.write(image.read())
            a.image_file = filename
            thumbnail(savefilename, "248x350")
            thumbnail(savefilename, "248x350", True)
            a.save()
            # TODO : return new page while upload success
            return HttpResponseRedirect("/")
        else:
            print "invalided"
            print form.errors
            return render_to_response('upload.html', {'error_msg': form.errors}, context_instance=RequestContext(request))
    return render_to_response('upload.html', context_instance=RequestContext(request))
Exemplo n.º 37
0
 def get(self):
     animals = [a.as_dict() for a in Animal.query(ancestor=PARENT)]
     template = JINJA_ENVIRONMENT.get_template('index.html')
     self.response.write(template.render({"animals": animals}))
Exemplo n.º 38
0
def subscribeUser():
    results = {
       'borough': "",
       'number': '',
       'animal': None,
       'prey' : None
    }
    BODY_PART_DICT = {
        'la': "Left Arm",
        'ra': "Right Arm",
        'll': "Left Leg",
        "rl": "Right Leg",
        "t": "Tail"
    }
    
    def getFullSubscriber(sub):
        return {
                "number": sub.subscriber.number,
                "animal": {
                    "name": sub.animal.name
                    },
                "body_part": {
                    "name": sub.body_part.name
                    },
                "division":{
                    "name": sub.division.name
                    }   
            }
    '''
    def get_neighborhood_wl(sub):
        #Get div
        div = SubscriberDivision.select().where(SubscriberDivision.subscriber == sub).get().division
        full_wl = FullSubscriber.select().where(FullSubscriber.division==div)
        return full_wl
    '''

    def getPredPrey(x):
        fm = { 
            "animal": x.animal.name,
            "division": x.division.name,
            "location": x.location.address,
            "body_part":x.body_part.name
        }
        print fm
        return fm


    if request.method == "POST":
        try:
            # Check if number exists
            check = None
            try:
                check = Subscriber.get(Subscriber.number == request.form['number'])
            except:
                pass
            if check:
                return render_template('error.html', error="Number already picked. Try another one.")
            sub = Subscriber(number=request.form['number'])
            sub.save()
            an = Animal.get(Animal.name==request.form['animal'])
            
            sa = SubscriberAnimal(subscriber=sub, animal=an)
            sa.save()

            bodypart = BodyPart.get(BodyPart.name==request.form['body_part'])
            sb = SubscriberBodyPart(subscriber=sub, body_part=bodypart)
            sb.save()
            div= Division.get(Division.name==request.form['borough'])
            sd = SubscriberDivision(subscriber=sub, division=div)
            sd.save()
            fs = FullSubscriber(subscriber=sub, animal=an, body_part=bodypart, division=div)
            fs.save()
        except peewee.IntegrityError:
            return render_template("error.html", error="Duplicate Phone Number. Pick Another One.")
        prey = [x.preyAnimal for x in PredPrey.select(PredPrey, Animal).join(Animal).where(PredPrey.predAnimal == fs.animal)]

        preyMurders = []
        for p in prey:
            q = FullMurder.select(FullMurder, Animal, Division, Location, BodyPart).join(Animal).switch(FullMurder).join(Division).switch(FullMurder).join(Location).switch(FullMurder).join(BodyPart).where(FullMurder.animal == p and FullMurder.division == fs.division)
            preyMurders.extend([x for x in q])
        watchlist = FullSubscriber.select(FullSubscriber, Subscriber, Animal, BodyPart, Division).join(Subscriber).switch(FullSubscriber).join(Animal).switch(FullSubscriber).join(BodyPart).switch(FullSubscriber).join(Division).where(FullSubscriber.division == fs.division and FullSubscriber.subscriber != fs.subscriber)
        results['prey'] = [getPredPrey(pm) for pm in preyMurders]
        results['watchlist'] = [getFullSubscriber(sub) for sub in watchlist]
        results['subFull'] = getFullSubscriber(fs)
        results['borough'] = fs.division.name
        results['number'] = fs.subscriber.number
    if request.method == 'GET':
        sub = None
        print request.args.get('number')
        phonenumber = request.args.get('number')
        try:
            sub = Subscriber.get(Subscriber.number== phonenumber)
        except:
            return render_template('error.html', error='Number does not exist. Subscribe by going to subscribe page and registering!')
        fs = FullSubscriber.get(FullSubscriber.subscriber == sub)
        prey = [x.preyAnimal for x in PredPrey.select(PredPrey, Animal).join(Animal).where(PredPrey.predAnimal == fs.animal)]

        preyMurders = []
        for p in prey:
            q = FullMurder.select(FullMurder, Animal, Division, Location, BodyPart).join(Animal).switch(FullMurder).join(Division).switch(FullMurder).join(Location).switch(FullMurder).join(BodyPart).where(FullMurder.animal == p and FullMurder.division == fs.division)
            preyMurders.extend([x for x in q])
        watchlist = FullSubscriber.select(FullSubscriber, Subscriber, Animal, BodyPart, Division).join(Subscriber).switch(FullSubscriber).join(Animal).switch(FullSubscriber).join(BodyPart).switch(FullSubscriber).join(Division).where(FullSubscriber.subscriber != fs.subscriber, FullSubscriber.division == fs.division)
        results['prey'] = [getPredPrey(pm) for pm in preyMurders]
        results['watchlist'] = [getFullSubscriber(sub) for sub in watchlist]
        results['subFull'] = getFullSubscriber(fs)
        results['borough'] = fs.division.name
        results['number'] = fs.subscriber.number
    return render_template("subscriber_results.html", results=results)