本文整理汇总了Python中models.Conference.allocate_ids方法的典型用法代码示例。如果您正苦于以下问题:Python Conference.allocate_ids方法的具体用法?Python Conference.allocate_ids怎么用?Python Conference.allocate_ids使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类models.Conference
的用法示例。
在下文中一共展示了Conference.allocate_ids方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _createSessionObject
# 需要导入模块: from models import Conference [as 别名]
# 或者: from models.Conference import allocate_ids [as 别名]
def _createSessionObject(self, request):
"""Create a session object, return SessionForm"""
# check for authentication
user = endpoints.get_current_user()
if not user:
raise endpoints.UnauthorizedException('Authorization required')
user_id = getUserId(user)
# get parent Conference from request; raise exception if not found
c_key = ndb.Key(urlsafe=request.websafeConferenceKey)
conf = c_key.get()
if not conf:
raise endpoints.NotFoundException(
'No conference found with key: %s' %
request.websafeConferenceKey)
if not request.sessionName:
raise endpoints.BadRequestException(
"Session 'sessionName' field required")
# check that user is owner of given conference
if user_id != conf.organizerUserId:
raise endpoints.ForbiddenException(
'Only the owner can add a session to the conference.')
# copy ConferenceForm/ProtoRPC Message into dict
data = {field.name: getattr(request, field.name)
for field in request.all_fields()}
del data['websafeConferenceKey']
del data['websafeKey']
# add default values for those missing
for df in SDEFAULTS:
if data[df] in (None, []):
data[df] = SDEFAULTS[df]
setattr(request, df, SDEFAULTS[df])
# convert dates from strings; set month based on start_date
if data['date']:
data['date'] = datetime.strptime(data['date'][:10],
"%Y-%m-%d").date()
# convert type of session to uppercase
data['typeOfSession'] = data['typeOfSession'].upper()
# generate Session ID based on Conference ID
s_id = Conference.allocate_ids(size=1, parent=c_key)[0]
s_key = ndb.Key(Session, s_id, parent=c_key)
data['key'] = s_key
# return a session form with the same data as in the datastore
newSess = Session(**data)
newSess.put()
# TASK 4
# Check for featured speaker
taskqueue.add(params={'sessionKey': s_key.urlsafe()},
url='/tasks/set_featured')
return self._copySessionToForm(newSess)
示例2: _createConferenceObject
# 需要导入模块: from models import Conference [as 别名]
# 或者: from models.Conference import allocate_ids [as 别名]
def _createConferenceObject(self, request):
"""Create or update Conference object, returning ConferenceForm/request."""
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")
data = {field.name: getattr(request, field.name) for field in request.all_fields()}
del data['websafeKey']
del data['organizerDisplayName']
for df in DEFAULTS:
if data[df] in (None, []):
data[df] = DEFAULTS[df]
setattr(request, df, DEFAULTS[df])
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()
if data["maxAttendees"] > 0:
data["seatsAvailable"] = data["maxAttendees"]
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()
taskqueue.add(params={'email': user.email(),
'conferenceInfo': repr(request)},
url='/tasks/send_confirmation_email'
)
return request
示例3: _createConferenceObject
# 需要导入模块: from models import Conference [as 别名]
# 或者: from models.Conference import allocate_ids [as 别名]
def _createConferenceObject(self, request):
"""Create or update Conference object, returning
ConferenceForm/request."""
# 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 and outbound
# Message.
for df in DEFAULTS:
if data[df] in (None, []):
data[df] = DEFAULTS[df]
setattr(request, df, DEFAULTS[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
# both for data model and outbound Message
if data["maxAttendees"] > 0:
data["seatsAvailable"] = data["maxAttendees"]
setattr(request, "seatsAvailable", data["maxAttendees"])
# make Profile Key from user ID
p_key = ndb.Key(Profile, user_id)
# allocate new Conference ID with Profile key as parent
c_id = Conference.allocate_ids(size=1, parent=p_key)[0]
# make Conference key from ID
c_key = ndb.Key(Conference, c_id, parent=p_key)
data['key'] = c_key
data['organizerUserId'] = request.organizerUserId = user_id
# create Conference and return (modified) ConferenceForm
Conference(**data).put()
taskqueue.add(params={'email': user.email(),
'conferenceInfo': request},
url='/tasks/send_confirmation_email')
return request
示例4: _createSessionObject
# 需要导入模块: from models import Conference [as 别名]
# 或者: from models.Conference import allocate_ids [as 别名]
def _createSessionObject(self, request):
"""Create or update Conference object, returning ConferenceForm/request."""
conf = ndb.Key(urlsafe=request.websafeConferenceKey).get()
if not conf:
raise endpoints.NotFoundException(
'No conference found with key: %s' % request.websafeConferenceKey)
user = endpoints.get_current_user()
if not user:
raise endpoints.UnauthorizedException('Authorization required')
user_id = getUserId(user)
if user_id != conf.organizerUserId:
raise endpoints.ForbiddenException(
'Only the owner of the conference can create session.')
if not request.name:
raise endpoints.BadRequestException("Session 'name' field required")
#
# # copy ConferenceForm/ProtoRPC Message into dict
data = {field.name: getattr(request, field.name) for field in request.all_fields()}
del data['websafeConferenceKey']
# #del data['organizerDisplayName']
#
# # add default values for those missing (both data model & outbound Message)
for df in SESSION_EFAULTS:
if data[df] in (None, []):
data[df] = SESSION_EFAULTS[df]
setattr(request, df, SESSION_EFAULTS[df])
data['organizerUserId']= user_id
data['websafeConferenceKey'] = request.websafeConferenceKey
data['conferenceName']=conf.name
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)
s_id = Session.allocate_ids(size=1, parent=c_key)[0]
s_key = ndb.Key(Session, s_id, parent=c_key)
data['key'] = s_key
if data['date']:
data['startTime'] = datetime.strptime(data['date'], '%Y-%m-%d %H:%M:%S').time()
data['date'] = datetime.strptime(data['date'][:10], "%Y-%m-%d").date()
# # create Conference, send email to organizer confirming
# # creation of Conference & return (modified) ConferenceForm
session = Session(**data)
session.put()
taskqueue.add(params={'websafeConferenceKey': request.websafeConferenceKey,
'speaker': data['speaker']},
url='/tasks/set_featured_speaker'
)
return self._copySessionToForm(session)
示例5: _createConferenceObject
# 需要导入模块: from models import Conference [as 别名]
# 或者: from models.Conference import allocate_ids [as 别名]
def _createConferenceObject(self, request):
"""Create or update Conference object,
returning ConferenceForm/request.
"""
# preload necessary data items
user = self._getCurrentUser()
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()}
# remove unnecessary values
del data['websafeKey']
del data['organizerDisplayName']
# add default values for those missing (both data model & outbound Message)
for df in DEFAULTS:
if data[df] in (None, []):
data[df] = DEFAULTS[df]
setattr(request, df, DEFAULTS[df])
# convert dates from strings to Date objects; set month based on start_date
if data['startDate']:
print data['startDate']
data['startDate'] = datetime.strptime(data['startDate'][:10], "%Y-%m-%d").date()
print data['startDate']
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()
# Send email to organizer confirming
# creation of Conference & return (modified) ConferenceForm
taskqueue.add(
params={'email': user.email(), 'conferenceInfo': repr(request)},
url='/tasks/send_confirmation_email')
return request
示例6: _createConferenceObject
# 需要导入模块: from models import Conference [as 别名]
# 或者: from models.Conference import allocate_ids [as 别名]
def _createConferenceObject(self, request):
"""Create a Conference object, returning ConferenceForm/request."""
# 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 CONF_DEFAULTS:
if data[df] in (None, []):
data[df] = CONF_DEFAULTS[df]
setattr(request, df, CONF_DEFAULTS[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)
# Update stored conference with profile and conference keys
data['key'] = c_key
data['organizerUserId'] = request.organizerUserId = user_id
# create Conference, send email to organizer confirming
# creation of Conference & return (modified) ConferenceForm
Conference(**data).put()
taskqueue.add(
params = {
'email' : user.email(),
'subject' : 'You Created a New Conference!',
'body' : 'Here are the details for your conference:',
'info' : repr(request)},
url = '/tasks/send_confirmation_email')
return request
示例7: _createConferenceObject
# 需要导入模块: from models import Conference [as 别名]
# 或者: from models.Conference import allocate_ids [as 别名]
def _createConferenceObject(self, request):
"""Create a Conference object, return the ConferenceForm."""
user = validateUser()
user_id = getUserId(user)
if not request.name:
raise endpoints.BadRequestException("'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.
for df in DEFAULTS:
if data[df] in (None, []):
data[df] = DEFAULTS[df]
setattr(request, df, DEFAULTS[df])
# Convert dates from strings to Date objects.
# Set month based on start_date.
if data['startDate']:
data['startDate'] = datetime.datetime.strptime(
data['startDate'][:10], "%Y-%m-%d").date()
data['month'] = data['startDate'].month
else:
data['month'] = 0
if data['endDate']:
data['endDate'] = datetime.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.
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
# Create Conference, send email to organizer confirming
# creation of Conference & return (modified) ConferenceForm
Conference(**data).put()
taskqueue.add(params={'email': user.email(),
'conferenceInfo': repr(request)},
url='/tasks/send_confirmation_email')
return request
示例8: _createConferenceObject
# 需要导入模块: from models import Conference [as 别名]
# 或者: from models.Conference import allocate_ids [as 别名]
def _createConferenceObject(self, request):
"""Create or update Conference object, returning ConferenceForm/request"""
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' is required")
# Copy the ConferenceForm/ProtoRPC message into a dictionary
data = {field.name: getattr(request, field.name) for field in request.all_fields()}
del data['websafeKey']
del data['organizerDisplayName']
# add default values for any missing items in both the data model and outbound message
for df in DEFAULTS:
if data[df] in (None, []):
data[df] = DEFAULTS[df]
setattr(request, df, DEFAULTS[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 maxAttendees at creation for data model and outbound message
if data['maxAttendees'] > 0:
data['seatsAvailable'] = data['maxAttendees']
#setattr(request, "seatsAvailable", data['maxAttendees'])
# get profile key from userId
p_key = ndb.Key(Profile, user_id)
# create a new conference id with profile key as parent
c_id = Conference.allocate_ids(size=1, parent=p_key)[0]
# make Conference key from id
c_key = ndb.Key(Conference, c_id, parent=p_key)
data['key'] = c_key
data['organizerUserId'] = request.organizerUserId = user_id
# create the Conference and return modified ConferenceForm
Conference(**data).put()
# Send a confirmation email to the user to verify that the
# conference has been created
taskqueue.add(params={'email': user.email(), 'conferenceInfo': repr(request)},
url='/tasks/send_confirmation_email')
return request
示例9: _createConferenceObject
# 需要导入模块: from models import Conference [as 别名]
# 或者: from models.Conference import allocate_ids [as 别名]
def _createConferenceObject(self, request):
"""Create a Conference object, returning ConferenceForm/request."""
if not request.name:
raise endpoints.BadRequestException("Conference 'name' field required")
# preload necessary data items
user, userId, userDisplayName, profileKey = currentUser()
# 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"]
del data["seatsAvailable"]
# add default values for those missing (both data model & outbound Message)
for df in CONFERENCE_DEFAULTS:
if data[df] in (None, []):
data[df] = CONFERENCE_DEFAULTS[df]
setattr(request, df, CONFERENCE_DEFAULTS[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 the same as maxAttendees on creation
# both for data model & outbound Message
if data["maxAttendees"] > 0:
data["seatsAvailable"] = data["maxAttendees"]
setattr(request, "seatsAvailable", data["maxAttendees"])
# allocate new Conference ID with profileKey as parent
conferenceId = Conference.allocate_ids(size=1, parent=profileKey)[0]
# make Conference key from ID
conferenceKey = ndb.Key(Conference, conferenceId, parent=profileKey)
data["key"] = conferenceKey
data["organizerUserId"] = request.organizerUserId = userId
# create Conference, send email to organizer confirming
# creation of Conference & return (modified) ConferenceForm
Conference(**data).put()
taskqueue.add(
params={"email": user.email(), "conferenceInfo": repr(request)}, url="/tasks/send_confirmation_email"
)
return self._copyConferenceToForm(conferenceKey.get(), userDisplayName)
示例10: _createConferenceObject
# 需要导入模块: from models import Conference [as 别名]
# 或者: from models.Conference import allocate_ids [as 别名]
def _createConferenceObject(self, conferenceForm):
"""Create conference object, returns ConferenceForm."""
user = endpoints.get_current_user()
if not user:
raise endpoints.UnauthorizedException('Authorization required')
data = formToDict(conferenceForm, exclude=('websafeKey', 'organizerDisplayName'))
# add default values for those missing
for df in DEFAULTS:
if data[df] in (None, []):
data[df] = DEFAULTS[df]
# add organizerUserId before checking the required fields
data['organizerUserId'] = user_id = getUserId(user)
# check required fields
for key in Conference.required_fields_schema:
if not data[key]:
raise endpoints.BadRequestException("Conference '%s' field required" % key)
# convert dates from strings to Date objects; set month based on start_date
try:
data['startDate'] = datetime.strptime(data['startDate'][:10], "%Y-%m-%d").date()
data['endDate'] = datetime.strptime(data['endDate'][:10], "%Y-%m-%d").date()
except (TypeError, ValueError):
raise endpoints.BadRequestException("Invalid date format. Please use 'YYYY-MM-DD'")
if data['startDate'] > data['endDate']:
raise endpoints.BadRequestException("start date must be before end date")
data['month'] = data['startDate'].month
# 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
# create Conference, send email to organizer confirming
# creation of Conference & return (modified) ConferenceForm
conf = Conference(**data)
conf.put()
taskqueue.add(
params={'email': user.email(), 'conferenceInfo': repr(conferenceForm)},
url='/tasks/send_confirmation_email'
)
return conf.toForm()
示例11: _createConferenceObject
# 需要导入模块: from models import Conference [as 别名]
# 或者: from models.Conference import allocate_ids [as 别名]
def _createConferenceObject(self, request):
"""Create or update Conference object, returning ConferenceForm/request."""
# 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:
if data[df] in (None, []):
data[df] = DEFAULTS[df]
setattr(request, df, DEFAULTS[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]
# TODO: Ejercicio 1 sesion 2
conference_key = ndb.Key(Conference, data['name'], parent=p_key)
data["key"] = conference_key
data["organizerUserId"] = user_id
print data
Conference(**data).put()
return request
示例12: _createConferenceObject
# 需要导入模块: from models import Conference [as 别名]
# 或者: from models.Conference import allocate_ids [as 别名]
def _createConferenceObject(self, request):
"""Create or update Conference object, returning ConferenceForm/request."""
user_id = self._getUser()
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["websafeConferenceKey"]
del data["organizerDisplayName"]
# add default values for those missing (both data model & outbound Message)
for df in DEFAULTS:
if data[df] in (None, []):
data[df] = DEFAULTS[df]
setattr(request, df, DEFAULTS[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 = self._getUserProfileKey(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
# create Conference, send email to organizer confirming
# creation of Conference & return (modified) ConferenceForm
Conference(**data).put()
# add confirmation email sending task to queue
user = endpoints.get_current_user()
taskqueue.add(
params={"email": user.email(), "conferenceInfo": repr(request)}, url="/tasks/send_confirmation_email"
)
return request
示例13: parseConference
# 需要导入模块: from models import Conference [as 别名]
# 或者: from models.Conference import allocate_ids [as 别名]
def parseConference(self, request):
"""Parse a request into a Conference and return it"""
# 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 CONFERENCE_DEFAULTS:
if data[df] in (None, []):
data[df] = CONFERENCE_DEFAULTS[df]
setattr(request, df, CONFERENCE_DEFAULTS[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'] = user_id
# create Conference, send email to organizer confirming
# creation of Conference & return (modified) ConferenceForm
conference = Conference(**data)
return conference
示例14: _createConferenceObject
# 需要导入模块: from models import Conference [as 别名]
# 或者: from models.Conference import allocate_ids [as 别名]
def _createConferenceObject(self, request):
"""Create a Conference object, returning ConferenceForm/request."""
# Getting and Verifying current user
user = getUser()
# get the user_id (email)
user_id = getUserId(user)
# Checking if the name field is filled out.
checkFieldValue(request.name)
# copy ConferenceForm/ProtoRPC Message into dict
data = ({field.name: getattr(request, field.name)
for field in request.all_fields()})
# Getting deleted because they are not part of the ndb model
del data['websafeKey']
del data['organizerDisplayName']
# add default values for those missing
for df in CONFERENCE_DEFAULTS:
if data[df] in (None, []):
data[df] = CONFERENCE_DEFAULTS[df]
setattr(request, df, CONFERENCE_DEFAULTS[df])
# convert dates TO strings using the Date objects
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 a Profile Key based on user ID and Conference ----
# Profile key
p_key = ndb.Key(Profile, user_id)
# allocate new Conference ID with Profile key as parent
c_id = Conference.allocate_ids(size=1, parent=p_key)[0]
# make Conference key using p_key and c_id
c_key = ndb.Key(Conference, c_id, parent=p_key)
# Update stored conference with profile and conference key
data['key'] = c_key
data['organizerUserId'] = request.organizerUserId = user_id
# create Conference, send email to organizer confirming
# creation of Conference & return (modified) ConferenceForm
Conference(**data).put()
# cron job
taskqueue.add(
params = {
'email' : user.email(),
'subject' : 'You Created a New Conference!',
'body' : 'Here are the details for your conference:',
'info' : repr(request)},
url = '/tasks/send_confirmation_email')
return request
示例15: _mockConferenceData
# 需要导入模块: from models import Conference [as 别名]
# 或者: from models.Conference import allocate_ids [as 别名]
def _mockConferenceData():
# 0. remove all user/conference/session
profiles = Profile.query()
for p in profiles:
p.key.delete()
conferences = Conference.query()
for c in conferences:
c.key.delete()
sessions = Session.query()
for s in sessions:
s.key.delete()
# 1. mock user profile
email = '[email protected]'
u_id = email # mock email as u_id
p_key = ndb.Key(Profile, u_id)
profile = p_key.get()
if not profile:
profile = Profile(
key=p_key,
displayName='Olala7846',
mainEmail=email,
teeShirtSize=str(TeeShirtSize.NOT_SPECIFIED),
)
profile.put()
# 2. mock 3 Conference under user
for i in range(1, 4):
c_id = Conference.allocate_ids(size=1, parent=p_key)[0]
c_key = ndb.Key(Conference, c_id, parent=p_key)
conference = Conference(
name='Pyconf{}'.format(i),
description='Python Conference 2015 - {}'.format(i),
organizerUserId=u_id,
topics=['Conputer Programming', 'Python'],
city='Taipei',
startDate=datetime.now(),
month=7,
endDate=datetime.now(),
maxAttendees=200,
seatsAvailable=200,
key=c_key,
)
conference.put()
# 3. mock 5 sessions under each conference
for j in range(1, 6):
s_id = Session.allocate_ids(size=1, parent=c_key)[0]
s_key = ndb.Key(Session, s_id, parent=c_key)
session = Session(
name='conference {} session {}'.format(i, j),
highlights='highlights about session {}'.format(j),
speakerName='Guido van Rossum {}'.format(j),
duration=90,
date=datetime.now(),
startTime=datetime.now().time(),
key=s_key,
)
session.put()