-
Notifications
You must be signed in to change notification settings - Fork 0
/
joi.py
283 lines (242 loc) · 10.4 KB
/
joi.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
import re
from datetime import datetime
class joi:
__xor_conditions = []
__and_conditions = []
__gt_conditions = []
__lt_conditions = []
__geq_conditions = []
__leq_conditions = []
def __init__(self, joi):
self.joi = joi
def get_joi(self):
return self.joi
def get_keys(self):
return [i for i in self.joi.keys()]
""""
at xor condition we take argument as fields names
and we require than we want one of them to exists at the object
"""
def xor(self, *args):
self.__xor_conditions.append(args)
return self
""""
and is function that take arguments of fields and check the existence of them
at and condition all field mentioned should all exists
"""
def and_(self, *args):
self.__and_conditions.append(args)
return self
""""
gt is decorator that add greater than condition
gt variable means who has the bigger value
lw variable means who has the smaller value
"""
def gt(self, gt, lw):
self.__gt_conditions.append([gt, lw])
return self
""""
lt is a decorator that add less than condition
lw variable means who has the smaller value
gt variable means who has the greater value
"""
def lt(self, lt, gt):
self.__lt_conditions.append([lt, gt])
return self
""""
geq is a decorator that add equal and gt condition
gt variable means who has the gt or equal value
lw variable means who has the smaller or equal the gt value
"""
def geq(self, gt, lw):
self.__geq_conditions.append([gt, lw])
return self
""""
leq is a decorator that add equal and lw condition
lw variable means who has the smaller or equal the lt value
gt variable means who has the gt or equal the lt value
"""
def leq(self, lw, gt):
self.__leq_conditions.append([lw, gt])
return self
def __isgt(self, value1, value2):
value1object = self.joi[value1]
value2object = self.joi[value2]
if value1object.get("format", False) == "date" and value2object.get("format", False) == "date":
date1 = datetime.strptime(value1, value1["format"])
date2 = datetime.strptime(value2, value2["format"])
return date1 > date2
else:
return value1 > value2
def __is_lt(self, value1, value2):
return value1 < value2
def __is_geq(self, value1, value2):
return value1 >= value2
def __is_leq(self, value1, value2):
return value1 <= value2
def __check_string_properties(self, form, key, form_keys) -> bool:
field_keys = [i for i in self.joi[key].keys()]
properties_exists = "minlength" in field_keys or "maxlength" in field_keys
return (key in form_keys and isinstance(form[key], self.joi[key]["type"])
and type(form[key]) in [str] and properties_exists)
def __check_max_and_min_for_numbers(self, form, key, form_keys) -> bool:
field_keys = [i for i in self.joi[key].keys()]
print(field_keys)
max_or_min_exists = "min" in field_keys or "max" in field_keys
print("exists:" + str(max_or_min_exists))
return (key in form_keys and isinstance(form[key], self.joi[key]["type"])
and type(form[key]) in [int, float] and max_or_min_exists)
def __check_regex(self, form, key, form_keys) -> bool:
field_keys = [i for i in self.joi[key].keys()]
print(field_keys)
is_regex_exists = "regex" in field_keys
return (key in form_keys and isinstance(form[key], self.joi[key]["type"])
and type(form[key]) in [str] and is_regex_exists)
def __check_date(self, form, key, form_keys) -> bool:
field_keys = [i for i in self.joi[key].keys()]
is_date_format = "format" in field_keys and "dateformat" in field_keys and self.joi[key]["format"] == "date"
return (key in form_keys and isinstance(form[key], self.joi[key]["type"])
and type(form[key]) in [str] and is_date_format)
def validate(self, form):
missing_fields = []
wrong_field = []
base_form_keys = self.get_keys()
form_keys = [i for i in form.keys()]
for key in base_form_keys:
print(self.__check_max_and_min_for_numbers(form, key, form_keys))
if key in form_keys and not isinstance(form[key], self.joi[key]["type"]):
wrong_field.append({
f"{key}": {
"message": "wrong type"
}
})
elif self.__check_max_and_min_for_numbers(form, key, form_keys):
print("there is max and min")
field_keys = [i for i in self.joi[key].keys()]
if "max" in field_keys and form[key] > self.joi[key]["max"]:
wrong_field.append({
f"{key}": {
"message": "wrong filed , the value is bigger than maximum"
}
})
elif "min" in field_keys and form[key] < self.joi[key]["min"]:
wrong_field.append({
f"{key}": {
"message": "wrong filed , the value is smaller than minimum"
}
})
elif self.__check_regex(form, key, form_keys):
regexp = self.joi[key]["regex"]
result_regex = re.match(regexp, form[key])
if not result_regex:
wrong_field.append({
f"{key}": {
"message": f"{key} is not a correct format"
}
})
elif self.__check_string_properties(form, key, form_keys):
field_keys = [i for i in self.joi[key].keys()]
if "maxlength" in field_keys and len(form[key]) > self.joi[key]["maxlength"]:
wrong_field.append({
f"{key}": {
"message": f"{key} is too long"
}
})
elif "minlength" in field_keys and len(form[key]) < self.joi[key]["minlength"]:
wrong_field.append({
f"{key}": {
"message": f"{key} is too short"
}
})
elif self.__check_date(form, key, form_keys):
field_keys = [i for i in self.joi[key].keys()]
date = None
try:
date = datetime.strptime(form[key], self.joi[key]["dateformat"])
except Exception as e:
wrong_field.append({
f"{key}": {
"message": f"{key} is not a correct format"
}
})
if date is not None and "min" in field_keys and isinstance(self.joi[key]["min"], datetime) and date < \
self.joi[key]["min"]:
wrong_field.append({
f"{key}": {
"message": f"{key} is lower than the minimum"
}
})
if date is not None and "max" in field_keys and isinstance(self.joi[key]["max"], datetime) and date > \
self.joi[key]["max"]:
wrong_field.append({
f"{key}": {
"message": f"{key} is higher than the maximum"
}
})
elif self.joi[key].get("required", False) and key not in form_keys:
missing_fields.append({
f"{key}": {
"message": "missing required field"
}
})
for key in form_keys:
if key not in base_form_keys:
wrong_field.append({
f"{key}": {
"message": "wrong key"
}
})
for i in self.__and_conditions:
missing_and_fields_number = 0
for j in i:
if j not in form_keys:
missing_and_fields_number += 1
if missing_and_fields_number > 0:
missing_fields.append({
f"{str(i)}": {
"message": "missing fields, should all of them exists"
}
})
for i in self.__xor_conditions:
number_of_existing_fields = 0
for j in i:
if j in form_keys:
print("is include")
number_of_existing_fields += 1
print(f"{str(i)}: {str(number_of_existing_fields)}")
if number_of_existing_fields == 0 or number_of_existing_fields > 1:
wrong_field.append({
f"{str(i)}": {
"message": "wrong xo condition, must one of them exists"
}
})
for i in self.__gt_conditions:
if not self.__isgt(form[i[0]], form[i[1]]):
wrong_field.append({
f"gt:{str(i)}": {
"message": f"{i[0]} must be $gt than {i[1]}"
}
})
for i in self.__leq_conditions:
if not self.__is_lt(form[i[0]], form[i[1]]):
wrong_field.append({
f"leq:{str(i)}": {
"message": f"{i[0]} must be $leq than {i[1]}"
}
})
for i in self.__geq_conditions:
if not self.__is_geq(form[i[0]], form[i[1]]):
wrong_field.append({
f"geq:{str(i)}": {
"message": f"{i[0]} must be $geq than {i[1]}"
}
})
for i in self.__leq_conditions:
if not self.__is_leq(form[i[0]], form[i[1]]):
wrong_field.append({
f"leq:{str(i)}": {
"message": f"{i[0]} must be $leq than {i[1]}"
}
})
form_accepted = (len(missing_fields) == 0 and len(wrong_field) == 0)
return dict(accepted=form_accepted, missing_fields=missing_fields, wrong_field=wrong_field)