This repository has been archived by the owner on Jan 23, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
conference.py
1293 lines (1111 loc) · 49.3 KB
/
conference.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
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
#!/usr/bin/env python
"""
conference.py -- Udacity conference server-side Python App Engine API;
uses Google Cloud Endpoints
$Id: conference.py,v 1.25 2014/05/24 23:42:19 wesc Exp wesc $
created by wesc on 2014 apr 21
"""
__author__ = 'wesc+api@google.com (Wesley Chun)'
from datetime import datetime
import endpoints
from protorpc import messages
from protorpc import message_types
from protorpc import remote
from google.appengine.api import memcache
from google.appengine.api import taskqueue
from google.appengine.ext import ndb
from models import ConflictException
from models import Profile
from models import ProfileMiniForm
from models import ProfileForm
from models import BooleanMessage
from models import Conference
from models import ConferenceForm
from models import ConferenceForms
from models import QueryForm
from models import QueryForms
from models import StringMessage
from models import SessionType
from models import Session
from models import SessionFormIn
from models import SessionFormOut
from models import SessionForms
from models import Speaker
from models import SpeakerFormIn
from models import SpeakerFormOut
from models import SpeakerForms
from utils import getUserId
from utils import get_current_user_id
from settings import WEB_CLIENT_ID
import logging
logging.getLogger().setLevel(logging.DEBUG)
EMAIL_SCOPE = endpoints.EMAIL_SCOPE
API_EXPLORER_CLIENT_ID = endpoints.API_EXPLORER_CLIENT_ID
MEMCACHE_ANNOUNCEMENTS_KEY = "RECENT_ANNOUNCEMENTS"
MEMCACHE_FEATUREDSPEAKER_KEY = "FEATURED_SPEAKER"
FEATUREDSPEAKER_TPL = (
'Speaker %s is our feature speaker, will appear in these sessions: %s')
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
DEFAULTS_CONF = {
"city": "Default City",
"maxAttendees": 0,
"seatsAvailable": 0,
"topics": [ "Default_Topic" ],
}
DEFAULTS_SESS = {
"durationInMins": 60,
"location": "Default Room",
"highlight": [ "Default_Highlight" ],
}
OPERATORS = {
'EQ': '=',
'GT': '>',
'GTEQ': '>=',
'LT': '<',
'LTEQ': '<=',
'NE': '!='
}
FIELDS_CONF = {
'CITY': 'city',
'TOPIC': 'topics',
'MONTH': 'month',
'MAX_ATTENDEES': 'maxAttendees',
}
FIELDS_SESS = {
'START_TIME': 'startTime',
'DURATION_IN_MINS': 'durationInMins',
'TYPE_OF_SESSION': 'typeOfSession',
'LOCATION': 'location',
}
CONF_GET_REQUEST = endpoints.ResourceContainer(
message_types.VoidMessage,
websafeConferenceKey=messages.StringField(1),
)
CONF_POST_REQUEST = endpoints.ResourceContainer(
ConferenceForm,
websafeConferenceKey=messages.StringField(1),
)
SESS_GET_REQUEST = endpoints.ResourceContainer(
message_types.VoidMessage,
websafeConferenceKey=messages.StringField(1),
sessionId=messages.StringField(2),
)
SESS_CREATE_REQUEST = endpoints.ResourceContainer(
SessionFormIn,
websafeConferenceKey=messages.StringField(1),
)
SESS_POST_REQUEST = endpoints.ResourceContainer(
SessionFormIn,
websafeConferenceKey=messages.StringField(1),
sessionId=messages.StringField(2),
)
SESS_GET_BY_TYPE = endpoints.ResourceContainer(
message_types.VoidMessage,
websafeConferenceKey=messages.StringField(1),
typeOfSession=messages.StringField(2),
)
SESS_GET_ALL_BY_SPEAKER = endpoints.ResourceContainer(
message_types.VoidMessage,
websafeSpeakerKey=messages.StringField(1),
)
SESS_GET_BY_SPEAKER = endpoints.ResourceContainer(
message_types.VoidMessage,
websafeConferenceKey=messages.StringField(1),
websafeSpeakerKey=messages.StringField(2),
)
SESS_GET_BY_LOCATION = endpoints.ResourceContainer(
message_types.VoidMessage,
websafeConferenceKey=messages.StringField(1),
location=messages.StringField(2),
)
SESS_GET_BY_HIGHLIGHT = endpoints.ResourceContainer(
message_types.VoidMessage,
websafeConferenceKey=messages.StringField(1),
highlight=messages.StringField(2),
)
SESS_QUERY_FORMS = endpoints.ResourceContainer(
QueryForms,
websafeConferenceKey=messages.StringField(1),
)
SPEAKER_GET_REQUEST = endpoints.ResourceContainer(
message_types.VoidMessage,
websafeSpeakerKey=messages.StringField(1),
)
SPEAKER_POST_REQUEST = endpoints.ResourceContainer(
SpeakerFormIn,
websafeSpeakerKey=messages.StringField(1),
)
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
@endpoints.api(name='conference', version='v1',
allowed_client_ids=[WEB_CLIENT_ID, API_EXPLORER_CLIENT_ID],
scopes=[EMAIL_SCOPE])
class ConferenceApi(remote.Service):
"""Conference API v0.1"""
# - - - Conference objects - - - - - - - - - - - - - - - - -
def ____CONFERENCE_PART():
pass # marked as a divider in function tree view
def _copyConferenceToForm(self, conf, displayName):
"""Copy relevant fields from Conference to ConferenceForm."""
cf = ConferenceForm()
for field in cf.all_fields():
if hasattr(conf, field.name):
# convert Date to date string; just copy others
if field.name.endswith('Date'):
setattr(cf, field.name, str(getattr(conf, field.name)))
else:
setattr(cf, field.name, getattr(conf, field.name))
elif field.name == "websafeKey":
setattr(cf, field.name, conf.key.urlsafe())
if displayName:
setattr(cf, 'organizerDisplayName', displayName)
cf.check_initialized()
return cf
def _createConferenceObject(self, request):
"""Create or update Conference object, returning ConferenceForm/request."""
"""Add a task of sending confirmation email to task queue"""
# preload necessary data items
user = endpoints.get_current_user()
if not user:
raise endpoints.UnauthorizedException('Authorization required')
user_id = getUserId(user)
if not request.name:
raise endpoints.BadRequestException("Conference 'name' field required")
# copy ConferenceForm/ProtoRPC Message into dict
data = {field.name: getattr(request, field.name)
for field in request.all_fields()}
del data['websafeKey']
del data['organizerDisplayName']
# add default values for those missing (both data model & outbound Message)
for df in DEFAULTS_CONF:
if data[df] in (None, []):
data[df] = DEFAULTS_CONF[df]
setattr(request, df, DEFAULTS_CONF[df])
# convert dates from strings to Date objects; set month based on start_date
if data['startDate']:
data['startDate'] = datetime.strptime(data['startDate'][:10],
"%Y-%m-%d").date()
data['month'] = data['startDate'].month
else:
data['month'] = 0
if data['endDate']:
data['endDate'] = datetime.strptime(data['endDate'][:10],
"%Y-%m-%d").date()
# set seatsAvailable to be same as maxAttendees on creation
if data["maxAttendees"] > 0:
data["seatsAvailable"] = data["maxAttendees"]
# generate Profile Key based on user ID and Conference
# ID based on Profile key get Conference key from ID
p_key = ndb.Key(Profile, user_id)
c_id = Conference.allocate_ids(size=1, parent=p_key)[0]
c_key = ndb.Key(Conference, c_id, parent=p_key)
data['key'] = c_key
data['organizerUserId'] = request.organizerUserId = user_id
Conference(**data).put()
# create Conference, send email to organizer confirming
# creation of Conference & return (modified) ConferenceForm
# _TODO 2: add confirmation email sending task to queue
taskqueue.add(params={'email': user.email(),
'conferenceInfo': repr(request)},
url='/tasks/send_confirmation_email'
)
return request
@ndb.transactional()
def _updateConferenceObject(self, request):
user_id = get_current_user_id()
# copy ConferenceForm/ProtoRPC Message into dict
data = {field.name: getattr(request, field.name)
for field in request.all_fields()}
# update existing conference
conf = ndb.Key(urlsafe=request.websafeConferenceKey).get()
# check that conference exists
if not conf:
raise endpoints.NotFoundException(
'No conference found with key: %s' % request.websafeConferenceKey)
# check that user is owner
if user_id != conf.organizerUserId:
raise endpoints.ForbiddenException(
'Only the owner can update the conference.')
# Not getting all the fields, so don't create a new object; just
# copy relevant fields from ConferenceForm to Conference object
for field in request.all_fields():
data = getattr(request, field.name)
# only copy fields where we get data
if data not in (None, []):
# special handling for dates (convert string to Date)
if field.name in ('startDate', 'endDate'):
data = datetime.strptime(data, "%Y-%m-%d").date()
if field.name == 'startDate':
conf.month = data.month
# write to Conference object
setattr(conf, field.name, data)
conf.put()
prof = ndb.Key(Profile, user_id).get()
return self._copyConferenceToForm(conf, getattr(prof, 'displayName'))
@endpoints.method(ConferenceForm, ConferenceForm, path='conference',
http_method='POST', name='createConference')
def createConference(self, request):
"""Create new conference."""
return self._createConferenceObject(request)
@endpoints.method(CONF_POST_REQUEST, ConferenceForm,
path='conference/{websafeConferenceKey}',
http_method='PUT', name='updateConference')
def updateConference(self, request):
"""Update conference with provided fields & return with updated info."""
return self._updateConferenceObject(request)
@endpoints.method(CONF_GET_REQUEST, ConferenceForm,
path='conference/{websafeConferenceKey}',
http_method='GET', name='getConference')
def getConference(self, request):
"""Return requested conference (by websafeConferenceKey)."""
# get Conference object from request; bail if not found
conf = ndb.Key(urlsafe=request.websafeConferenceKey).get()
if not conf:
raise endpoints.NotFoundException(
'No conference found with key: %s' % request.websafeConferenceKey)
prof = conf.key.parent().get()
# return ConferenceForm
return self._copyConferenceToForm(conf, getattr(prof, 'displayName'))
@endpoints.method(message_types.VoidMessage, ConferenceForms,
path='getConferencesCreated',
http_method='POST', name='getConferencesCreated')
def getConferencesCreated(self, request):
"""Return conferences created by user."""
# make sure user is authed
user_id = get_current_user_id()
# create ancestor query for all key matches for this user
confs = Conference.query(ancestor=ndb.Key(Profile, user_id))
prof = ndb.Key(Profile, user_id).get()
# return set of ConferenceForm objects per Conference
return ConferenceForms(
items=[self._copyConferenceToForm(conf, getattr(prof, 'displayName')) for conf in confs]
)
# - - - - - - - - - - Conference Query functions
def ____CONF_QUERY_PART():
pass # marked as a divider in function tree view
def _getConferenceQuery(self, request):
"""Return formatted query from the submitted filters."""
q = Conference.query()
inequality_filter, filters = self._formatFilters(request.filters)
# If exists, sort on inequality filter first
if not inequality_filter:
q = q.order(Conference.name)
else:
q = q.order(ndb.GenericProperty(inequality_filter))
q = q.order(Conference.name)
for filtr in filters:
if filtr["field"] in ["month", "maxAttendees"]:
filtr["value"] = int(filtr["value"])
formatted_query = ndb.query.FilterNode(filtr["field"], filtr["operator"], filtr["value"])
q = q.filter(formatted_query)
return q
def _formatFilters(self, filters):
"""Parse, check validity and format user supplied filters."""
formatted_filters = []
inequality_field = None
for f in filters:
filtr = {field.name: getattr(f, field.name) for field in f.all_fields()}
try:
filtr["field"] = FIELDS_CONF[filtr["field"]]
filtr["operator"] = OPERATORS[filtr["operator"]]
except KeyError:
raise endpoints.BadRequestException("Filter contains invalid field or operator.")
# Every operation except "=" is an inequality
if filtr["operator"] != "=":
# check if inequality operation has been used in previous filters
# disallow the filter if inequality was performed on a different field before
# track the field on which the inequality operation is performed
if inequality_field and inequality_field != filtr["field"]:
raise endpoints.BadRequestException("Inequality filter is allowed on only one field.")
else:
inequality_field = filtr["field"]
formatted_filters.append(filtr)
return (inequality_field, formatted_filters)
@endpoints.method(QueryForms, ConferenceForms,
path='queryConferences',
http_method='POST',
name='queryConferences')
def queryConferences(self, request):
"""Query for conferences."""
conferences = self._getConferenceQuery(request)
# 1. fetch organiser displayName from profiles
# get all keys and use get_multi
organisers = [(ndb.Key(Profile, conf.organizerUserId)) for conf in conferences]
profiles = ndb.get_multi(organisers)
# parse display names in a dict for easier fetching
names = {}
for profile in profiles:
names[profile.key.id()] = profile.displayName
# 2. return individual ConferenceForm object per Conference
return ConferenceForms(
items=[self._copyConferenceToForm(conf, names[conf.organizerUserId]) for conf in \
conferences]
)
# - - - Speaker objects - - - - - - - - - - - - - - - - -
def ____SPEAKER_PART():
pass # marked as a divider in function tree view
def _copySpeakerToForm(self, speaker):
"""Copy relevant fields from Speaker to SpeakerFormOut."""
sf = SpeakerFormOut()
for field in sf.all_fields():
if hasattr(speaker, field.name):
setattr(sf, field.name, getattr(speaker, field.name))
elif field.name == "websafeKey":
setattr(sf, field.name, speaker.key.urlsafe())
sf.check_initialized()
return sf
def _createSpeakerObject(self, request):
"""Create Speaker object, returning SpeakerFormOut."""
# preload necessary data items
user_id = get_current_user_id()
if not request.name:
raise endpoints.BadRequestException(
"Speaker 'name' field required")
# copy SpeakerFormIn/ProtoRPC Message into dict
data = {field.name: getattr(request, field.name)
for field in request.all_fields()}
# generate Profile Key based on user ID, used as parent
p_key = ndb.Key(Profile, user_id)
data['parent'] = p_key
# create Speaker & return (new) SpeakerFormOut
speaker = Speaker(**data).put()
return self._copySpeakerToForm(speaker.get())
@ndb.transactional()
def _updateSpeakerObject(self, request):
user_id = get_current_user_id()
# update existing speaker
speaker = ndb.Key(urlsafe=request.websafeSpeakerKey).get()
# check that speaker exists
if not speaker:
raise endpoints.NotFoundException(
'No speaker found with key: %s' % request.websafeSpeakerKey)
# check that user is owner:
# speaker parent (=profile) has user_id as id
if user_id != speaker.key.parent().string_id():
raise endpoints.ForbiddenException(
'Only the owner can update the speaker.')
# Not getting all the fields, so don't create a new object; just
# copy relevant fields from SpeakerFormIn to Speaker object
for field in request.all_fields():
data = getattr(request, field.name)
# only copy fields where we get data
if data not in (None, []):
# write to Speaker object
setattr(speaker, field.name, data)
speaker.put()
return self._copySpeakerToForm(speaker)
@endpoints.method(
SpeakerFormIn, SpeakerFormOut, path='speaker',
http_method='POST', name='createSpeaker')
def createSpeaker(self, request):
"""Create new speaker."""
return self._createSpeakerObject(request)
@endpoints.method(
SPEAKER_POST_REQUEST, SpeakerFormOut,
path='speaker/{websafeSpeakerKey}',
http_method='PUT', name='updateSpeaker')
def updateSpeaker(self, request):
"""Update speaker with provided fields & return with updated info."""
return self._updateSpeakerObject(request)
@endpoints.method(
SPEAKER_GET_REQUEST, SpeakerFormOut,
path='speaker/{websafeSpeakerKey}',
http_method='GET', name='getSpeaker')
def getSpeaker(self, request):
"""Return requested speaker (by websafeSpeakerKey)."""
# get Speaker object from request; bail if not found
speaker = ndb.Key(urlsafe=request.websafeSpeakerKey).get()
if not speaker:
raise endpoints.NotFoundException(
'No speaker found with key: %s' % request.websafeSpeakerKey)
if speaker.key.kind() != "Speaker":
raise endpoints.NotFoundException(
'Key does not belong to speaker: %s'% request.websafeSpeakerKey)
# return SpeakerFormOut
return self._copySpeakerToForm(speaker)
@endpoints.method(message_types.VoidMessage, SpeakerForms,
path='getAllSpeakers',
http_method='GET', name='getAllSpeakers')
def getAllSpeakers(self, request):
"""Get all Speakers"""
user_id = get_current_user_id()
speakers = Speaker.query() # get all speakers
return SpeakerForms(
items=[self._copySpeakerToForm(speaker) for speaker in speakers]
)
# - - - Session objects - - - - - - - - - - - - - - - - -
def ____SESS_PART():
pass # marked as a divider in function tree view
def _copySessionToForm(self, sess):
"""Copy relevant fields from Session to SessionFormOut."""
sf = SessionFormOut()
for field in sf.all_fields():
if hasattr(sess, field.name):
# convert Date to date string and Time to time string;
# copy speakers into forms;
# just copy all the others
if field.name in ("startTime", "date"):
setattr(sf, field.name, str(getattr(sess, field.name)))
elif field.name == "speaker":
speakers = []
for speaker_key in getattr(sess, "speaker"):
speaker = speaker_key.get()
speakers.append(self._copySpeakerToForm(speaker))
setattr(sf, "speaker", speakers)
else:
setattr(sf, field.name, getattr(sess, field.name))
elif field.name == "sessionId":
setattr(sf, field.name, str(sess.key.id()))
elif field.name == "websafeConferenceKey":
setattr(sf, field.name, sess.key.parent().urlsafe())
sf.check_initialized()
return sf
def _createSessionObject(self, request):
"""
Create Session object, returning SessionFormOut.
"""
# preload necessary data items
user_id = get_current_user_id()
# load conference
conf = ndb.Key(urlsafe=request.websafeConferenceKey)
if conf.kind() != "Conference":
raise endpoints.BadRequestException(
"Conference key expected")
# check if the conference has the right owner
if conf.get().organizerUserId != user_id:
raise endpoints.BadRequestException(
"Only the conference owner can add sessions")
if not request.name:
raise endpoints.BadRequestException(
"Session 'name' field required")
# copy SessionFormIn/ProtoRPC Message into dict
data = {field.name: getattr(request, field.name)
for field in request.all_fields()}
# The speaker field will be dealt with specially
del data['speaker_key']
# delete websafeConferenceKey
del data['websafeConferenceKey']
# we have to adjust the typeOfSession
if data['typeOfSession']:
data['typeOfSession'] = (
str(getattr(request, 'typeOfSession')))
# add default values for those missing
# (both data model & outbound Message)
for df in DEFAULTS_SESS:
if data[df] in (None, []):
data[df] = DEFAULTS_SESS[df]
setattr(request, df, DEFAULTS_SESS[df])
# add speakers
speaker_keys = []
for speakerform in getattr(request, 'speaker_key'):
speaker_key = ndb.Key(urlsafe=speakerform)
if speaker_key.kind() != "Speaker":
raise endpoints.BadRequestException(
"Speaker key expected")
# we try to get the data - is the speaker existing?
speaker = speaker_key.get()
if speaker is None:
raise endpoints.BadRequestException("Speaker not found")
speaker_keys.append(speaker_key)
data['speaker'] = speaker_keys
# convert dates from strings to Date objects,
# times from strings to Time objects
if data['date']:
data['date'] = datetime.strptime(data['date'][:10],
"%Y-%m-%d").date()
if data['startTime']:
data['startTime'] = datetime.strptime(data['startTime'][:5],
"%H:%M").time()
# set session parent to conference
data['parent'] = conf
# create Session, search for featured speaker in a task
session = Session(**data).put()
taskqueue.add(
params=
{
'sessionId': str(session.id()),
'websafeConferenceKey': session.parent().urlsafe()
},
url='/tasks/search_featured_speakers'
)
return self._copySessionToForm(session.get())
@ndb.transactional()
def _updateSessionObject(self, request):
"""Update the session object."""
user_id = get_current_user_id()
# get the conference object
conf = ndb.Key(urlsafe=request.websafeConferenceKey).get()
if conf.kind() != 'Conference':
raise endpoints.BadRequestException(
'Provided conference key is invalid')
# check that user is organizer
if user_id != conf.organizerUserId:
raise endpoints.ForbiddenException(
'Only the owner can update the conference.')
# get the existing session
sess = Session.get_by_id(int(request.sessionId), parent=conf)
# check that session exists
if not sess:
raise endpoints.NotFoundException(
'No session found with id: %s' % request.sessionId)
# Not getting all the fields, so don't create a new object; just
# copy relevant fields from SessionFormIn to Session object
for field in request.all_fields():
data = getattr(request, field.name)
# only copy fields where we get data
if data not in (None, []):
# special handling for dates (convert string to Date)
if field.name in ('date', 'startTime'):
data = datetime.strptime(data, "%Y-%m-%d").date()
# special handling for speaker: convert to key
if field.name == 'speaker':
data2 = []
for speakerform in data:
speaker_key = ndb.Key(urlsafe=speakerform.websafeKey)
if speaker_key.kind() != 'Speaker':
raise endpoints.BadRequestException('Expected Speaker key')
# check if the speaker exists
if speaker_key.get() is None:
raise endpoints.BadRequestException('Could not find speaker')
# set speaker key
data2.append(speaker_key)
# replace speaker forms with speaker key list
data = data2
# special handling for session type
if field.name == 'typeOfSession':
data = getattr(SessionType, data)
# write to Conference object
setattr(conf, field.name, data)
sess.put()
return self._copySessionToForm(sess)
@endpoints.method(
SESS_CREATE_REQUEST, SessionFormOut,
path='conference/{websafeConferenceKey}/session',
http_method='POST', name='createSession')
def createSession(self, request):
"""Create new session in a conference."""
return self._createSessionObject(request)
@endpoints.method(
SESS_POST_REQUEST, SessionFormOut,
path='conference/{websafeConferenceKey}/session/{sessionId}',
http_method='PUT', name='updateSession')
def updateSession(self, request):
"""Update session with provided fields & return with updated info."""
return self._updateSessionObject(request)
@endpoints.method(
SESS_GET_REQUEST, SessionFormOut,
path='conference/{websafeConferenceKey}/session/{sessionId}',
http_method='GET', name='getSession')
def getSession(self, request):
"""Return requested session (by websafeConferenceKey and
sessionId)."""
# get the conference key
conf = ndb.Key(urlsafe=request.websafeConferenceKey)
if conf.kind() != 'Conference':
raise endpoints.BadRequestException(
'Provided conference key is invalid')
# get Session object from request; bail if not found
# dumpclean(request)
sess = Session.get_by_id(int(request.sessionId), parent=conf)
if not sess:
raise endpoints.NotFoundException(
'No session found with id %s' % request.sessionId)
# return SessionFormOut
return self._copySessionToForm(sess)
# - - - - - - - - - Session Query Methods
def ____SESS_QUERY_PART():
pass # marked as a divider in function tree view
def _getSessionQuery(self, request):
"""Return formatted query from the submitted filters."""
# check for the provided conference
conf = ndb.Key(urlsafe=request.websafeConferenceKey)
if conf.kind() != 'Conference':
raise endpoints.BadRequestException(
'Conference specified not valid')
q = Session.query(ancestor=conf)
inequality_filter, filters = self._formatFilters(
request.filters, FIELDS_SESS)
# If exists, sort on inequality filter first
if not inequality_filter:
q = q.order(Session.name)
else:
q = q.order(ndb.GenericProperty(inequality_filter))
q = q.order(Session.name)
for filtr in filters:
if filtr["field"] == "durationInMins":
filtr["value"] = int(filtr["value"])
formatted_query = ndb.query.FilterNode(
filtr["field"],
filtr["operator"],
filtr["value"])
q = q.filter(formatted_query)
return q
@endpoints.method(
SESS_QUERY_FORMS, SessionForms,
path='conference/{websafeConferenceKey}/session/query',
http_method='POST',
name='querySessions')
def querySessions(self, request):
"""Query for sessions."""
sessions = self._getSessionQuery(request)
# return individual SessionFormOut object per Session
return SessionForms(
items=[self._copySessionToForm(sess)
for sess in sessions]
)
@endpoints.method(
CONF_GET_REQUEST, SessionForms,
path='conference/{websafeConferenceKey}/session',
http_method='GET',
name='getConferenceSessions')
def getConferenceSessions(self, request):
"""Get all sessions in a conference"""
# get the conference
conf = ndb.Key(urlsafe=request.websafeConferenceKey)
# is it really a conference key?
if conf.kind() != 'Conference':
raise endpoints.BadRequestException(
'Provided key is not a conference key')
# is the conference existing?
if conf.get() is None:
raise endpoints.NotFoundException('Conference not found')
# get all sessions in the conference
sessions = Session.query(ancestor=conf)
# return individual SessionFormOut object per Session
return SessionForms(
items=[self._copySessionToForm(sess)
for sess in sessions]
)
@endpoints.method(
SESS_GET_BY_TYPE, SessionForms,
path='conference/{websafeConferenceKey}/sessionByType/{typeOfSession}',
http_method='GET',
name='getConferenceSessionsByType')
def getConferenceSessionsByType(self, request):
"""Get all sessions in a conference of a specific type"""
# get the conference
conf = ndb.Key(urlsafe=request.websafeConferenceKey)
# is it really a conference key?
if conf.kind() != 'Conference':
raise endpoints.BadRequestException(
'Provided key is not a conference key')
# is the conference existing?
if conf.get() is None:
raise endpoints.NotFoundException('Conference not found')
# get all sessions in the conference
sessions = Session.query(ancestor=conf)
# and filter by session type
sessions = sessions.filter(Session.typeOfSession == request.typeOfSession)
# return individual SessionFormOut object per Session
return SessionForms(
items=[self._copySessionToForm(sess)
for sess in sessions]
)
@endpoints.method(
SESS_GET_ALL_BY_SPEAKER, SessionForms,
path='speaker/{websafeSpeakerKey}/session',
http_method='GET',
name='getSessionsBySpeaker')
def getSessionsBySpeaker(self, request):
"""Get all sessions with a specified speaker"""
# get the speaker
speaker = ndb.Key(urlsafe=request.websafeSpeakerKey)
# is it really a speaker key?
if speaker.kind() != 'Speaker':
raise endpoints.BadRequestException(
'Provided key is not a speaker key')
# is the speaker existing?
if speaker.get() is None:
raise endpoints.NotFoundException('Speaker not found')
# get all sessions with this speaker
sessions = Session.query(Session.speaker == speaker)
# return individual SessionFormOut object per Session
return SessionForms(
items=[self._copySessionToForm(sess)
for sess in sessions]
)
def ____TWO_ADDITIONAL_QUERY():
pass # marked as a divider in function tree view
@endpoints.method(
SESS_GET_BY_HIGHLIGHT, SessionForms,
path='conference/{websafeConferenceKey}/byHighlight/{highlight}',
http_method='GET',
name='getConferenceSessionsByHighlight')
def getConferenceSessionsByHighlight(self, request):
"""Get all conference sessions with a specified highlight"""
# get the conference
conf = ndb.Key(urlsafe=request.websafeConferenceKey)
# is it really a conference key?
if conf.kind() != 'Conference':
raise endpoints.BadRequestException(
'Provided key is not a conference key')
# is the conference existing?
if conf.get() is None:
raise endpoints.NotFoundException('Conference not found')
# get all sessions in the conference
sessions = Session.query(ancestor=conf)
# and filter by highlight
sessions = sessions.filter(Session.highlight == request.highlight)
# return individual SessionFormOut object per Session
return SessionForms(
items=[self._copySessionToForm(sess)
for sess in sessions]
)
@endpoints.method(
SESS_GET_BY_LOCATION, SessionForms,
path='conference/{websafeConferenceKey}/byLocation/{location}',
http_method='GET',
name='getConferenceSessionsByLocation')
def getConferenceSessionsByLocation(self, request):
"""Get all conference sessions with a specified location"""
# get the conference
conf = ndb.Key(urlsafe=request.websafeConferenceKey)
# is it really a conference key?
if conf.kind() != 'Conference':
raise endpoints.BadRequestException(
'Provided key is not a conference key')
# is the conference existing?
if conf.get() is None:
raise endpoints.NotFoundException('Conference not found')
# get all sessions in the conference
sessions = Session.query(ancestor=conf)
# and filter by highlight
sessions = sessions.filter(Session.location == request.location)
# return individual SessionFormOut object per Session
return SessionForms(
items=[self._copySessionToForm(sess)
for sess in sessions]
)
# - - - Profile objects - - - - - - - - - - - - - - - - - - -
def ____PROFILE_PART():
pass # marked as a divider in function tree view
def _copyProfileToForm(self, prof):
"""Copy relevant fields from Profile to ProfileForm."""
# copy relevant fields from Profile to ProfileForm
pf = ProfileForm()
for field in pf.all_fields():
if hasattr(prof, field.name):
# convert t-shirt string to Enum; just copy others
if field.name == 'teeShirtSize':
setattr(pf, field.name, getattr(TeeShirtSize, getattr(prof, field.name)))
else:
setattr(pf, field.name, getattr(prof, field.name))
pf.check_initialized()
return pf
def _getProfileFromUser(self):
"""Return user Profile from datastore, creating new one if non-existent."""
# make sure user is authed
user = endpoints.get_current_user()
if not user:
raise endpoints.UnauthorizedException('Authorization required')
# get Profile from datastore
user_id = getUserId(user)
p_key = ndb.Key(Profile, user_id)
profile = p_key.get()
# create new Profile if not there
if not profile:
profile = Profile(
key = p_key,
displayName = user.nickname(),
mainEmail= user.email(),
)
profile.put()
return profile # return Profile
def _doProfile(self, save_request=None):
"""Get user Profile and return to user, possibly updating it first."""
# get user Profile
prof = self._getProfileFromUser()
# if saveProfile(), process user-modifyable fields
if save_request:
for field in ('displayName', 'teeShirtSize'):
if hasattr(save_request, field):
val = getattr(save_request, field)
if val:
setattr(prof, field, str(val))
#if field == 'teeShirtSize':
# setattr(prof, field, str(val).upper())
#else:
# setattr(prof, field, val)
prof.put()
# return ProfileForm
return self._copyProfileToForm(prof)
@endpoints.method(message_types.VoidMessage, ProfileForm,
path='profile', http_method='GET', name='getProfile')
def getProfile(self, request):
"""Return user profile."""
return self._doProfile()
@endpoints.method(ProfileMiniForm, ProfileForm,
path='profile', http_method='POST', name='saveProfile')
def saveProfile(self, request):
"""Update & return user profile."""
return self._doProfile(request)
# - - - Registration - - - - - - - - - - - - - - - - - - - -
def ____CONF_REGISTRATION_PART():
pass # marked as a divider in function tree view
@ndb.transactional(xg=True)
def _conferenceRegistration(self, request, reg=True):
"""Register or unregister user for selected conference."""
retval = None
prof = self._getProfileFromUser() # get user Profile
# check if conf exists given websafeConfKey
# get conference; check that it exists
wsck = request.websafeConferenceKey
conf = ndb.Key(urlsafe=wsck).get()
if not conf:
raise endpoints.NotFoundException(
'No conference found with key: %s' % wsck)
# register
if reg: