def test_api_can_add_plant_to_garden_with_no_harvest_date(self): """Sad path test, plants can be added without harvest date.""" garden = Garden(id=1) zeke = Plant(plant_type='Cherry Tomato', image='jim_photo.jpg', lighting='Full Sun', water_frequency=3, harvest_time=50, root_depth=12, annual="Annual") dan = Plant(plant_type='Cactus', image='cactus_dan.jpg', lighting='Full Sun', water_frequency=7, harvest_time=None, root_depth=8, annual="Annual") db.session.add_all([zeke, dan, garden]) db.session.commit() res = self.client().post( '/api/v1/garden?plant_id={}&plant_name=Cactus Dan'.format(dan.id)) self.assertEqual(res.status_code, 201) json_response = json.loads(res.data) self.assertIsNotNone(json_response['garden_plant_id']) self.assertEqual(dan.id, json_response['plant_id']) self.assertEqual(garden.id, json_response['garden_id']) self.assertEqual("Cactus Dan", json_response['plant_name']) self.assertEqual("N/A", json_response['harvest_date']) self.assertNotEqual(zeke.id, json_response['plant_id'])
def test_api_can_return_a_random_plant(self): """GET request to return a ranom plant from the DB.""" zeke = Plant(plant_type='Cherry Tomato', image='jim_photo.jpg', lighting='Full Sun', water_frequency=3, harvest_time=50, root_depth=12, annual="Annual") dan = Plant(plant_type='Cactus', image='cactus_dan.jpg', lighting='Full Sun', water_frequency=7, harvest_time=None, root_depth=8, annual="Annual") agatha = Plant(plant_type='Roma Tomato', image='agatha_photo.jpg', lighting='Full Sun', water_frequency=2, harvest_time=60, root_depth=12, annual="Annual") db.session.add_all([zeke, dan, agatha]) db.session.commit() res = self.client().get('/api/v1/plants/meet') self.assertEqual(res.status_code, 200) json_response = json.loads(res.data) self.assertIsNotNone(json_response['id']) self.assertIsNotNone(json_response['plant_type']) self.assertIsNotNone(json_response['plant_image'])
def test_api_can_update_watering_information(self): """PUT request for watering a garden plant.""" garden = Garden(id=1) zeke = Plant(plant_type='Cherry Tomato', image='jim_photo.jpg', lighting='Full Sun', water_frequency=3, harvest_time=50, root_depth=12, annual="Annual") dan = Plant(id=5, plant_type='Cactus', image='cactus_dan.jpg', lighting='Full Sun', water_frequency=7, harvest_time=None, root_depth=8, annual="Annual") db.session.add_all([zeke, dan, garden]) db.session.commit() res_zeke = self.client().post( '/api/v1/garden?plant_id={}&plant_name=Ezekiel'.format(zeke.id)) res_dan = self.client().post( '/api/v1/garden?plant_id={}&plant_name=Dan'.format(dan.id)) dan_json_response = json.loads(res_dan.data) zeke_json_response = json.loads(res_zeke.data) self.assertEqual("Dan", dan_json_response['plant_name']) water_res = self.client().put( '/api/v1/garden/water?garden_plant_id={}'.format( dan_json_response['garden_plant_id'])) self.assertEqual(water_res.status_code, 201) last_watered = datetime.now().strftime("%a, %B %d, %Y") next_water = ( datetime.now() + timedelta(days=dan.water_frequency)).strftime("%a, %B %d, %Y") water_json_response = json.loads(water_res.data) self.assertEqual(dan_json_response['garden_plant_id'], water_json_response['id']) self.assertEqual(dan_json_response['plant_name'], water_json_response['name']) self.assertEqual(dan.plant_type, water_json_response['plant_type']) self.assertEqual(dan.water_frequency, water_json_response['water_frequency']) self.assertEqual(last_watered, water_json_response['last_watered']) self.assertEqual(next_water, water_json_response['next_water']) self.assertNotEqual(zeke_json_response['garden_plant_id'], water_json_response['id']) self.assertNotEqual(zeke_json_response['plant_name'], water_json_response['name']) self.assertNotEqual(zeke.plant_type, water_json_response['plant_type']) self.assertNotEqual(zeke.water_frequency, water_json_response['water_frequency'])
def test_seach_for_a_plant(self): """Plant model can search for plants with a keyword.""" zeke = Plant(plant_type='Cherry Tomato', image='jim_photo.jpg', lighting='Full Sun', water_frequency=3, harvest_time=50, root_depth=12, annual="Annual") dan = Plant(plant_type='Cactus', image='cactus_dan.jpg', lighting='Full Sun', water_frequency=7, harvest_time=None, root_depth=8, annual="Annual") agatha = Plant(plant_type='Roma Tomato', image='agatha_photo.jpg', lighting='Full Sun', water_frequency=2, harvest_time=60, root_depth=12, annual="Annual") db.session.add_all([zeke, dan, agatha]) db.session.commit() results = Plant.plant_search('cactus') self.assertEqual(1, len(results)) cactus_dan = results[0] self.assertEqual(dan.id, cactus_dan.id) self.assertNotEqual(zeke.id, cactus_dan.id) self.assertNotEqual(agatha.id, cactus_dan.id)
def test_it_can_retrieve_all_plants(self): """Plants can look up all plant objects in the DB.""" zeke = Plant(plant_type='Cherry Tomato', image='jim_photo.jpg', lighting='Full Sun', water_frequency=3, harvest_time=50, root_depth=12, annual="Annual") dan = Plant(plant_type='Cactus', image='cactus_dan.jpg', lighting='Full Sun', water_frequency=7, harvest_time=None, root_depth=8, annual="Annual") agatha = Plant(plant_type='Roma Tomato', image='agatha_photo.jpg', lighting='Full Sun', water_frequency=2, harvest_time=60, root_depth=12, annual="Annual") db.session.add_all([zeke, dan, agatha]) db.session.commit() plants = Plant.get_all() self.assertIn(zeke, plants) self.assertIn(dan, plants) self.assertIn(agatha, plants)
def test_api_can_return_a_plant_by_id(self): """GET request to return a single plant by its ID.""" jimmy = Plant(plant_type='Cherry Tomato', image='jim_photo.jpg', lighting='Full Sun', water_frequency=3, harvest_time=50, root_depth=12, annual="Annual") dan = Plant(plant_type='Cactus', image='cactus_dan.jpg', lighting='Full Sun', water_frequency=7, harvest_time=None, root_depth=8, annual="Annual") db.session.add_all([jimmy, dan]) db.session.commit() res = self.client().get('/api/v1/plants/{}'.format(jimmy.id)) self.assertEqual(res.status_code, 200) json_response = json.loads(res.data) self.assertNotEqual(dan.id, json_response['id']) self.assertEqual(jimmy.id, json_response['id']) self.assertEqual(jimmy.plant_type, json_response['plant_type']) self.assertEqual(jimmy.image, json_response['plant_image']) self.assertEqual(jimmy.lighting, json_response['lighting']) self.assertEqual(jimmy.water_frequency, json_response['days_between_water']) self.assertEqual(jimmy.harvest_time, json_response['days_to_harvest_from_seed']) self.assertEqual(jimmy.root_depth, json_response['root_depth_in']) self.assertEqual(jimmy.annual, json_response['lifecycle'])
def test_it_can_get_a_plant_by_id(self): """Plant model can return a plant by its ID.""" zeke = Plant(plant_type='Cherry Tomato', image='jim_photo.jpg', lighting='Full Sun', water_frequency=3, harvest_time=50, root_depth=12, annual="Annual") dan = Plant(plant_type='Cactus', image='cactus_dan.jpg', lighting='Full Sun', water_frequency=7, harvest_time=None, root_depth=8, annual="Annual") agatha = Plant(plant_type='Roma Tomato', image='agatha_photo.jpg', lighting='Full Sun', water_frequency=2, harvest_time=60, root_depth=12, annual="Annual") db.session.add_all([zeke, dan, agatha]) db.session.commit() plant = Plant.get_by_id(zeke.id) self.assertEqual(zeke.id, plant.id) self.assertNotEqual(dan.id, plant.id) self.assertNotEqual(agatha.id, plant.id)
def index(): form = PlantForm() if form.validate_on_submit(): new_plant = Plant(type=form.type.data, pot=form.pot.data, watering_frequency=form.watering_frequency.data, user_id=current_user.id, next_water_date=datetime.utcnow() + timedelta(days=form.watering_frequency.data)) db.session.add(new_plant) db.session.commit() flash('New plant added!') return redirect(url_for('index')) plants = Plant.query.filter_by(user_id=current_user.id) plant_list = [] # This loop to update my existing table that didn't have water date populated. for plant in plants: plant.update_water_date() plant_list.append(plant.type) print(plant_list) plant_count = Plant.query.filter_by(user_id=current_user.id).count() #TODO add form to update watering date or other properties. #update_form = UpdatePlantForm() return render_template('index.html', title='Home', plants=plants, form=form, plant_count=plant_count)
def test_api_can_return_all_plants_in_garden(self): """GET request for returning all gardenplants.""" garden = Garden(id=1) zeke = Plant(plant_type='Cherry Tomato', image='jim_photo.jpg', lighting='Full Sun', water_frequency=3, harvest_time=50, root_depth=12, annual="Annual") dan = Plant(plant_type='Cactus', image='cactus_dan.jpg', lighting='Full Sun', water_frequency=7, harvest_time=None, root_depth=8, annual="Annual") agatha = Plant(plant_type='Roma Tomato', image='agatha_photo.jpg', lighting='Full Sun', water_frequency=2, harvest_time=60, root_depth=12, annual="Annual") db.session.add_all([zeke, dan, agatha, garden]) db.session.commit() res = self.client().post( '/api/v1/garden?plant_id={}&plant_name=Ezekiel'.format(zeke.id)) res = self.client().post( '/api/v1/garden?plant_id={}&plant_name=Dan'.format(dan.id)) res = self.client().get('/api/v1/garden') self.assertEqual(res.status_code, 200) json_response = json.loads(res.data) self.assertEqual(len(json_response), 2) self.assertEqual(zeke.id, json_response[0]['id']) self.assertEqual("Ezekiel", json_response[0]['plant_name']) self.assertEqual(dan.id, json_response[1]['id']) self.assertEqual("Dan", json_response[1]['plant_name']) self.assertNotEqual(agatha.id, json_response[0]['id']) self.assertNotEqual(agatha.id, json_response[1]['id'])
def test_api_can_search_for_a_plant_type_sad_path(self): """Sad path testing for plant search.""" jimmy = Plant(plant_type='Cherry Tomato', image='jim_photo.jpg', lighting='Full Sun', water_frequency=3, harvest_time=50, root_depth=12, annual="Annual") agatha = Plant(plant_type='Roma Tomato', image='agatha_photo.jpg', lighting='Full Sun', water_frequency=2, harvest_time=60, root_depth=12, annual="Annual") dan = Plant(plant_type='Cactus', image='cactus_dan.jpg', lighting='Full Sun', water_frequency=7, harvest_time=None, root_depth=8, annual="Annual") db.session.add_all([jimmy, agatha, dan]) db.session.commit() res = self.client().get('/api/v1/plants/search?q=elephant') self.assertEqual(res.status_code, 200) no_response_image = 'https://images.unsplash.com/reserve/unsplash_529f1a3f2f5ed_1.JPG' no_response_message = 'Oh Crop! We did not find any plants called elephant. Maybe try a different search term?' json_response = json.loads(res.data) self.assertEqual(len(json_response), 1) self.assertEqual(no_response_image, json_response[0]['plant_image']) self.assertEqual(no_response_message, json_response[0]['plant_type']) self.assertNotIn(jimmy.id, json_response) self.assertNotIn(jimmy.plant_type, json_response) self.assertNotIn(jimmy.image, json_response) self.assertNotIn(agatha.id, json_response) self.assertNotIn(agatha.plant_type, json_response) self.assertNotIn(agatha.image, json_response) self.assertNotIn(dan.id, json_response) self.assertNotIn(dan.plant_type, json_response) self.assertNotIn(dan.image, json_response)
def test_new_plant(self): """ GIVEN a Plant model WHEN a new Plant is created THEN ensure that all fields set correctly """ plant = Plant(id=1, type="type") assert plant.id == 1 assert plant.type == "type"
def test_api_can_add_plant_to_garden(self): """POST request for adding a plant to a garden.""" garden = Garden(id=1) zeke = Plant(plant_type='Cherry Tomato', image='jim_photo.jpg', lighting='Full Sun', water_frequency=3, harvest_time=50, root_depth=12, annual="Annual") agatha = Plant(plant_type='Roma Tomato', image='agatha_photo.jpg', lighting='Full Sun', water_frequency=2, harvest_time=60, root_depth=12, annual="Annual") dan = Plant(plant_type='Cactus', image='cactus_dan.jpg', lighting='Full Sun', water_frequency=7, harvest_time=None, root_depth=8, annual="Annual") db.session.add_all([zeke, agatha, dan, garden]) db.session.commit() harvest_date = (datetime.now() + timedelta(days=50)) parsed_harvest_date = harvest_date.strftime("%a, %B %d, %Y") res = self.client().post( '/api/v1/garden?plant_id={}&plant_name=Ezekiel'.format(zeke.id)) self.assertEqual(res.status_code, 201) json_response = json.loads(res.data) self.assertIsNotNone(json_response['garden_plant_id']) self.assertEqual(zeke.id, json_response['plant_id']) self.assertEqual(garden.id, json_response['garden_id']) self.assertEqual("Ezekiel", json_response['plant_name']) self.assertEqual(parsed_harvest_date, json_response['harvest_date']) self.assertNotEqual(agatha.id, json_response['plant_id']) self.assertNotEqual(dan.id, json_response['plant_id'])
def test_api_can_search_for_a_plant_type(self): """GET request to return plants with keyword search.""" jimmy = Plant(plant_type='Cherry Tomato', image='jim_photo.jpg', lighting='Full Sun', water_frequency=3, harvest_time=50, root_depth=12, annual="Annual") agatha = Plant(plant_type='Roma Tomato', image='agatha_photo.jpg', lighting='Full Sun', water_frequency=2, harvest_time=60, root_depth=12, annual="Annual") dan = Plant(plant_type='Cactus', image='cactus_dan.jpg', lighting='Full Sun', water_frequency=7, harvest_time=None, root_depth=8, annual="Annual") db.session.add_all([jimmy, agatha, dan]) db.session.commit() res = self.client().get('/api/v1/plants/search?q=tomato') self.assertEqual(res.status_code, 200) json_response = json.loads(res.data) self.assertEqual(len(json_response), 2) self.assertEqual(jimmy.id, json_response[0]['id']) self.assertEqual(jimmy.plant_type, json_response[0]['plant_type']) self.assertEqual(jimmy.image, json_response[0]['plant_image']) self.assertEqual(agatha.id, json_response[1]['id']) self.assertEqual(agatha.plant_type, json_response[1]['plant_type']) self.assertEqual(agatha.image, json_response[1]['plant_image']) self.assertNotIn(dan.id, json_response) self.assertNotIn(dan.plant_type, json_response) self.assertNotIn(dan.image, json_response)
def test_api_can_return_msg_when_no_plants_are_in_garden(self): """ Sad path test for returning garden plants. Garden plants are plants in the DB that have been assigned to a garden. Many gardens can have many plants through gardenplants. Garden plants not only hold a foreign key of a plant and a garden, but also specific information about planting and watering of that particular plant in that particular garden. """ garden = Garden(id=1) zeke = Plant(plant_type='Cherry Tomato', image='jim_photo.jpg', lighting='Full Sun', water_frequency=3, harvest_time=50, root_depth=12, annual="Annual") dan = Plant(plant_type='Cactus', image='cactus_dan.jpg', lighting='Full Sun', water_frequency=7, harvest_time=None, root_depth=8, annual="Annual") agatha = Plant(plant_type='Roma Tomato', image='agatha_photo.jpg', lighting='Full Sun', water_frequency=2, harvest_time=60, root_depth=12, annual="Annual") db.session.add_all([zeke, dan, agatha, garden]) db.session.commit() res = self.client().get('/api/v1/garden') self.assertEqual(res.status_code, 200) json_response = json.loads(res.data) self.assertEqual('You have no plants in your garden', json_response['info'])
def test_follow_plants(self): # create four users u1 = User(username='******', email='*****@*****.**') u2 = User(username='******', email='*****@*****.**') u3 = User(username='******', email='*****@*****.**') u4 = User(username='******', email='*****@*****.**') db.session.add_all([u1, u2, u3, u4]) # create four plants now = datetime.utcnow() p1 = Plant(body="plant from john", author=u1, timestamp=now + timedelta(seconds=1)) p2 = Plant(body="plant from susan", author=u2, timestamp=now + timedelta(seconds=4)) p3 = Plant(body="plant from mary", author=u3, timestamp=now + timedelta(seconds=3)) p4 = Plant(body="plant from david", author=u4, timestamp=now + timedelta(seconds=2)) db.session.add_all([p1, p2, p3, p4]) db.session.commit() # setup the followers u1.follow(u2) # john follows susan u1.follow(u4) # john follows david u2.follow(u3) # susan follows mary u3.follow(u4) # mary follows david db.session.commit() # check the followed plants of each user f1 = u1.followed_plants().all() f2 = u2.followed_plants().all() f3 = u3.followed_plants().all() f4 = u4.followed_plants().all() self.assertEqual(f1, [p2, p4, p1]) self.assertEqual(f2, [p2, p3]) self.assertEqual(f3, [p3, p4]) self.assertEqual(f4, [p4])
def test_a_plant_can_get_a_random_plant(self): """Plant model can return a random plant in the DB.""" zeke = Plant(plant_type='Cherry Tomato', image='jim_photo.jpg', lighting='Full Sun', water_frequency=3, harvest_time=50, root_depth=12, annual="Annual") dan = Plant(plant_type='Cactus', image='cactus_dan.jpg', lighting='Full Sun', water_frequency=7, harvest_time=None, root_depth=8, annual="Annual") agatha = Plant(plant_type='Roma Tomato', image='agatha_photo.jpg', lighting='Full Sun', water_frequency=2, harvest_time=60, root_depth=12, annual="Annual") db.session.add_all([zeke, dan, agatha]) db.session.commit() plant = Plant.random_plant() ids = [zeke.id, dan.id, agatha.id] self.assertIn(plant.id, ids) self.assertIsNotNone(plant.plant_type) self.assertIsNotNone(plant.image) self.assertIsNotNone(plant.lighting) self.assertIsNotNone(plant.water_frequency) self.assertIsNotNone(plant.root_depth) self.assertIsNotNone(plant.annual) self.assertTrue(type(plant) == Plant) self.assertFalse(type(plant) == Garden) self.assertFalse(type(plant) == GardenPlant)
def test_api_can_return_all_plants(self): """GET request to return all plants in the DB.""" zeke = Plant(plant_type='Cherry Tomato', image='jim_photo.jpg', lighting='Full Sun', water_frequency=3, harvest_time=50, root_depth=12, annual="Annual") dan = Plant(plant_type='Cactus', image='cactus_dan.jpg', lighting='Full Sun', water_frequency=7, harvest_time=None, root_depth=8, annual="Annual") agatha = Plant(plant_type='Roma Tomato', image='agatha_photo.jpg', lighting='Full Sun', water_frequency=2, harvest_time=60, root_depth=12, annual="Annual") db.session.add_all([zeke, dan, agatha]) db.session.commit() res = self.client().get('/api/v1/plants/') self.assertEqual(res.status_code, 200) json_response = json.loads(res.data) self.assertEqual(len(json_response), 3) self.assertEqual(zeke.id, json_response[0]['id']) self.assertEqual(zeke.image, json_response[0]['image']) self.assertEqual(dan.id, json_response[1]['id']) self.assertEqual(dan.image, json_response[1]['image']) self.assertEqual(agatha.id, json_response[2]['id']) self.assertEqual(agatha.image, json_response[2]['image'])
def garden(garden_name, garden_id): garden = Garden.query.filter_by(id=garden_id).first_or_404() plants = garden.plants form = PlantFormFromGardenPage() if form.validate_on_submit(): plant = Plant(name=form.plant.data, grower=current_user, garden=garden) db.session.add(plant) db.session.commit() flash('Your plant is now live!') return redirect(url_for('main.index')) return render_template('garden.html', form=form, garden=garden, plants=plants)
def submit_user_plant_by_token(): id = g.current_user.id user = User.query.get(id) data = request.get_json() or {} plant_text = data['plantName'] garden_id = data['gardenID'] garden = Garden.query.get(garden_id) if plant_text is None: return bad_request('No post text found.') if garden_id is None: return bad_request('No garden_id found.') if garden is None: return bad_request('No garden found.') if user is None: return bad_request('No user found.') plant = Plant(name=plant_text, grower=user, garden=garden) db.session.add(plant) db.session.commit() #response.status_code = 201 #response = plant.to_dict() response = jsonify(plant.to_dict()) response.headers['Location'] = url_for('api.get_current_user_plants') return response
def test_api_can_search_for_a_plant_is_alphabetical(self): """Plant search comes back in alphabetical order.""" jimmy = Plant(plant_type='Cherry Tomato', image='jim_photo.jpg', lighting='Full Sun', water_frequency=3, harvest_time=50, root_depth=12, annual="Annual") agatha = Plant(plant_type='Roma Tomato', image='agatha_photo.jpg', lighting='Full Sun', water_frequency=2, harvest_time=60, root_depth=12, annual="Annual") dan = Plant(plant_type='Cactus', image='cactus_dan.jpg', lighting='Full Sun', water_frequency=7, harvest_time=None, root_depth=8, annual="Annual") db.session.add_all([jimmy, agatha, dan]) db.session.commit() res = self.client().get('/api/v1/plants/search?q=a') self.assertEqual(res.status_code, 200) json_response = json.loads(res.data) # For easier readability, each plant type is listed in order below: # dan.plant_type: 'Cactus' # jimmy.plant_type: 'Cherry Tomato' # agatha.plant_type: 'Roma Tomato' self.assertEqual(dan.plant_type, json_response[0]['plant_type']) self.assertEqual(jimmy.plant_type, json_response[1]['plant_type']) self.assertEqual(agatha.plant_type, json_response[2]['plant_type'])
def test_api_can_return_garden_plant_profile_page(self): """GET request for gardenplant by ID (profile page).""" garden = Garden(id=1) adrian = Plant(id=5, plant_type='Buckcherry', image='adrian_photo.jpg', lighting='Full Sun', water_frequency=5, harvest_time=50, root_depth=12, annual="Annual") db.session.add_all([adrian, garden]) db.session.commit() add_adrian_res = self.client().post( '/api/v1/garden?plant_id={}&plant_name=Adrian'.format(adrian.id)) add_adrian_json = json.loads(add_adrian_res.data) gardenplant_id = add_adrian_json['garden_plant_id'] profile_res = self.client().get( '/api/v1/garden/plants/{}'.format(gardenplant_id)) self.assertEqual(profile_res.status_code, 200) profile_json_response = json.loads(profile_res.data) today = datetime.now().strftime("%a, %B %d, %Y") harvest_date = ( datetime.now() + timedelta(days=adrian.harvest_time)).strftime("%a, %B %d, %Y") remaining_harvest = ( (datetime.now() + timedelta(days=adrian.harvest_time)) - datetime.now()).days self.assertEqual(gardenplant_id, profile_json_response['gardenplant_id']) self.assertEqual("Adrian", profile_json_response['plant_name']) self.assertEqual(today, profile_json_response['date_added']) self.assertEqual(today, profile_json_response['last_watered']) self.assertEqual(harvest_date, profile_json_response['harvest_date']) self.assertEqual(remaining_harvest, profile_json_response['days_until_harvest']) self.assertEqual(adrian.plant_type, profile_json_response['plant_type']) self.assertEqual(adrian.image, profile_json_response['image']) self.assertIsNotNone(profile_json_response['days_until_next_water'])
def get_locations(): page = request.args.get('page', 1, type=int) per_page = min(request.args.get('per_page', 10000, type=int), 10000) data = Garden.to_collection_dict( Garden.query.filter(Garden.lat != None, Garden.lon != None).order_by(Garden.address), page, per_page, 'api.get_locations') all_gardens = Garden.query.all() coords = [] locations = [] for garden in all_gardens: garden_plants_objs_arr = [] if garden.lat and garden.lon: address = garden.address lat = garden.lat lon = garden.lon coord = (lat, lon) garden_plants = garden.plants.all() for plant in garden_plants: plant_obj = Plant.to_dict(plant) garden_plants_objs_arr.append(plant_obj) garden_obj = Garden.to_dict(garden) #handle the case where two markers would be placed in hte exact #same spot, where only one would be visible and usable in the #google maps once rendered if coord in coords: #find the index of the first garden for a given coord index = coords.index(coord) #use index of given coord to select the corresponding #location_for_markers in its list and extend the plants list locations[index]['gardens'].append(garden_obj) locations[index]['plants'].extend(garden_plants_objs_arr) elif coord not in coords: coords.append(coord) location = { 'address': address, 'latitude': lat, 'longitude': lon, 'gardens': [garden_obj], 'plants': garden_plants_objs_arr } locations.append(location) return jsonify(locations)
def test_a_plant_has_attributes(self): """Test plant model attributes.""" agatha = Plant(plant_type='Roma Tomato', image='agatha_photo.jpg', lighting='Full Sun', water_frequency=2, harvest_time=60, root_depth=12, annual="Annual") db.session.add_all([agatha]) db.session.commit() self.assertTrue(type(agatha.id) is int) self.assertEqual(agatha.plant_type, 'Roma Tomato') self.assertEqual(agatha.image, 'agatha_photo.jpg') self.assertEqual(agatha.lighting, 'Full Sun') self.assertEqual(agatha.water_frequency, 2) self.assertEqual(agatha.harvest_time, 60) self.assertEqual(agatha.root_depth, 12) self.assertEqual(agatha.annual, "Annual")
def plant(): form1 = PostForm() form2 = PlantFormDropDown() form2.garden.choices = [(g.id, g.name) for g in current_user.gardens] if form2.submit.data: id = form2.garden.data garden = Garden.query.filter_by(id=id).first() if form2.validate_on_submit(): id = form2.garden.data garden = Garden.query.filter_by(id=id).first() plant = Plant(name=form2.plant.data, grower=current_user, garden=garden) db.session.add(plant) db.session.commit() flash('Your plant is now live!') return redirect(url_for('main.index')) else: return redirect(url_for('main.index'))
def test_api_can_remove_a_plant_from_a_garden(self): """DELETE request for removing a plant from a garden.""" garden = Garden(id=1) lincoln = Plant(plant_type='Lime', image='lincoln_photo.jpg', lighting='Full Sun', water_frequency=5, harvest_time=50, root_depth=12, annual="Annual") db.session.add_all([lincoln, garden]) db.session.commit() res = self.client().post( '/api/v1/garden?plant_id={}&plant_name=Lincoln'.format(lincoln.id)) data_dict = json.loads(res.data) gardenplant_id = data_dict['garden_plant_id'] res1 = self.client().get('/api/v1/garden') self.assertEqual(res1.status_code, 200) lincoln_in_garden_json_response = json.loads(res1.data) self.assertEqual("Lincoln", lincoln_in_garden_json_response[0]['plant_name']) self.assertEqual(lincoln.id, lincoln_in_garden_json_response[0]['id']) res2 = self.client().delete( '/api/v1/garden/plants/{}'.format(gardenplant_id)) self.assertEqual(res2.status_code, 202) lincoln_out_of_garden_json_response = json.loads(res2.data) self.assertEqual("Lincoln", lincoln_out_of_garden_json_response['plant_name']) self.assertEqual(gardenplant_id, lincoln_out_of_garden_json_response['gardenplant_id']) res3 = self.client().get('/api/v1/garden') self.assertEqual(res3.status_code, 200) no_plants_garden_json_response = json.loads(res3.data) self.assertEqual("You have no plants in your garden", no_plants_garden_json_response['info'])
def register_plant(): form = PlantRegistrationForm() if form.validate_on_submit(): last_watered_datetime = datetime.combine(form.last_watered_date.data, form.last_watered_time.data) filename = images.save(request.files['photo']) url = images.url(filename) plant = Plant(name=form.name.data, location=form.location.data, last_watered=last_watered_datetime, image_filename=filename, image_url=url) db.session.add(plant) db.session.commit() flash('Congratulations, new plant registered') return redirect(url_for('index')) return render_template('register_plant.html', title='Register Plant', form=form)
address = ad[0] if address != '': response = requests.get( 'https://maps.googleapis.com/maps/api/geocode/json?address={}&key={}' .format(address, gkey)) responseJSON = response.json() lat = responseJSON['results'][0]['geometry']['location']['lat'] lon = responseJSON['results'][0]['geometry']['location']['lng'] for g in ad[3]: new_garden = Garden(name=g[0], address=address, lat=lat, lon=lon) new_garden.users.append(new_user) session.add(new_garden) print("Garden Name: ", new_garden.name, " Grower: ", new_user.username) for p in g[1]: new_plant = Plant(name=p, grower=new_user, garden=new_garden) session.add(new_plant) print(new_plant.name) post_body = random.choice(posts) post = Post(body=post_body, author=new_user) session.add(post) session.commit() print("-------------------------------------------------------------------") print("-------------------------------------------------------------------") print("-------------------------------------------------------------------") print("-------------------------------------------------------------------") print("Users, Gardens, Plants, and Posts added successfully!!!") print("-------------------------------------------------------------------") print("-------------------------------------------------------------------") print("-------------------------------------------------------------------")
def index(): gkey = current_app.config['GOOGLEMAPS_KEY_ALL'] form1 = PostForm() form2 = PlantFormDropDown() form3 = PostReplyForm() form2.garden.choices = [(g.id, g.name) for g in current_user.gardens] if form1.submit1.data and form1.validate_on_submit(): post = Post(body=form1.post.data, author=current_user) db.session.add(post) db.session.commit() flash('Your post is now live!') return redirect(url_for('main.index')) if form2.submit2.data and form2.validate_on_submit(): id = form2.garden.data garden = Garden.query.filter_by(id=id).first() plant = Plant(name=form2.plant.data, grower=current_user, garden=garden) db.session.add(plant) db.session.commit() flash('Your plant is now live!') return redirect(url_for('main.index')) if form3.submit3.data and form3.validate_on_submit(): parent_post = Post.query.get(int(form3.parent_post_id.data)) if parent_post is not None: post = Post(body=form3.post.data, reply_post=True, author=current_user, parent_comment=parent_post) db.session.add(post) db.session.commit() flash('Your reply is now live!') return redirect(url_for('main.index')) else: flash('Your reply did not go through') return redirect(url_for('main.index')) posts_page = request.args.get('posts_page', 1, type=int) plants_page = request.args.get('plants_page', 1, type=int) posts = current_user.followed_posts().paginate( posts_page, current_app.config['POSTS_PER_PAGE'], False) plants = current_user.followed_plants().paginate( plants_page, current_app.config['PLANTS_PER_PAGE'], False) plants_next_url = url_for('main.index', plants_page=plants.next_num, posts_page=posts_page) \ if plants.has_next else None plants_prev_url = url_for('main.index', plants_page=plants.prev_num, posts_page=posts_page) \ if plants.has_prev else None posts_next_url = url_for('main.index', plants_page=plants_page, posts_page=posts.next_num) \ if posts.has_next else None posts_prev_url = url_for('main.index', plants_page=plants_page, posts_page=posts.prev_num) \ if posts.has_prev else None gardens = current_user.gardens coords = [] locations_for_markers = [] markers = [] for garden in gardens: if garden.lat and garden.lon: lat = garden.lat lon = garden.lon coord = (lat, lon) garden_plants = garden.plants.all() #handle the case where two markers would be placed in hte exact same spot, where only one would be visible and usable in the google maps once rendered if coord in coords: #find the index of the first garden for a given coord index = coords.index(coord) #use index of given coord to select the corresponding location_for_markers in its list and extend the plants list locations_for_markers[index][2].extend(garden_plants) elif coord not in coords: coords.append(coord) location_for_markers = (lat, lon, garden_plants) locations_for_markers.append(location_for_markers) for location_for_markers in locations_for_markers: location_plants = location_for_markers[2] infobox_plants = '' for location_plant in location_plants: infobox_plants = infobox_plants + '<li style="list-style-type: none;">' + location_plant.name + '</li>' lat = location_for_markers[0] lon = location_for_markers[1] icon = str( url_for('static', filename='agriculture_map_icons/iboga.png')) embed_img = '<iframe width="280" height="300" frameborder="0" style="border:0" src="https://www.google.com/maps/embed/v1/streetview?location={},{}&key={}" allowfullscreen></iframe>'.format( lat, lon, gkey) infobox = '<h3 style="strong">{}'s plants at this location</h3><ul>{}</ul>{}'.format( current_user.username, infobox_plants, embed_img) marker = {'icon': icon, 'lat': lat, 'lng': lon, 'infobox': infobox} markers.append(marker) mymap = Map( identifier="mymap", lat=45.487292, lng=-122.635435, style="height:500px;width:100%;margin-bottom=:20px;", markers=markers, ) return render_template("index.html", title='Home Page', form1=form1, form2=form2, posts=posts.items, posts_next_url=posts_next_url, posts_prev_url=posts_prev_url, plants=plants.items, plants_next_url=plants_next_url, plants_prev_url=plants_prev_url, mymap=mymap, gardens=gardens, form3=form3)
def get_all_plants_for_maps(): page = request.args.get('page', 1, type=int) per_page = min(request.args.get('per_page', 10000, type=int), 100) data = Plant.to_collection_dict(Plant.query, page, per_page, 'api.get_all_plants_for_maps') return jsonify(data)
def create_plant(db: Session, new_plant: Plant_base): db_plant = Plant(**new_plant.dict()) db.add(db_plant) db.commit() return db_plant