-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathPlantRepository.py
105 lines (97 loc) · 3.4 KB
/
PlantRepository.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
from database.Plant import Plant as PlantDB
from models.Plant import Plant
from models.Disease import Disease
from repository.base import Base
from sqlalchemy import and_
class PlantRepository(Base):
"""
Plant repository, dedicated to realize all functions related to plants
"""
def __init__(self,
dbuser="",
dbpass="",
dbhost="",
port="",
dbname=""):
super().__init__(dbuser, dbpass, dbhost, port, dbname)
def create(self, plant=Plant()):
"""
(Plant) -> (Plant)
"""
plantDB = PlantDB(plant=plant)
session = self.session_factory()
session.add(plantDB)
session.flush()
session.refresh(plantDB)
session.commit()
return Plant(plantDB.id,
plantDB.scientificName,
plantDB.commonName)
def update(self, plant=Plant()):
"""
(Plant) -> (Plant)
"""
session = self.session_factory()
plantDB = session.query(PlantDB).filter_by(id=plant.id).first()
dic = {}
if (plantDB.scientificName != plant.scientificName):
dic['scientificName'] = plant.scientificName
if (plantDB.commonName != plant.commonName):
dic['commonName'] = plant.commonName
if (dic != {}):
session.query(PlantDB).filter_by(id=plant.id).update(dic)
session.commit()
session.flush()
session.refresh(plantDB)
return Plant(plantDB.id,
plantDB.scientificName,
plantDB.commonName)
def delete(self, plant=Plant()):
"""
(Plant) -> (Boolean)
"""
status = False
session = self.session_factory()
plantDB = session.query(PlantDB).filter_by(id=plant.id).first()
session.delete(plantDB)
session.commit()
session.flush()
if (not session.query(PlantDB).filter_by(id=plantDB.id).count()):
status = True
session.close()
return status
def search(self, plant=Plant(), pageSize=10, offset=0):
"""
(Plant, pageSize, offset) -> {'total': int, 'content':[Plant]}
"""
session = self.session_factory()
query = session.query(PlantDB).filter(and_(
PlantDB.scientificName.like(
'%'+plant.scientificName+'%'),
PlantDB.commonName.like('%'+plant.commonName+'%')))
content = query.slice(offset, pageSize).all()
total = query.count()
plants = []
for plantDB in content:
plants.append(Plant(
plantDB.id,
plantDB.scientificName,
plantDB.commonName))
dic = {'total': total, 'content': plants}
return dic
def searchByID(self, plantId):
"""
(Int) -> (Plant)
"""
session = self.session_factory()
plantDB = session.query(PlantDB).get(plantId)
diseases = []
for disease in plantDB.diseases:
diseases.append(Disease(
id=disease.id,
scientificName=disease.scientificName,
commonName=disease.commonName))
return Plant(plantDB.id,
plantDB.scientificName,
plantDB.commonName,
diseases)