示例#1
0
def create_new_plant():
    body = request.get_json()

    name = body["name"]
    scientific_name = body["scientific_name"]
    is_poisonous = body["is_poisonous"]
    primary_color = body["primary_color"]

    try:
        new_plant = Plant(name=name,
                          scientific_name=scientific_name,
                          is_poisonous=is_poisonous,
                          primary_color=primary_color)
        new_plant.insert()
        plants = Plant.query.order_by(Plant.id).all()
        current_plants = paginate_plants(request, plants)

        return jsonify({
            "success": True,
            "created": new_plant.id,
            "plants": current_plants,
            "total_plants": len(plants)
        })
    except:
        abort(422)
示例#2
0
 def create_plant():
     body = request.get_json()
     new_name = body.get('name', None)
     new_sientific_name = body.get('sientific_name', None)
     new_is_poisonuons = str_to_bool(body.get('is_poisonuons', None))
     new_primary_color = body.get('primary_color', None)
     search = body.get('search', None)
     try:
         if search:
             selection = Plant.query.filter(
                 Plant.name.ilike("{}".format(search))).all()
             search_plant = paginate_plants(request, selection)
             return jsonify({
                 'success': True,
                 'total plants': len(search_plant),
                 'plants': search_plant
             })
         else:
             new_plant = Plant(new_name, new_sientific_name,
                               new_is_poisonuons, new_primary_color)
             new_plant.Add()
             selection = Plant.query.all()
             current_plants = paginate_plants(request, selection)
             return jsonify({
                 'success': True,
                 'created': new_plant.id,
                 'plants': current_plants,
                 'total plants': len(selection)
             })
     except:
         abort(422)
示例#3
0
    def create_plant():
        body = request.get_json()
        new_name = body.get('name', None)
        new_scientific_name = body.get('scientific_name', None)
        new_is_poisonous = body.get('is_poisonous', None)
        new_primary_color = body.get('primary_color', None)
        new_state = body.get('state', None)
        search = body.get('search', None)

        #try:
        if search:
            plants = Plant.query.order_by(Plan.id).filter(
                Plan.name.ilike('%{}%'.format(search)))
            current_plants = paginate_plants(request, plants)
            return jsonify({
                'success': True,
                'plants': current_plants,
                'totals_plants': len(plants)
            })
        else:
            plant = Plant(name=new_name,
                          scientific_name=new_scientific_name,
                          is_poisonous=new_is_poisonous,
                          primary_color=new_primary_color,
                          state=new_state)
            plant.insert()
            plants = Plant.query.order_by(Plant.id).all()
            current_plants = paginate_plants(request, plants)

            return jsonify({
                'success': True,
                'created': plant.id,
                'plants': current_plants,
                'totals_plants': len(Plant.query.all())
            })
示例#4
0
    def create_plant():
        body = request.get_json()

        try:
            plant_name = body.get('name')
            plant_scientific = body.get('scientific_name')
            plant_color = body.get('primary_color')
            plant_poisonous = body.get('is_poisonous')

            new_plant = Plant(
                name = plant_name,
                scientific_name = plant_scientific,
                primay_color = plant_color,
                is_poisonous = plant_poisonous
            )

            new_plant.insert()

            return jsonify({
                'success': True,
                'id': new_plant.id
            })

        except:
            abort(422)
示例#5
0
    def create_test_plant(self, user_id):

        # create and insert new plant
        plant = Plant(user_id=user_id,
                      name=self.test_plant['name'],
                      latin_name=self.test_plant['latinName'],
                      description=self.test_plant['description'],
                      image_link=self.test_plant['imageLink'])
        plant.insert()

        return plant.id
示例#6
0
def plant():
	
	if request.method == 'GET':
		
		data = Plant.query.all()
		data = [r.as_dict() for r in data]
		return jsonify(data)

	else:
		# CREATE new substrate
		if not request.json:	
			abort(400)

		plant = Plant(
			description=request.json['description'],
			tank_id = request.json['tankID'],
			growbed_id = request.json['growbedID'],
			count = request.json['count'],
			units = request.json['units'],
			start_plant = request.json['start']
		)

		db.session.add(plant)
		db.session.commit()
		return jsonify(request.json), 201
示例#7
0
    def test_plantlist_add_plant(self):
        with self.client as c:
            with c.session_transaction() as sess:
                sess[CURR_USER_KEY] = self.testuser_id

            plant = Plant(
                trefle_id=1232,
                slug="plantus-slugs2",
                common_name="common plant2",
                scientific_name="plantus testus2",
                family="Plantaceae2",
                family_common_name="Plant Family2",
            )
            db.session.add(plant)
            db.session.commit()
            plantlist = PlantList.query.get(self.testplantlist_id)

            resp = c.post(
                f"/plantlists/{plantlist.id}/add/plant/{plant.id}",
                follow_redirects=True,
            )

            self.assertIn(plant, plantlist.plants)
            self.assertEqual(resp.status_code, 200)
            self.assertIn(
                f"Plant {plant.id} added to plantlist {plantlist.id} successfully.",
                str(resp.data),
            )
示例#8
0
    def new_plant_api(jwt):

        # get request body
        body = request.get_json()

        # get user table id from session or jwt
        if 'profile' in session:
            user_id = session['profile']['user_table_id']
        else:
            auth0_user_id = jwt['sub']
            user_id = User.query.filter_by(
                user_id=auth0_user_id).one_or_none().id

        # load plant form data
        name = body.get('name')
        latin_name = body.get('latinName')
        description = body.get('description')
        image_link = body.get('imageLink')

        # ensure all fields have data
        if ((name == "") or (latin_name == "") or (description == "")
                or (image_link == "")):
            abort(422)

        # create a new plant
        plant = Plant(user_id=user_id,
                      name=name,
                      latin_name=latin_name,
                      description=description,
                      image_link=image_link)

        try:
            # add plant to the database
            plant.insert()
        except Exception as e:
            print('ERROR: ', str(e))
            abort(422)

        # flash success message
        flash(f'Plant {name} successfully created!')

        return jsonify({'success': True, 'plant': plant.format()})
示例#9
0
def get_last_hour_plant_data():
    output = {
        'temperature': [],
        'humidity': [],
        'date': []
    }
    last_hour = Plant.select()\
        .order_by(Plant.date.asc())\
        .limit(6)
    for measure in last_hour:
        output['temperature'].append(float(measure.temperature))
        output['humidity'].append(float(measure.humidity))
        output['date'].append({
                'hour': datetime.datetime.fromtimestamp(measure.date / 1e3).hour - 1,
                'minute': datetime.datetime.fromtimestamp(measure.date / 1e3).minute
            })
    return output
示例#10
0
def get_plant_attributes(pref_common_name):

    # Populates and returns a plant object for the given (exact) pref_common_name
    # Arguments:
    # pref_common_name - preferred common name (string)
    # Returns - a Plant object populated with available attributes

    import lxml.etree as etree

    plant = Plant()

    for event, elem in etree.iterparse('/Users/Annie/Documents/Surrey/COMM002/XML/plantselector.xml',
                                       events=("start", "end")):

        if event == "start" and elem.tag == 'EntityDetailsItems':
            # Start of a plant - check if correct one then populate object with attributes
            if elem.attrib['PreferredCommonName'] == pref_common_name:
                plant = _populate_plant(elem)

        elif event == 'end':

            # Add any common names or synonyms to the plant object
            if (elem.tag == 'CommonName' or elem.tag == 'Synonyms') and plant.common_name == pref_common_name:

                    if elem.tag == 'CommonName' and elem.text:
                        plant.common_names.append(elem.text)
                    elif elem.tag == 'Synonyms' and elem.text:
                        plant.synonyms.append(elem.text)

            elif elem.tag == 'EntityDetailsItems':

                # Plant finished - delete extra synonym caused by extra XML tag, then break
                if plant.common_name == pref_common_name:
                    elem.clear()
                    if plant.synonyms:
                        del plant.synonyms[-1]
                        break

            # Clear element when finished with it to save memory
            elem.clear()

    return plant
def register(device_id):
    if not check_logged_in():
        return redirect(url_for('users.login'))
    device = Device.query.filter_by(id=device_id).first()
    form = PlantRegistrationForm(request.form)
    form.plant_type.choices = [(i.id, i.name) for i in PlantType.query.all()]
    if not device:
        flash("No device exists for this plant. Please use a device listed below.", category="danger")
        return redirect(url_for('plants.show_devices'))
    else:
        if request.method=="POST" and form.validate():
            newPlant = Plant(type=form.plant_type.data, level=form.level.data, location=form.location.data, mac_address=device.mac_address)
            if not Plant.query.filter_by(type=newPlant.type, level=newPlant.level, location=newPlant.location).all() and not Plant.query.filter_by(mac_address=newPlant.mac_address).all():
                device = Device.query.filter_by(id=device_id).one()
                device.registered = 1
                db.session.add(newPlant)
                db.session.commit()
                return redirect(url_for('main.home'))
            else:
                flash("A plant with those details already exists!", category="danger")
    return render_template("register_plant.html", form=form)
示例#12
0
           "watering": 3,
           "light": 4,
           "Difficulty": 1
           },
          {"image": "static/african-daisy.jpg",
           "species": "African Daisies",
           "watering": 3,
           "light": 4,
           "Difficulty": 2
           },
          {"image": "static/Aloe.jpg",
           "species": "Aloe Vera",
           "watering": 3,
           "light": 4,
           "Difficulty": 3
           },
           {"image": "static/Crocus.jpg",
           "species": "Crocus",
           "watering": 3,
           "light": 4,
           "Difficulty": 1
           },
          {"image": "static/Cyclamen.jpg",
           "species": "Cyclamen",
           "watering": 3,
           "light": 4,
           "Difficulty": 2
           }
          ]
Plant.insert_many(plants).execute()
示例#13
0
def plant_profile(plant_slug):
    """Shows specific plant profile page"""

    payload = {
        "token": TREFLE_API_KEY,
    }

    trefle_plant = requests.get(f"{API_BASE_URL}/plants/{plant_slug}",
                                params=payload).json()["data"]
    # Some responses have data nested in "main_species"
    if "main_species" in trefle_plant:
        main_species = trefle_plant["main_species"]
    else:
        main_species = trefle_plant

    form = AddPlantListForm()

    # If user is logged in, they can add this plant to their plantlists
    # Otherwise ask them to signup/login.
    if g.user:
        plant = Plant.query.filter(
            Plant.trefle_id == main_species["id"]).one_or_none()

        if request.method == "POST":
            if not plant:

                try:
                    plant = Plant.add(
                        trefle_id=main_species["id"],
                        slug=main_species["slug"],
                        common_name=main_species["common_name"],
                        scientific_name=main_species["scientific_name"],
                        family=main_species["family"],
                        family_common_name=main_species["family_common_name"],
                        image_url=main_species["image_url"],
                    )

                    db.session.commit()

                except IntegrityError:
                    flash("Failed to create plant.", "danger")
                    return render_template("plants/profile.html",
                                           main_species=main_species,
                                           form=form)

            # Append selected plantlists to the plant
            for plantlist in form.plantlists.data:
                plantlist = PlantList.query.get(plantlist)
                plant.plantlists.append(plantlist)

            db.session.commit()

        if plant:
            form.plantlists.choices = [(
                plantlist.id,
                plantlist.name,
            ) for plantlist in g.user.plantlists
                                       if plantlist not in plant.plantlists]

        else:
            form.plantlists.choices = [(
                plantlist.id,
                plantlist.name,
            ) for plantlist in g.user.plantlists]

    return render_template("plants/profile.html",
                           main_species=main_species,
                           form=form)
示例#14
0
def update_db():
    with open('/mnt/project/KnapsackSolver/data.txt') as f:
        reader = csv.reader(f)
        for fields in reader:
            if len(fields) == 0:
                continue
            #print(fields[10])
            if(Plant.objects.filter(serial_number = fields[0]).exists()):
                existing_plant = Plant.objects.filter(serial_number = fields[0])
                existing_plant.code = fields[1],
                existing_plant.classification = fields[2],
                existing_plant.plant_type = fields[3],
                existing_plant.genus = fields[4],
                existing_plant.species = fields[5],
                existing_plant.latin_name = fields[6],
                existing_plant.common_name = fields[7],
                existing_plant.min_spread = to_float(fields[10]),
                existing_plant.max_spread = to_float(fields[11]),
                existing_plant.min_height = to_float(fields[12]),
                existing_plant.max_height = to_float(fields[13]),
                existing_plant.min_roots = to_float(fields[14]),
                existing_plant.max_roots = to_float(fields[15]),
                existing_plant.blooms_in_jan = to_bool(fields[16]),
                existing_plant.blooms_in_feb = to_bool(fields[17]),
                existing_plant.blooms_in_mar = to_bool(fields[18]),
                existing_plant.blooms_in_apr = to_bool(fields[19]),
                existing_plant.blooms_in_may = to_bool(fields[20]),
                existing_plant.blooms_in_jun = to_bool(fields[21]),
                existing_plant.blooms_in_jul = to_bool(fields[22]),
                existing_plant.blooms_in_aug = to_bool(fields[23]),
                existing_plant.blooms_in_sep = to_bool(fields[24]),
                existing_plant.blooms_in_oct = to_bool(fields[25]),
                existing_plant.blooms_in_nov = to_bool(fields[26]),
                existing_plant.blooms_in_dec = to_bool(fields[27]),
                existing_plant.min_life_cycle = to_int(fields[28]),
                existing_plant.max_life_cycle = to_int(fields[29]),
                existing_plant.light = fields[30],
                existing_plant.soil_ph = to_float(fields[31]),
                existing_plant.salt_tolerance = fields[32],
                existing_plant.drought_tolerance = fields[33],
                existing_plant.irrigation = fields[34],
                existing_plant.UOM = fields[35],
                existing_plant.material_cost = to_float(fields[36]),
                existing_plant.planting_cost = to_float(fields[37]),
                existing_plant.maintainence_cost_during_execution = to_float(fields[38]),
                existing_plant.maintainence_cost_after_initial_handing_over = to_float(fields[39])
                existing_plant[0].save()
            else:
                new_plant = Plant(serial_number = fields[0],
                              code = fields[1],
                              classification = fields[2],
                              plant_type = fields[3],
                              genus = fields[4],
                              species = fields[5],
                              latin_name = fields[6],
                              common_name = fields[7],
                              min_spread = to_float(fields[10]),
                              max_spread = to_float(fields[11]),
                              min_height = to_float(fields[12]),
                              max_height = to_float(fields[13]),
                              min_roots = to_float(fields[14]),
                              max_roots = to_float(fields[15]),
                              blooms_in_jan = to_bool(fields[16]),
                              blooms_in_feb = to_bool(fields[17]),
                              blooms_in_mar = to_bool(fields[18]),
                              blooms_in_apr = to_bool(fields[19]),
                              blooms_in_may = to_bool(fields[20]),
                              blooms_in_jun = to_bool(fields[21]),
                              blooms_in_jul = to_bool(fields[22]),
                              blooms_in_aug = to_bool(fields[23]),
                              blooms_in_sep = to_bool(fields[24]),
                              blooms_in_oct = to_bool(fields[25]),
                              blooms_in_nov = to_bool(fields[26]),
                              blooms_in_dec = to_bool(fields[27]),
                              min_life_cycle = to_int(fields[28]),
                              max_life_cycle = to_int(fields[29]),
                              light = fields[30],
                              soil_ph = to_float(fields[31]),
                              salt_tolerance = fields[32],
                              drought_tolerance = fields[33],
                              irrigation = fields[34],
                              UOM = fields[35],
                              material_cost = to_float(fields[36]),
                              planting_cost = to_float(fields[37]),
                              maintainence_cost_during_execution = to_float(fields[38]),
                              maintainence_cost_after_initial_handing_over = to_float(fields[39])
                             )
                new_plant.save()
示例#15
0
def _populate_plant(elem):

    # Populates a Plant object with attributes from elem
    # Arguments:
    # elem - an XML element
    # plant - a Plant object
    # Returns - the populated Plant object

    plant = Plant()
    plant.name_num = elem.attrib['Name_Num']
    plant.pic = elem.attrib['PlantImagePath']
    plant.height = elem.attrib['Height']
    plant.hardiness = elem.attrib['Hardiness']
    plant.common_name = elem.attrib['PreferredCommonName']
    plant.spread = elem.attrib['Spread']
    plant.time_to_full_height = elem.attrib['TimeToFullHeight']
    plant.accepted_botanical_name = elem.attrib['AcceptedBotanicalName']
    plant.description = elem.attrib['EntityDescription']
    plant.soil_type = elem.attrib['SoilType']
    plant.foliage = elem.attrib['Foliage']
    plant.uses = elem.attrib['SuggestedPlantUses']
    plant.aspect = elem.attrib['Aspect']
    plant.flower_colour = elem.attrib['Flower']
    plant.moisture = elem.attrib['Moisture']
    plant.ph = elem.attrib['PH']
    plant.disease_resistance = elem.attrib['DiseaseResistance']
    plant.sunlight = elem.attrib['Sunlight']
    plant.exposure = elem.attrib['Exposure']
    plant.cultivation = elem.attrib['Cultivation']
    plant.low_maintenance = elem.attrib['LowMaintenance']

    return plant
示例#16
0
    def setUp(self):
        """Create test client, add sample data"""

        db.drop_all()
        db.create_all()

        self.client = app.test_client()

        self.testuser = User.signup(
            username="******", email="*****@*****.**", password="******",
        )
        self.testuser_id = 100
        self.testuser.id = self.testuser_id

        self.otheruser = User.signup(
            username="******", email="*****@*****.**", password="******",
        )

        self.otheruser_id = 200
        self.otheruser.id = self.otheruser_id

        self.testproject = Project(
            name="Project_Test", description="Project_Test test description.",
        )
        self.testproject_name = self.testproject.name
        self.testproject_id = 110
        self.testproject.id = self.testproject_id
        db.session.add(self.testproject)

        self.testplot = Plot(
            name="Plot_Test",
            width=5,
            length=10,
            description="Plot_Test test description.",
        )
        self.testplot_name = self.testplot.name
        self.testplot_id = 120
        self.testplot.id = self.testplot_id
        db.session.add(self.testplot)

        self.testplantlist = PlantList(
            name="Plantlist_Test", description="Plantlist_Test test description.",
        )
        self.testplantlist_name = self.testplantlist.name
        self.testplantlist_id = 130
        self.testplantlist.id = self.testplantlist_id
        db.session.add(self.testplantlist)

        self.testplant = Plant(
            trefle_id=1231,
            slug="plantus-slugs1",
            common_name="common plant1",
            scientific_name="plantus testus1",
            family="Plantaceae1",
            family_common_name="Plant Family1",
        )
        self.testplant_common_name = self.testplant.common_name
        self.testplant_id = 140
        self.testplant.id = self.testplant_id

        db.session.add(self.testplant)

        self.testsymbol = Symbol(
            symbol="<i class='symbol fas fa-seedling' style='color:#228B22;'></i>"
        )

        self.testsymbol_id = 1
        self.testsymbol.id = self.testsymbol_id
        db.session.add(self.testsymbol)

        # Connections
        self.testuser.projects.append(self.testproject)
        self.testuser.plots.append(self.testplot)
        self.testuser.plantlists.append(self.testplantlist)
        self.testproject.plots.append(self.testplot)
        self.testproject.plantlists.append(self.testplantlist)
        self.testplot.plantlists.append(self.testplantlist)
        self.testplantlist.plants.append(self.testplant)

        db.session.commit()
示例#17
0
def insert_plant_data(temperature, humidity):
    Plant.insert(temperature=temperature, humidity=humidity).execute()