本文整理汇总了Python中models.Speaker.get_or_insert方法的典型用法代码示例。如果您正苦于以下问题:Python Speaker.get_or_insert方法的具体用法?Python Speaker.get_or_insert怎么用?Python Speaker.get_or_insert使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类models.Speaker
的用法示例。
在下文中一共展示了Speaker.get_or_insert方法的3个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _createSessionObject
# 需要导入模块: from models import Speaker [as 别名]
# 或者: from models.Speaker import get_or_insert [as 别名]
def _createSessionObject(self, request):
"""
Creates Session object, returning a variation of the
SessionForm object.
"""
# check if user is already logged in
user = endpoints.get_current_user()
if not user:
raise endpoints.UnauthorizedException('Authorization required')
user_id = getUserId(user)
# convert websafeKey to a conference key
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 the owner
if user_id != conf.organizerUserId:
raise endpoints.ForbiddenException(
'The conference can only be changed by the owner.')
if not request.name:
raise endpoints.BadRequestException("Session 'name' field \
required")
# copy SessionForm/ProtoRPC Message into dict
data = {field.name: getattr(request, field.name) for field in
request.all_fields()}
del data['websafeKey']
del data['websafeConfKey']
del data['websafeConferenceKey']
# add default values for those missing (both data model & outbound
# Message)
for df in DEFAULT_SESS:
if data[df] in (None, []):
data[df] = DEFAULT_SESS[df]
setattr(request, df, DEFAULT_SESS[df])
# convert type of session object to string
if data['typeOfSession']:
data['typeOfSession'] = str(data['typeOfSession'])
# convert date from a string to Date objects
if data['date']:
data['date'] = datetime.strptime(data['date'][:10],
"%Y-%m-%d").date()
# convert startTime from a string to Time objects
if data['startTime']:
data['startTime'] = datetime.strptime(data['startTime'][:5],
"%H:%M").time()
# convert duration from a string to Time objects
if data['duration']:
data['duration'] = datetime.strptime(data['duration'][:5],
"%H:%M").time()
# convert speakers from strings as list to Speaker entity keys as list
if data['speakers']:
# Check that each provided speaker for a session exists in the
# database. If the speaker exists in the database, then retrieve
# the key value. Otherwise, make a new speaker having the provided
# name as the key.
speakersForSession = []
for speaker in data['speakers']:
# The function get_or_insert(key_name, args) gets as a
# transaction an existing entity or it makes a new entity,
# which eliminates the problem of duplicate speakers when
# multiple sessions that have the same speaker are formed
# during the same time. The speaker string value is put in
# lowercase with no whitespaces for the key name.
spkr_for_sess_key = Speaker.get_or_insert(
speaker.lower().strip().replace(" ", "_"),
name=speaker).key
# add speaker for session key to speakersForSession list
speakersForSession.append(spkr_for_sess_key)
# update data['speakers'] with newly formed list of keys
data['speakers'] = speakersForSession
# get Conference key
c_key = conf.key
# designate new Session ID with the Conference key as a parent
s_id = Session.allocate_ids(size=1, parent=c_key)[0]
# create key for new Session having Conference key as a parent
s_key = ndb.Key(Session, s_id, parent=c_key)
# put key into dict
data['key'] = s_key
# create a Session
Session(**data).put()
# allows for the session to be copied back to form
sess = s_key.get()
# reviews speakers for conference when task is added to queue
taskqueue.add(params={'c_key_str': c_key.urlsafe()},
url='/tasks/review_speakers_for_sessions')
return self._copySessionToForm(sess)
示例2: _createSessionObject
# 需要导入模块: from models import Speaker [as 别名]
# 或者: from models.Speaker import get_or_insert [as 别名]
def _createSessionObject(self, request):
'''Create a new session object
Note:
Only conference owner can add sessions
'''
user = endpoints.get_current_user()
if not user:
raise endpoints.UnauthorizedException('Authorization required')
user_id = getUserId(user)
# get conference using websafe key
conf = ndb.Key(urlsafe=request.websafeConferenceKey).get()
# Raise if conference doesn't exist
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 add a session to the conference.')
# Check request has session required attribute name
if not request.name:
raise endpoints.BadRequestException("Conference 'name' field required")
# copy SessionForm/ProtoRPC Message into dict
data = {field.name: getattr(request, field.name) for field in request.all_fields()}
del data['websafeKey']
del data['websafeConferenceKey']
# add default values for those missing (both data model & outbound Message)
for df in SESSION_DEFAULTS:
if data[df] in (None, []):
data[df] = SESSION_DEFAULTS[df]
setattr(request, df, SESSION_DEFAULTS[df])
# convert session type to string
if data['typeOfSession']:
data['typeOfSession'] = str(data['typeOfSession'])
# convert dates from strings to Date and TimeDuration 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()
if data['duration']:
data['duration'] = datetime.strptime(data['duration'][:5],
"%H:%M").time()
# Transform list of speaker names into list of speaker keys
# Speaker names are case-insensitive
data['speakers'] = [
Speaker.get_or_insert(speaker.lower().strip(),
name=speaker).key
for speaker in data['speakers']
]
# get Conference Key, allocate Session ID
c_key = conf.key
s_id = Session.allocate_ids(size=1, parent=c_key)[0]
# create Session's key and store in data
s_key = ndb.Key(Session, s_id, parent=c_key)
data['key'] = s_key
# add task to queue to update featured speaker
taskqueue.add(params={'conf_key': c_key.urlsafe()},
url='/tasks/featured_speaker')
# creation of Session & return (modified) SessionForm
Session(**data).put()
return self._copySessionToForm(s_key.get())
示例3: _createSessionObject
# 需要导入模块: from models import Speaker [as 别名]
# 或者: from models.Speaker import get_or_insert [as 别名]
def _createSessionObject(self, request):
"""Creates a Session and returns an altered SessionForm object.
args:
request: Combined Container of a SessionForm object and a
websafeConferenceKey identifying the conference.
returns:
sform: Altered SessionForm object with possible filled in default
values and a websafeKey identifying the session.
"""
# check if user is logged in
user = endpoints.get_current_user()
if not user:
raise endpoints.UnauthorizedException('Authorization required')
user_id = getUserId(user)
# convert websafeKey to conference key
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.')
if not request.name:
raise endpoints.BadRequestException("Session 'name' field \
required")
# copy SessionForm/ProtoRPC Message into dict
data = {field.name: getattr(request, field.name) for field in
request.all_fields()}
del data['websafeKey']
del data['websafeConfKey']
del data['websafeConferenceKey']
# add default values for those missing (both data model & outbound
# Message)
for df in DEFAULTS_SESSION:
if data[df] in (None, []):
data[df] = DEFAULTS_SESSION[df]
setattr(request, df, DEFAULTS_SESSION[df])
# convert type of session object to string
if data['typeOfSession']:
data['typeOfSession'] = str(data['typeOfSession'])
# convert date from string to Date objects
if data['date']:
data['date'] = datetime.strptime(data['date'][:10],
"%Y-%m-%d").date()
# convert startTime from string to Time objects
if data['startTime']:
data['startTime'] = datetime.strptime(data['startTime'][:5],
"%H:%M").time()
# convert duration from string to Time objects
if data['duration']:
data['duration'] = datetime.strptime(data['duration'][:5],
"%H:%M").time()
# convert speakers from a list of strings to a list of Speaker entity
# keys
if data['speakers']:
# check for each provided session speaker if he exists already in
# the database. If yes, get the key value, if not, create a new
# speaker with the provided name as key.
# NOTE: For simplification, it is assumed that a name uniquely
# identifies a speaker and therefore can be set as id as well.
sessionSpeakers = []
for speaker in data['speakers']:
# get_or_insert(key_name, args) transactionally retrieves an
# existing entity or creates a new one. This also prevents the
# risk of duplicate speaker records when multiple sessions with
# the same speaker are created at the same time.
# For the key name, the speaker string is formatted in lower
# case without whitespaces. To be safe, it should also be
# converted to an ascii string in case of special unicode
# characters. However, as this is more complicated, its not
# been done for this exercise.
session_speaker_key = Speaker.get_or_insert(
speaker.lower().strip().replace(" ", "_"),
name=speaker).key
# Add Speaker key to the list of sessionSpeakers.
sessionSpeakers.append(session_speaker_key)
# overwrite data['speakers'] with the new created key list.
data['speakers'] = sessionSpeakers
# get Conference Key
c_key = conf.key
# allocate new Session ID with Conference key as parent
s_id = Session.allocate_ids(size=1, parent=c_key)[0]
# create a key for for the new Session with conference key as parent
s_key = ndb.Key(Session, s_id, parent=c_key)
# add key into dictionary
data['key'] = s_key
# create Session
Session(**data).put()
# get session to copy it back to the form as return
#.........这里部分代码省略.........