def delete_plant_in_garden(garden_id: str, plant_id: str): if 'email' not in session: abort(403) if not is_valid_id(garden_id): abort(401) if not is_valid_id(plant_id): abort(401) with util.MongoConnect(): user = users.objects(email=session['email']) if str(user) == '[]': abort(401) user = user[0] # need to do str(i) because user.gardens is a list of ObjectIdFields if garden_id in [str(i) for i in user.gardens]: try: garden = gardens.objects(id=garden_id) except Exception as e: abort(404) if str(garden) == '[]': abort(404) garden = garden[0] # same as above if plant_id not in [str(i) for i in garden.plants]: abort(401) try: plant = user_plants.objects(id=plant_id) except Exception as e: abort(404) if str(plant) == '[]': abort(404) plant = plant[0] plant_type = plant_types.objects(id=str(plant.plant_type_id)) if str(plant_type) == '[]': abort(401) plant_type = plant_type[0] #goes in place of "Water it": plant_type["watering_description"] garden.plants.remove(plant.id) garden.save() plant.delete() else: abort(401) return "", 200
# print(catalog_file) # Connects to mongodb database data mongoengine.connect("data") # Imports from txt file using pandas catalog_df = pandas.read_csv(catalog_infile, sep='|', header=0, index_col=False, keep_default_na=False) print("Reading plants catalog file from: ") print(catalog_infile) print("Adding images of plants to database: ") # For each plant in the catalog for row, plant in catalog_df.iterrows(): try: image_filestring = os.sep.join(catalog_filedir.split(os.sep)[:-2]) + os.sep + "images" + os.sep \ + plant["species"].replace(" ", "_") + ".jpg" if os.path.isfile(image_filestring): plant_doc = plant_types.objects(species=plant["species"]) plant_doc.update(set__image=base64.b64encode(open(image_filestring, 'rb').read()).decode('ascii')) except: # plant_images_b64.append("") print("Failed for " + plant["species"]) # Adds empty string to database plant_doc = plant_types.objects(species=plant["species"]) plant_doc.update(set__image="")
def generate_user_tasks(self, usr): """ Generate task lists for a user. """ spring_mulch_month = 3 spring_mulch_day = 20 fall_mulch_month = 9 fall_mulch_day = 22 min_temp_today = None min_temp_tomorrow = None watering_tasks = [] cold_weather_tasks = [] fertilize = (date.today().day == 1) mulch = ((date.today().month == spring_mulch_month and date.today().day == spring_mulch_day) or (date.today().month == fall_mulch_month and date.today().day == fall_mulch_day)) for garden_id in usr.gardens: garden_weather_data = util.calc_garden_plants_watering(garden_id) # in degrees C if "forecast_data" in garden_weather_data and garden_weather_data[ "forecast_data"][0] and garden_weather_data[ "forecast_data"][1]: min_temp_today = garden_weather_data["forecast_data"][0][ "min_temp"] min_temp_tomorrow = garden_weather_data["forecast_data"][1][ "min_temp"] garden = None with util.MongoConnect(): gardens_found = gardens.objects(id=garden_id) if gardens_found: garden = gardens_found[0] if garden: for plant_id in garden.plants: plant = None plant_type = None with util.MongoConnect(): plants_found = user_plants.objects(id=plant_id) if plants_found: plant = plants_found[0] plant_types_found = plant_types.objects( id=plant.plant_type_id) if plants_found and plant_types_found: plant_type = plant_types_found[0] if plant and plant_type: last_watered_date = plant.last_watered days_to_water = plant_type.days_to_water if days_to_water and (date.today() - last_watered_date ).days >= days_to_water: watering_tasks.append( WateringTask( plant_name=plant.name, plant_type=plant_type.name, plant_lat=plant.latitude, plant_long=plant.longitude, water_instr=plant_type. watering_description, )) if plant.outdoors and min_temp_today and min_temp_tomorrow and "zones" in plant_type.tags: min_zone = min(plant_type.tags["zones"]) if min_temp_today < util.zone_min_temp( min_zone ) or min_temp_tomorrow < util.zone_min_temp( min_zone): cold_weather_tasks.append( ColdWeatherTask( plant_name=plant.name, plant_type=plant_type.name, plant_lat=plant.latitude, plant_long=plant.longitude, plant_zone=min_zone, )) return fertilize, mulch, watering_tasks, cold_weather_tasks, min_temp_today, min_temp_tomorrow
def get_garden(garden_id: str): ''' Route which returns a json object with a single garden ''' if 'email' not in session: abort(403) if not is_valid_id(garden_id): abort(401) if request.method == 'DELETE': with util.MongoConnect(): user = users.objects(email=session['email']) if str(user) == '[]': abort(401) user = user[0] # need to do str(i) because user.gardens is a list of ObjectIdFields if garden_id in [str(i) for i in user.gardens]: try: garden = gardens.objects(id=garden_id) except Exception as e: abort(404) if str(garden) == '[]': abort(404) garden = garden[0] user.gardens.remove(garden.id) # delete all plants in the garden for plant_id in garden.plants: plant = user_plants.objects(id=plant_id) if str(plant) == '[]': continue plant = plant[0] plant_type = plant_types.objects(id=plant.plant_type_id) if str(plant_type) == '[]': plant.delete() continue plant_type = plant_type[0] plant.delete() garden.delete() user.save() else: abort(401) elif request.method == 'PUT': expected_fields = [ 'name', 'address', 'latitudetl', 'longitudetl', 'latitudebr', 'longitudebr' ] for field in expected_fields: if field not in request.json: abort(401) with util.MongoConnect(): user = users.objects(email=session['email']) if str(user) == '[]': abort(401) user = user[0] # need to do str(i) because user.gardens is a list of ObjectIdFields if garden_id in [str(i) for i in user.gardens]: garden = gardens.objects(id=garden_id) if str(garden) == '[]': abort(404) garden = garden[0] garden.name = request.json['name'] garden.address = request.json['address'] garden.topleft_lat = request.json['latitudetl'] garden.topleft_long = request.json['longitudetl'] garden.bottomright_lat = request.json['latitudebr'] garden.bottomright_long = request.json['longitudebr'] garden.save() else: abort(401) else: garden = {} with util.MongoConnect(): user = users.objects(email=session['email']) if str(user) == '[]': abort(401) user = user[0] if garden_id in [str(i) for i in user.gardens]: garden = gardens.objects(id=garden_id) if str(garden) == '[]': abort(404) garden = json.loads(garden[0].to_json()) return jsonify(garden) return "", 200
def edit_plant_in_garden(garden_id: str, plant_id: str): expected_fields = [ 'plant_type_id', 'latitude', 'longitude', 'light_duration', 'light_intensity', 'last_watered', 'name', 'price', 'outdoors' ] if 'email' not in session: abort(403) if not is_valid_id(garden_id): abort(401) if not is_valid_id(plant_id): abort(401) # check that the right info was provided, else 401 for field in expected_fields: if field not in request.json: # Don't reject if still using the old set of expected fields if field in ['light_duration', 'light_intensity', 'price']: request.json[field] = 0 elif field == 'name': request.json['name'] = '' elif field == 'outdoors': request.json['outdoors'] = False else: abort(401) if not is_valid_id(request.json['plant_type_id']): abort(401) if request.json['last_watered'].find('.') == -1: request.json['last_watered'] = request.json['last_watered'] + '.000000' with util.MongoConnect(): user = users.objects(email=session['email']) if str(user) == '[]': abort(401) user = user[0] # need to do str(i) because user.gardens is a list of ObjectIdFields if garden_id in [str(i) for i in user.gardens]: try: garden = gardens.objects(id=garden_id) except Exception as e: abort(404) if str(garden) == '[]': abort(404) garden = garden[0] # same as above if plant_id not in [str(i) for i in garden.plants]: abort(401) try: plant_type = plant_types.objects( id=request.json['plant_type_id']) except Exception as e: abort(404) if str(plant_type) == '[]': abort(404) plant_type = plant_type[0] try: plant = user_plants.objects(id=plant_id) except Exception as e: abort(404) if str(plant) == '[]': abort(404) plant = plant[0] plant.plant_type_id = plant_type.id plant.latitude = request.json['latitude'] plant.longitude = request.json['longitude'] plant.light_duration = request.json['light_duration'] plant.light_intensity = request.json['light_intensity'] plant.name = request.json['name'] plant.price = request.json['price'] plant.outdoors = request.json['outdoors'] plant.last_watered = datetime.datetime.strptime( request.json['last_watered'], '%Y-%m-%d %H:%M:%S.%f') plant.save() else: abort(401) return "", 200
def calc_garden_plants_watering(garden_id): ''' Given user garden id, acquires weather predicted and historical data for that garden. Then calculates if the weather watered each plant enough ''' # Connects to the data database with MongoConnect(): # Gets the user's garden user_garden = gardens.objects(id=garden_id)[0] lat_avg = 0 long_avg = 0 # Calculates average latitude/longitude of garden lat_avg += user_garden["topleft_lat"] lat_avg += user_garden["bottomright_lat"] lat_avg /= 2 long_avg += user_garden["topleft_long"] long_avg += user_garden["bottomright_long"] long_avg /= 2 # Gets offset from UTC utc_offset = get_offset(lat_avg, long_avg) # Gets midnight local in UTC # tzf = TimezoneFinder() # tz = timezone(tzf.certain_timezone_at(lng=long_avg, lat=lat_avg)) today_date = date.today() today_midnight_utc = datetime.combine(today_date, time(0, 0)) # UTC Today at midnight in epoch time today_midnight_epoch_utc = mktime( today_midnight_utc.timetuple()) + utc_offset # Gets last 5 days historical data # by filtering out rain, snow, and min/max temp's hist_data = get_historical_data(lat_avg, long_avg, today_midnight_epoch_utc) # Gets next 5 days forecast (today + 4 days in future) daily data # by filtering out rain, snow, and min/max temps forecast_data = get_forecast_data(lat_avg, long_avg) # Iterates through each plant in the user's garden # And adds it to a dictionary stating if the weather watered the plant sufficiently plant_watering_data = [] for plant_id in user_garden.plants: plant = user_plants.objects(id=plant_id)[0] if plant.outdoors: plant_type = plant_types.objects(id=plant.plant_type_id)[0] rain_amt = 0 last_day_watered = -1 # Uses the min because we can only look back 5 days in the past # so max size of historical data array is size 5 (max index = 4) if "days_to_water" in plant_type: for i in range(min(plant_type["days_to_water"] - 1, 4), -1, -1): rain_amt += hist_data[i]["rain"] if hist_data[i]["rain"] > 0: last_day_watered = i + 1 # Appends that plant's rain amount to the plant_weather_data plant_watering_data.append({ "plant_id": str(plant_id), "rain_amt": rain_amt, "last_watered": None }) # If sufficiently watered then set last watered day # to last day it rained if rain_amt > 40 - 5 * plant_type["days_to_water"]: plant_watering_data[-1][ "last_watered"] = datetime.fromtimestamp( today_midnight_epoch_utc - last_day_watered * 86400) plant.last_watered = datetime.fromtimestamp( today_midnight_epoch_utc - last_day_watered * 86400) # Returns a dictionary of historical, forecast, and plant watering data return { "hist_data": hist_data, "forecast_data": forecast_data, "plant_watering_data": plant_watering_data }