-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodels.py
More file actions
3471 lines (2885 loc) · 134 KB
/
Copy pathmodels.py
File metadata and controls
3471 lines (2885 loc) · 134 KB
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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'''
Created on Sep 15, 2014
@author: beatricevaleri
'''
import fix_path
import types
from myexceptions import *
from datetime import datetime
from google.appengine.ext import ndb
from google.appengine.api.datastore_types import GeoPt
from google.appengine.api import search
from google.appengine.api import memcache
import logging
from __builtin__ import staticmethod
# for SQL
import MySQLdb
import os
import math
#server
INSTANCE_NAME = 'secure-gizmo-698:mysql56'
DATABASE = 'planfree'
DB_USER = 'root'
#local
DB_PASSWORD = 'root'
def get_db():
if os.environ.get('SERVER_SOFTWARE', '').startswith('Development'):
# This is a development server.
db = MySQLdb.connect(host='127.0.0.1', port=3306, db=DATABASE, user=DB_USER, passwd=DB_PASSWORD)
else:
# This is on App Engine. A password is not needed.
db = MySQLdb.connect(unix_socket='/cloudsql/' + INSTANCE_NAME, db=DATABASE, user=DB_USER)
return db
def code_generator(used_codes):
"""
Generates a random string of 5 characters
Input parameters:
- used_codes: list of codes already used, the new one should not be in the list
Return value: str of 5 characters
Exceptions: CodeException, if the generator is not able to find a unique string within 20 attempts
"""
import string
import random
res = ''.join(random.SystemRandom().choice(
string.ascii_uppercase + string.digits) for _ in range(5))
i = 1
while res in used_codes:
if i > 20:
raise CodeException(
"Not able to generate a new code in reasonable time.")
res = ''.join(random.SystemRandom().choice(
string.ascii_uppercase + string.digits) for _ in range(5))
i += 1
return res
class PFmodel(ndb.Model):
@staticmethod
def to_json(obj, obj_type, allowed, hidden):
"""
It transforms the object in a dict, that can be easily converted to a json.
Parameters:
- obj: the instance of PFmodel or subclass to convert.
- obj_type: the specific class of the object.
- allowed: list of strings indicating which properties are needed.
- hidden: list of strings indicating which properties are not needed.
Return value: dict representation of the object.
If a property appears in both allowed and hidden, hidden wins and the property is not returned.
'key' is converted to urlsafe.
Exceptions: TypeError if the input parameters are not of the correct type
"""
if not isinstance(obj_type, types.ClassType) and not isinstance(obj, obj_type):
raise TypeError('obj_type must be a ClassType and obj must be an object of that class!')
if allowed is not None and not isinstance(allowed, list) and not all(isinstance(n, (str, unicode)) for n in allowed):
raise TypeError('allowed must be a list of strings, i.e. a list of names of properties for the object.')
if hidden is not None and not isinstance(hidden, list) and not all(isinstance(n, (str, unicode)) for n in hidden):
raise TypeError('hidden must be a list of strings, i.e. a list of names of properties for the object.')
res = obj.to_dict()
if obj.key is not None:
res['key'] = obj.key.urlsafe()
for k in res.keys():
if hidden is not None and len(hidden) > 0 and k in hidden:
del res[k]
elif allowed is not None and len(allowed) > 0 and k not in allowed:
del res[k]
for k in res.keys():
if res[k] is None:
del res[k]
return res
@staticmethod
def from_json(json_dict):
"""
It converts a dict coming from a json string into an object.
Parameters:
- json_dict: the dict containing the information received from a json string.
Return value: object of this class.
It is empty in the parent class.
"""
pass
@staticmethod
def make_key(obj_id, url_encoded, class_name):
"""
It creates a Key object for this class, with id obj_id.
Parameters:
- obj_id: the object id. It can be a string or a long.
- url_encoded: the object key as url-encoded string.
- class_name: the name of the class representing the object type;
it is used in combination with obj_id, while url_encoded alrady contain such information.
If obj_id is set, the key is generated fom the id, otherwise url_encoded is used to get the key.
Return value: ndb.Key.
Exceptions: TypeError if input parameters are of the wrong type
"""
if obj_id is not None:
if not isinstance(obj_id, (str, unicode, long)):
raise TypeError(
"obj_id must be str, unicode or long, instead it is " + str(type(obj_id)))
else:
if class_name is None or not isinstance(class_name, str):
raise TypeError(
"class_name must be a str, instead it is " + str(type(class_name)))
return ndb.Key(class_name, obj_id)
elif url_encoded is not None:
if not isinstance(url_encoded, (str, unicode)):
raise TypeError(
"url_encoded must be str or unicode, instead it is " + str(type(url_encoded)))
else:
return ndb.Key(urlsafe=url_encoded)
else:
# obj_id and url_encoded are not set! TODO: raise exception?
return None
@staticmethod
def is_valid(obj):
"""
It validates the object data.
Parameters:
- obj: the object to be validated
Return value: (boolean, list of strings representing invalid properties).
It is empty in the parent class.
"""
pass
@staticmethod
def store(obj, key):
"""
It creates or updates the object, according to presence and validity of the key.
Parameters:
- obj: it containes the object data to store
- key: if it is not set, this function creates a new object; if it is set, this function updates the object.
Return value: object of this class
It is empty in the parent class.
"""
pass
@staticmethod
def get_by_key(key):
"""
It retrieves the object by key.
Parameters:
- key: the ndb key identifying the object to retrieve.
Return value: object of this class.
Exceptions: TypeError id the input parameter is of the wrong type
"""
if not isinstance(key, ndb.Key):
raise TypeError(
"key must be ndb.Key, instead it is " + str(type(key)))
return key.get()
@staticmethod
def get_list(filters):
"""
It retrieves a list of objects satisfying the characteristics described in filter.
Parameters:
- filters: a dict containing the characteristics the objects in the resulting list should have.
Return value: list of objects of this class.
It is empty in the parent class.
"""
pass
@staticmethod
def delete(key):
"""
It deletes the object referenced by the key.
Parameters:
- key: the ndb.Key that identifies the object to delete (both kind and id needed).
Return value: boolean.
It returns True if the object has been deleted, False if delete is not allowed.
Exceptions: TypeError if the input parameter is of the wrong type
"""
if not isinstance(key, ndb.Key):
raise TypeError(
"key must be ndb.Key, instead it is " + str(type(key)))
delete_allowed = ['Place', 'ClusterRating', 'Rating']
kind = key.kind()
if kind in delete_allowed:
key.delete()
return True
return False
class Address(PFmodel):
"""
Represents an address.
It can be partially defined, but if a property is defined also all the more generic ones have to be set.
For example, if city is set, also province, state and country should be set. Only state can be empty,
since some countries are not divided in states.
"""
street = ndb.StringProperty()
city = ndb.StringProperty()
province = ndb.StringProperty()
state = ndb.StringProperty()
country = ndb.StringProperty()
location = ndb.GeoPtProperty()
@staticmethod
def to_json(obj, allowed, hidden):
"""
It transforms the Address in a dict, that can be easily converted to a json.
Parameters:
- obj: the instance of Address to convert.
- allowed: list of strings indicating which properties are needed.
- hidden: list of strings indicating which properties are not needed.
Return value: dict representation of the object.
If a property appears in both allowed and hidden, hidden wins and the property is not returned.
'key' is converted to urlsafe.
Exceptions: TypeError if parameters are of the wrong type (from PFmodel.to_json())
"""
res = PFmodel.to_json(obj, Address, allowed, hidden)
if res is not None and 'location' in res.keys():
res['lat'] = obj.location.lat
res['lon'] = obj.location.lon
del res['location']
return res
@staticmethod
def from_json(json_dict):
"""
It converts a dict coming from a json string into a Address.
Parameters:
- json_dict: the dict containing the information received from a json string.
Return value: Address or None if the input dict contains wrong data.
Exceptions: TypeError if parameter is of the wrong type;
Exceptions raised from res.populate()
"""
if not isinstance(json_dict, dict):
raise TypeError(
"json_dict must be dict, instead it is " + str(type(json_dict)))
if 'lat' in json_dict.keys() and 'lon' in json_dict.keys():
lat = float(json_dict['lat'])
lon = float(json_dict['lon'])
json_dict['location'] = GeoPt(
lat, lon)
del json_dict['lat']
del json_dict['lon']
res = Address()
res.populate(**json_dict)
return res
@staticmethod
def make_key(obj_id, url_encoded):
"""
It creates a Key object for this class, with id obj_id.
Parameters:
- obj_id: the object id. It can be a string or a long.
- url_encoded: the object key as url-encoded string.
If obj_id is set, the key is generated fom the id, otherwise url_encoded is used to get the key.
Return value: ndb.Key.
Exceptions: TypeError if input parameters are of the wrong type (from PFmodel.make_key)
"""
return PFmodel.make_key(obj_id, url_encoded, 'Address')
@staticmethod
def is_valid(obj):
"""
It validates the object data.
Parameters:
- obj: the object to be validated
Return value: (boolean, list of strings representing invalid properties).
A result of False, [] means that the object type is wrong, so all properties are wrong.
"""
wrong_list = []
if not isinstance(obj, Address):
return False, wrong_list
# if obj.street is not None and not isinstance(obj.street, (str, unicode)):
# wrong_list.append("street")
# if obj.city is not None and not isinstance(obj.city, (str, unicode)):
# wrong_list.append("city")
# if obj.province is not None and not isinstance(obj.province, (str, unicode)):
# wrong_list.append("province")
# if obj.state is not None and not isinstance(obj.state, (str, unicode)):
# wrong_list.append("state")
# if obj.country is not None and not isinstance(obj.country, (str, unicode)):
# wrong_list.append("country")
# if obj.location is not None and not isinstance(obj.location, GeoPt):
# wrong_list.append("location")
if obj.city is not None and (obj.province is None or obj.country is None):
# if the city is set, also province and country must be set, to
# distinguish between cities with the same name
wrong_list.append("province")
wrong_list.append('country')
if len(wrong_list) > 0:
return False, wrong_list
else:
return True, None
# Address is only present into other entities, it is never created alone
# @staticmethod
# def store(obj, key):
# """
# It creates or updates the address, according to presence and validity of the key.
#
# Parameters:
# - obj: the address to store
# - key: if it is not set, this function creates a new object; if it is set, this function updates the object.
#
# For updates, only allowed attributes are updated, while the others are ignored.
#
# Return value: Address
# Exceptions: TypeError if the input parameters are of the wrong type;
# ValueError if the input obj has wrong values;
# InvalidKeyException if the key does not correspond to a valid Address;
#
# """
# valid, wrong_list = Address.is_valid(obj)
# if not valid:
# logging.error("Invalid input data: " + str(wrong_list))
# if len(wrong_list)<1:
# raise TypeError('obj must be Address, instead it is ' + str(type(obj)))
# else :
# raise ValueError('Wrong values for the following attributes: ' + str(wrong_list))
#
# if key is not None:
# if not( isinstance(key, ndb.Key) and key.kind().find('Address') > -1):
# raise TypeError('key must be a valid key for an Address, it is ' + str(key))
# key is valid --> update
# db_obj = key.get()
# if db_obj is None:
# logging.info("Updating address - NOT FOUND " + str(key))
# raise InvalidKeyException('key does not correspond to any Address')
#
# objdict = obj.to_dict()
#
# NOT_ALLOWED = ['id', 'key']
#
# for key, value in objdict.iteritems():
# if key in NOT_ALLOWED:
# continue
# if hasattr(db_obj, key):
# try:
# setattr(db_obj, key, value)
# except ValueError:
# continue
#
# else:
# continue
#
# db_obj.put()
# return db_obj
#
# else:
# key is not valid --> create
# obj.put()
# return obj
class Hours(PFmodel):
"""Information about the weekly hours of a place."""
# CANNOT USE REPEATED = TRUE because Hours is already repeated in its
# container
# weekday 1 = monday, in line with ISO format
weekday = ndb.StringProperty(
choices=['1', '2', '3', '4', '5', '6', '7'])
open1 = ndb.TimeProperty()
close1 = ndb.TimeProperty()
open2 = ndb.TimeProperty()
close2 = ndb.TimeProperty()
@staticmethod
def to_json(obj, allowed, hidden):
"""
It transforms the Hours in a dict, that can be easily converted to a json.
Parameters:
- obj: the instance of Hours to convert.
- allowed: list of strings indicating which properties are needed.
- hidden: list of strings indicating which properties are not needed.
Return value: dict representation of the object.
If a property appears in both allowed and hidden, hidden wins and the property is not returned.
'key' is converted to urlsafe.
Exceptions: TypeError if parameters are of the wrong type (from PFmodel.to_json())
"""
res = PFmodel.to_json(obj, Hours, allowed, hidden)
if 'open1' in res.keys():
res['open1'] = res['open1'].strftime('%H:%M')
if 'close1' in res.keys():
res['close1'] = res['close1'].strftime('%H:%M')
if 'open2' in res.keys():
res['open2'] = res['open2'].strftime('%H:%M')
if 'close2' in res.keys():
res['close2'] = res['close2'].strftime('%H:%M')
return res
@staticmethod
def from_json(json_dict):
"""
It converts a dict coming from a json string into a Hours object.
Parameters:
- json_dict: the dict containing the information received from a json string.
Return value: Hours or None if the input dict contains wrong data.
Exceptions: TypeError if parameter is of the wrong type, Exceptions raised from res.populate()
"""
if not isinstance(json_dict, dict):
raise TypeError(
"json_dict must be dict, instead it is " + str(type(json_dict)))
res = Hours()
if 'open1' in json_dict.keys():
try:
json_dict['open1'] = datetime.strptime(
json_dict['open1'], '%H:%M').time()
except ValueError:
del json_dict['open1']
if 'close1' in json_dict.keys():
try:
json_dict['close1'] = datetime.strptime(
json_dict['close1'], '%H:%M').time()
except ValueError:
del json_dict['close1']
if 'open2' in json_dict.keys():
try:
json_dict['open2'] = datetime.strptime(
json_dict['open2'], '%H:%M').time()
except ValueError:
del json_dict['open2']
if 'close2' in json_dict.keys():
try:
json_dict['close2'] = datetime.strptime(
json_dict['close2'], '%H:%M').time()
except ValueError:
del json_dict['close2']
res.populate(**json_dict)
return res
@staticmethod
def make_key(obj_id, url_encoded):
"""
It creates a Key object for this class, with id obj_id.
Parameters:
- obj_id: the object id. It can be a string or a long.
- url_encoded: the object key as url-encoded string.
If obj_id is set, the key is generated fom the id, otherwise url_encoded is used to get the key.
Return value: ndb.Key.
Exceptions: TypeError if input parameters are of the wrong type (from PFmodel.make_key)
"""
return PFmodel.make_key(obj_id, url_encoded, 'Hours')
@staticmethod
def is_valid(obj):
"""
It validates the object data.
Parameters:
- obj: the object to be validated
Return value: (boolean, list of strings representing invalid properties).
A result of False, [] means that the object type is wrong, so all properties are wrong.
"""
wrong_list = []
if not isinstance(obj, Hours):
return False, wrong_list
# check that open1, close1, open2 and close2 dfines two consecutive
# perods in a day
if obj.open1 is None:
# if the first time interval does not start, it does not end and
# the second time interval cannot be defined
if obj.close1 is not None:
wrong_list.appen('close1')
if obj.open2 is not None:
wrong_list.appen('open2')
if obj.close2 is not None:
wrong_list.appen('close2')
else:
# open1 is set
if obj.close1 is None:
wrong_list.appen('close1')
else:
if obj.close1 < obj.open1:
# close1 is defined and is before open1
wrong_list.appen('close1')
if obj.open2 is not None:
if obj.close2 is None:
wrong_list.appen('close2')
else:
if obj.close2 < obj.open2:
# close2 is defined and is before open2
wrong_list.appen('close2')
if obj.open2 < obj.close1:
# the second time interval starts before the end of the
# first one
wrong_list.appen('open2')
if len(wrong_list) > 0:
return False, wrong_list
else:
return True, None
# Hours is only used within other entities, it is never stored separately.
# @staticmethod
# def store(obj, key):
# """
# It creates or updates the Hours object, according to presence and validity of the key.
#
# Parameters:
# - obj: the Hours object to store
# - key: if it is not set, this function creates a new object; if it is set, this function updates the object.
#
# For updates, only allowed attributes are updated, while the others are ignored.
#
# Return value: Hours
# Exceptions: TypeError if the input parameters are of the wrong type;
# ValueError if the input obj has wrong values;
# InvalidKeyException if the key does not correspond to a valid Hours;
# """
# valid, wrong_list = Hours.is_valid(obj)
# if not valid:
# logging.error("Invalid input data: " + str(wrong_list))
# if len(wrong_list) < 1:
# raise TypeError(
# 'obj must be Hours, instead it is ' + str(type(obj)))
# else:
# raise ValueError(
# 'Wrong values for the following attributes: ' + str(wrong_list))
#
# if key is not None:
# if not(isinstance(key, ndb.Key) and key.kind().find('Hours') > -1):
# raise TypeError('key must be a valid key for an Hours, it is ' + str(key))
#
# # key is valid --> update
# db_obj = key.get()
# if db_obj is None:
# logging.info("Updating hours - NOT FOUND " + str(key))
# raise InvalidKeyException('key does not correspond to a valid Hours')
#
# objdict = obj.to_dict()
#
# NOT_ALLOWED = ['id', 'key']
#
# for key, value in objdict.iteritems():
# if key in NOT_ALLOWED:
# continue
# if hasattr(db_obj, key):
# try:
# setattr(db_obj, key, value)
# except:
# continue
#
# else:
# continue
#
# db_obj.put()
# return db_obj
#
# else:
# # key is not valid --> create
# obj.put()
# return obj
class Settings(PFmodel):
"""
Collects user's settings for recommendations.
"""
purpose = ndb.StringProperty(choices=[
"dinner with tourists", "romantic dinner", "dinner with friends", "best price/quality ratio"], indexed=False)
max_distance = ndb.IntegerProperty(indexed=False)
num_places = ndb.IntegerProperty(indexed=False)
created = ndb.DateTimeProperty(auto_now_add=True)
updated = ndb.DateTimeProperty(auto_now=True)
@staticmethod
def to_json(obj):
"""
It transforms the object in a dict, that can be easily converted to a json.
Parameters:
- obj: the instance of Settings to convert.
Return value: dict representation of the object containing all its fields.
If a property appears in both allowed and hidden, hidden wins and the property is not returned.
'key' is converted to urlsafe.
Exceptions: TypeError if parameters are of the wrong type (from PFmodel.to_json())
"""
res = PFmodel.to_json(
obj, Settings, ['purpose', 'max_distance', 'num_places'], ['created', 'updated'])
return res
@staticmethod
def from_json(json_dict):
"""
It converts a dict coming from a json string into an object.
Parameters:
- json_dict: the dict containing the information received from a json string.
Return value: object of this class.
Exceptions: TypeError if parameter is of the wrong type, Exceptions raised from res.populate()
"""
if not isinstance(json_dict, dict):
raise TypeError(
"json_dict must be dict, instead it is " + str(type(json_dict)))
res = Settings()
res.populate(**json_dict)
return res
@staticmethod
def make_key(obj_id, url_encoded, class_name):
"""
It creates a Key object for this class, with id obj_id.
Parameters:
- obj_id: the object id. It can be a string or a long.
- url_encoded: the object key as url-encoded string.
- class_name: the name of the class representing the object type;
it is used in combination with obj_id, while url_encoded alrady contain such information.
If obj_id is set, the key is generated fom the id, otherwise url_encoded is used to get the key.
Return value: ndb.Key.
Exceptions: TypeError if input parameters are of the wrong type (from PFmodel.make_key)
"""
return PFmodel.make_key(obj_id, url_encoded, 'Settings')
@staticmethod
def is_valid(obj):
"""
It validates the object data.
Parameters:
- obj: the object to be validated
Return value: (boolean, list of strings representing invalid properties).
"""
wrong_list = []
if not isinstance(obj, Settings):
return False, wrong_list
if obj.max_distance is not None and obj.max_distance < 100:
wrong_list.append('max_distance')
if obj.num_places is not None and obj.num_places < 1:
wrong_list.append('num_places')
if len(wrong_list) > 0:
return False, wrong_list
else:
return True, None
# Settings is only present into other entities, it is never created alone
# @staticmethod
# def store(obj, key):
# """
# It creates or updates the settings, according to presence and validity of the key.
#
# Parameters:
# - obj: the settings to store
# - key: if it is not set, this function creates a new object; if it is set, this function updates the object.
#
# For updates, only allowed attributes are updated, while the others are ignored.
#
# Return value: Settings
# Exceptions: TypeError if the input parameters are of the wrong type;
# ValueError if the input obj has wrong values;
# InvalidKeyException if the key does not correspond to a valid Settings;
# """
# valid, wrong_list = Settings.is_valid(obj)
# if not valid:
# logging.error("Invalid input data: " + str(wrong_list))
# if len(wrong_list)<1:
# raise TypeError('obj must be Settings, instead it is ' + str(type(obj)))
# else :
# raise ValueError('Wrong values for the following attributes: ' + str(wrong_list))
#
# if key is not None:
# if not( isinstance(key, ndb.Key) and key.kind().find('Settings') > -1):
# raise TypeError('key must be a valid key for Settings, it is ' + str(key))
# # key is valid --> update
# db_obj = key.get()
# if db_obj is None:
# logging.info("Updating settings - NOT FOUND " + str(key))
# raise InvalidKeyException('key does not correspond to any Settings')
#
# objdict = obj.to_dict()
#
# NOT_ALLOWED = ['id', 'key']
#
# for key, value in objdict.iteritems():
# if key in NOT_ALLOWED:
# continue
# if hasattr(db_obj, key):
# try:
# setattr(db_obj, key, value)
# except:
# continue
#
# else:
# continue
#
# db_obj.put()
#
# else:
# # key is not valid --> create
# obj.put()
# return obj
class PFuser(PFmodel):
"""
Represents a user, with full profile
"""
user_id = ndb.StringProperty(required=True)
fb_user_id = ndb.StringProperty()
fb_access_token = ndb.StringProperty()
google_user_id = ndb.StringProperty()
google_access_token = ndb.StringProperty()
created = ndb.DateTimeProperty(auto_now_add=True)
updated = ndb.DateTimeProperty(auto_now=True)
first_name = ndb.StringProperty()
last_name = ndb.StringProperty()
full_name = ndb.StringProperty()
email = ndb.StringProperty(required=True)
locale = ndb.StringProperty()
profile = ndb.StringProperty(indexed=False)
picture = ndb.TextProperty(indexed=False)
age = ndb.StringProperty(indexed=False)
gender = ndb.StringProperty(indexed=False)
# home can be a pratially-defined address, with street and location as optional,
# while the city should be fully defined (not only city name, but also at
# least country is needed)
home = ndb.StructuredProperty(Address)
# list of cities visited in the last year, address is only partialluy
# defined, as before
visited_city = ndb.StructuredProperty(Address, repeated=True)
settings = ndb.StructuredProperty(Settings, indexed=False)
role = ndb.StringProperty()
cluster_id = ndb.StringProperty()
# rating = ndb.StructuredProperty(Rating, repeated=True)
# first_login = ndb.DateTimeProperty(auto_now_add=True)
# ext_id_facebook = ndb.StringProperty()
# ext_id_google = ndb.StringProperty()
# def add_or_get_user(user_response, access_token, provider, update=False):
@staticmethod
def login(user_response, access_token, provider, update=False):
'''
Adds the user, if new, and returns it, else just returns the user.
'''
# update is never used!
status = []
if provider == 'facebook':
user_query = PFuser.query(
ndb.OR(
PFuser.fb_user_id == user_response['id'],
PFuser.email == user_response['email'].lower()
)
)
user = user_query.get()
if user and user.fb_user_id:
if user.first_name != user_response['first_name']:
user.first_name = user_response['first_name']
if user.last_name != user_response['last_name']:
user.last_name = user_response['last_name']
if user.full_name != user_response['name']:
user.full_name = user_response['name']
if user.locale != user_response['locale']:
user.locale = user_response['locale']
picture = 'http://graph.facebook.com/{0}/picture'.format(
user_response['id'])
if user.picture != picture:
user.picture = picture
user.fb_access_token = access_token
user.put()
return user, ['FB_user_exists']
if not user:
if 'id' not in user_response:
logging.error('Missing user id!!')
return None, None
user_id = "FB_" + user_response['id']
key = ndb.Key('PFuser', user_id)
user = PFuser(key=key)
user.user_id = user_id
user.first_name = user_response['first_name']
user.last_name = user_response['last_name']
user.email = user_response['email']
user.full_name = user_response['name']
user.locale = user_response['locale']
user.picture = 'http://graph.facebook.com/{0}/picture'.format(
user_response['id'])
status.append('user_added')
else:
status.append('FB_user_data_added')
# add FB details
user.fb_user_id = user_response['id']
user.profile = user_response['link']
if user_response['gender'] and (user_response['gender'][0] == 'f' or user_response['gender'][0] == 'F'):
user.gender = 'F'
elif user_response['gender'] and (user_response['gender'][0] == 'm' or user_response['gender'][0] == 'M'):
user.gender = 'M'
user.fb_access_token = access_token
elif provider == 'google':
user_query = PFuser.query(ndb.OR(
PFuser.fb_user_id == user_response['id'],
PFuser.email == user_response['email'].lower()
))
user = user_query.get()
if user and user.google_user_id:
if user.first_name != user_response['given_name']:
user.first_name = user_response['given_name']
if user.last_name != user_response['family_name']:
user.last_name = user_response['family_name']
if user.full_name != user_response['name']:
user.full_name = user_response['name']
if user.locale != user_response['locale']:
user.locale = user_response['locale']
if user.picture != user_response['picture']:
user.picture = user_response['picture']
user.google_access_token = access_token
user.put()
return user, ['google_user_exists']
if not user:
user_id = "google_" + user_response['id']
key = ndb.Key('PFuser', user_id)
user = PFuser(key=key)
user.user_id = user_id
user.first_name = user_response['given_name']
user.last_name = user_response['family_name']
user.email = user_response['email']
user.full_name = user_response['name']
user.locale = user_response['locale']
user.picture = user_response['picture']
status.append('user_added')
else:
status.append('google_user_data_added')
# add Google details
user.google_user_id = user_response['id']
if 'profile' in user_response.keys():
user.profile = user_response['profile']
user.google_access_token = access_token
user.put()
return user, status
@staticmethod
def to_json(obj, allowed, hidden):
"""
It transforms the PFuser in a dict, that can be easily converted to a json.
Parameters:
- obj: the instance of PFuser to convert.
- allowed: list of strings indicating which properties are needed.
- hidden: list of strings indicating which properties are not needed.
Return value: dict representation of the object.
If a property appears in both allowed and hidden, hidden wins and the property is not returned.
'key' is converted to urlsafe.
Exceptions: TypeError if parameters are of the wrong type (from PFmodel.to_json())
"""
# add to hidden those properties that we never want to show
hidden.extend(('fb_user_id', 'fb_access_token', 'google_user_id',
'google_access_token', 'created', 'updated', 'email'))
res = PFmodel.to_json(obj, PFuser, allowed, hidden)
if 'home' in res.keys():
res['home'] = Address.to_json(
Address.from_json(res['home']), allowed, hidden)
if 'visited_city' in res.keys():
for city in res['visited_city']:
city = Address.to_json(
Address.from_json(city), allowed, hidden)
if 'settings' in res.keys():
res['settings'] = Settings.to_json(
Settings.from_json(res['settings']))
return res
@staticmethod
def from_json(json_dict):
"""
It converts a dict coming from a json string into a PFuser.