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()
def get_initial_simulation_step(): male = Animal() male.gender = GENDER_MALE female = Animal() female.gender = GENDER_FEMALE simulation_step = SimulationStep() simulation_step.animals.append(male) simulation_step.animals.append(female) return simulation_step
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}]}"))
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__)
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)
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)
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>""")
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)
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)
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)
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)
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()
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)
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
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)
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)
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__)
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)
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)
def post(self): name = self.request.get('animal') if name: animal = Animal(parent=PARENT, name=name) animal.put() self.redirect('/')
def update_animal(id, updated_animal): # Iterate the ANIMALS list, but use enumerate() so that # you can access the index value of each item. for index, animal in enumerate(ANIMALS): if animal.id == id: # Found the animal. Update the value. ANIMALS[index] = Animal(updated_animal['id'], updated_animal['name'], updated_animal['species'], updated_animal['status'], updated_animal['location_id'], updated_animal['customer_id']) break
def dummy_data(amount): for i in range(int(amount)): for j in range(1, 5): animal = Animal(animal_type_id=j, name='test', weight=10, age=5) session.add(animal) if i % 1000 == 0: session.commit() return redirect(url_for('stats'))
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)
def test_get_animal(self): cat = Animal(center_id=1, name='cat', description='cat in the boots', age=33, species_id=1, price=100500) db.session.add(cat) db.session.commit() response = self.app.get('/animals/1') self.assertEqual(response.status_code, 200) self.assertEqual(response.json, json.loads("{\"id\": 1, \"name\": \"cat\", \"description\": " "\"cat in the boots\", \"age\": 33, \"price\": 100500.0, " "\"species_id\": 1, \"center_id\": 1}"))
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
def test_too_young(self): animal = Animal() species = Species() species.minimum_breeding_age = 1 simulation_step = SimulationStep() simulation_step.month = 0 self.assertFalse(can_breed(animal, species, simulation_step))
def test(self): animal = Animal() species = Species() species.minimum_breeding_age = 1 simulation_step = SimulationStep() simulation_step.month = MONTHS_IN_YEAR self.assertTrue(can_breed(animal, species, simulation_step))
def test_feed(self): animals = [Animal(), Animal()] # Males cannot reproduce, so we can use them to test if they will die # correctly. simulation_step = SimulationStep() simulation_step.month = 4 simulation_step.animals = animals species = Species() species.life_span = 1 species.monthly_food_consumption = 1 habitat = Habitat() habitat.monthly_food = 1 next_step = advance(simulation_step, species, habitat) # One animal should have died due to starvation from not enough food self.assertEqual(1, len(next_step.animals)) self.assertIn(DEATH_STARVATION, next_step.deaths)
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__)
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)