本文整理汇总了Python中models.Session.put方法的典型用法代码示例。如果您正苦于以下问题:Python Session.put方法的具体用法?Python Session.put怎么用?Python Session.put使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类models.Session
的用法示例。
在下文中一共展示了Session.put方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: createSession
# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import put [as 别名]
def createSession(self, request):
""" Creates Session from given SESSION_POST_REQUEST_FOR_CONFERENCE and returns a SessionForm."""
# (SessionForm, websafeConferenceKey) -- open only to the organizer of the conference
profile = self._getProfileFromUser()
conf = ndb.Key(urlsafe=request.websafeConferenceKey).get()
if not conf:
raise endpoints.NotFoundException(
'No conference found with key: %s' % request.websafeConferenceKey)
if conf.key.parent().get() != profile:
raise endpoints.UnauthorizedException('Session creation is open only to the organizer of the conference!')
# copy SESSION_POST_REQUEST_FOR_CONFERENCE/ProtoRPC Message into dict
data = {field.name: getattr(request, field.name) for field in request.all_fields()}
session = Session(name=data['name'],parent=conf.key)
# convert dates from strings to Date objects; set month based on start_date
if data['dateTime']:
session.date = data['dateTime'].date()
session.time = data['dateTime'].time()
if data['highlights']:
session.highlights = data['highlights']
if data['typeOfSession']:
session.typeOfSession = data['typeOfSession']
if data['duration']:
session.duration = data['duration']
if data['speakers']:
session.speakers = data['speakers']
session.put()
if data['speakers']:
session.speakers = data['speakers']
logging.debug("Creating session with speakers, adding task to taskqueue.", str(session))
taskqueue.add(url='/tasks/add_featured_speaker', params={'sessionKeyUrlSafe': session.key.urlsafe()})
return self._copySessionToForm(session)
示例2: _createSessionObject
# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import put [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)
示例3: save
# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import put [as 别名]
def save(self):
session = Session(
session_key = self.session_key,
session_data = self.encode(self._session),
expire_date = self.get_expiry_date()
)
session.put()
示例4: _createSessionObject
# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import put [as 别名]
def _createSessionObject(self, request):
"""Create or update Session object, returning ConferenceForm/request."""
# get user id
user = endpoints.get_current_user()
if not user:
raise endpoints.UnauthorizedException('Authorization required')
user_id = getUserId(user)
# check to make sure required fields are present
if not request.name:
raise endpoints.BadRequestException("Session 'name' field required")
if not request.conferenceId:
raise endpoints.BadRequestException("Session 'conferenceId' field required")
# check to make sure given conference is an actual conference
conference_key = ndb.Key(urlsafe=request.conferenceId)
if not conference_key:
raise endpoints.NotFoundException(
'No conference found with key: %s' % request.conferenceId)
# check to make sure user is owner of this conference
conference = conference_key.get()
if user_id != conference.organizerUserId:
raise endpoints.ForbiddenException(
'Only the owner can update the conference.')
# copy ConferenceForm/ProtoRPC Message into dict
data = {field.name: getattr(request, field.name) for field in request.all_fields()}
# 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]
# convert dates from strings to DateTime objects
if data['dateTime']:
data['dateTime'] = datetime.strptime(data['dateTime'][:16], "%Y-%m-%dT%H:%M")
# set seatsAvailable to be same as maxAttendees on creation
# it defaults to 0 if not provided in request
data["seatsAvailable"] = data["maxAttendees"]
# generate Session Key based on conference ID and Session
session_id = Session.allocate_ids(size=1, parent=conference_key)[0]
session_key = ndb.Key(Session, session_id, parent=conference_key)
data['key'] = session_key
# create Session & return (modified) ConferenceForm
newSession = Session(**data)
newSession.put()
# if speaker given, schedule Task to check for Featured Speaker
if data['speakerUserId']:
taskqueue.add(params={'websafeConferenceKey': conference_key.urlsafe(),
'speakerUserId': data['speakerUserId']},
url='/tasks/check_featured_speaker'
)
return self._copySessionToForm(newSession)
示例5: save
# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import put [as 别名]
def save(self, must_create=False):
if must_create and self.exists(self.session_key):
raise base.CreateError
session = Session(
key_name='k:' + self.session_key,
session_data = self.encode(self._session),
expire_date = self.get_expiry_date())
session.put()
示例6: process_event
# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import put [as 别名]
def process_event(event_file, user):
event_data = json.loads(event_file)
event_name = event_data['name']
event_place = event_data['place']
event_date_from = datetime.strptime(event_data['date_from'], '%Y-%m-%d').date()
event_date_to = datetime.strptime(event_data['date_to'], '%Y-%m-%d').date()
event_timezone = event_data['timezone']
if 'description' in event_data:
event_description = event_data['description']
else:
event_description = ''
ev = Event(owner=user,
name=event_name,
place=event_place,
date_from=event_date_from,
date_to=event_date_to,
timezone=event_timezone,
description=event_description,
data=event_data
)
ev.put()
for session in event_data['sessions']:
session_name = session['name']
session_room = session['room']
tr = Session(owner=user,
name=session_name,
room=session_room,
event=ev.key)
tr.put()
for talk in session['talks']:
talk_title = talk['title']
talk_authors = talk['authors']
talk_start = datetime.strptime(talk['start'], '%Y-%m-%d %H:%M')
talk_end = datetime.strptime(talk['end'], '%Y-%m-%d %H:%M')
if 'tags' in talk:
talk_tags = talk['tags']
else:
talk_tags = []
if 'abstract' in talk:
talk_abstract = talk['abstract']
else:
talk_abstract = ''
tk = Talk(owner=user,
session=tr.key,
title=talk_title,
authors=talk_authors,
start=talk_start,
end=talk_end,
tags=talk_tags,
abstract=talk_abstract
)
tk.put()
示例7: _createSessionObject
# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import put [as 别名]
def _createSessionObject(self, request, user=None):
"""Create Session object, returning SessionForm/request."""
user_id = getUserId(user)
# get Conference object from request; bail if not found
wck = request.websafeConferenceKey
c_key = ndb.Key(urlsafe=wck)
conf = c_key.get()
if not conf:
raise endpoints.NotFoundException(
'No conference found with key: %s' % wck)
# Check editing authorization. Creater and user match
if user_id != conf.organizerUserId:
raise endpoints.ForbiddenException(
'Only conference creator may add sessions')
if not request.name or not request.date or not request.startTime:
raise endpoints.BadRequestException(
"Session 'name', 'date', and 'startTime' fields required")
# copy SessionForm/ProtoRPC Message into dict
data = {field.name: getattr(request, field.name)
for field in request.all_fields()}
data['conferenceKey'] = wck
data.pop('websafeConferenceKey', None)
data.pop('websafeKey', None)
# convert date/time strings to Date/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'][:10], "%H:%M").time()
# Check date is within conference date range (if specified)
if conf.startDate and conf.endDate:
if data['date'] < conf.startDate or data['date'] > conf.endDate:
raise endpoints.BadRequestException(
"Session date is not within conference timeframe.")
# generate Session Key based on parent 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
# create Session & return (modified) SessionForm
sess = Session(**data)
sess.put()
# Send speaker names to taskqueue for processing featured speaker
for speaker in data['speaker']:
taskqueue.add(
url='/tasks/set_featured_speaker',
params={'speaker': speaker, 'websafeConferenceKey': wck}
)
return self._copySessionToForm(sess)
示例8: _createSessionObject
# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import put [as 别名]
def _createSessionObject(self, sessionForm):
"""Create Session object, returning SessionForm."""
# make sure user is authenticated
user = endpoints.get_current_user()
if not user:
raise endpoints.UnauthorizedException('Authorization required')
# get the conference
conf = ndb.Key(urlsafe=sessionForm.websafeConferenceKey).get()
if not conf:
raise endpoints.NotFoundException('No conference found with key: %s' % sessionForm.conferenceKey)
# check ownership
if getUserId(user) != conf.organizerUserId:
raise endpoints.ForbiddenException('Only the organizer of this conference can add sessions.')
# copy SessionForm/ProtoRPC Message into dict
data = formToDict(sessionForm, exclude=('websafeKey', 'websafeConferenceKey'))
# check required fields
for key in Session.required_fields_schema:
if not data[key]:
raise endpoints.BadRequestException("'%s' field is required to create a session." % key)
# convert date string to a datetime object.
try:
data['date'] = datetime.strptime(data['date'][:10], "%Y-%m-%d").date()
except (TypeError, ValueError):
raise endpoints.BadRequestException("Invalid date format. Please use 'YYYY-MM-DD'")
# convert date string to a time object. HH:MM
try:
data['startTime'] = datetime.strptime(data['startTime'][:5], "%H:%M").time()
except (TypeError, ValueError):
raise endpoints.BadRequestException("Invalid date format. Please use 'HH:MM'")
if data['duration'] <= 0:
raise endpoints.BadRequestException("Duration must be greater than zero")
if data['date'] < conf.startDate or data['date'] > conf.endDate:
raise endpoints.BadRequestException("Session must be within range of conference start and end date")
data['speaker'] = Speaker(name=data['speaker'])
# ask Datastore to allocate an ID.
s_id = Session.allocate_ids(size=1, parent=conf.key)[0]
# Datastore returns an integer ID that we can use to create a session key
data['key'] = ndb.Key(Session, s_id, parent=conf.key)
# Add session to datastore
session = Session(**data)
session.put()
# Add a task to check and update new featured speaker
taskqueue.add(
params={'websafeConferenceKey': conf.key.urlsafe(), 'speaker': session.speaker.name},
url='/tasks/set_featured_speaker'
)
return session.toForm()
示例9: _createSessionObject
# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import put [as 别名]
def _createSessionObject(self, request):
# Check to see if user is logged in
self._checkLoggedIn()
# Check to see if minimum, necessary information
# has been supplied in request
if not request.name:
raise endpoints.BadRequestException(
"Conference session 'name' field required")
if not request.speakerDisplayName:
raise endpoints.BadRequestException(
"Conference session 'speakerDisplayName' field required")
if not request.sessionType:
raise endpoints.BadRequestException(
"Conference session 'sessionType' field required")
# Check to make sure speaker has a profile: using displayName
self._checkSpeakerProfile(displayName=request.speakerDisplayName)
# copy ConferenceForm/ProtoRPC Message into dict
data = {field.name: getattr(request, field.name)
for field in request.all_fields()}
# Retrieve Conference by websafeConferenceKey
conference = self._getConferenceByKey(request.websafeConferenceKey)
# clean up and translate date fields
clean_data = self._cleanData(data=data)
# Check for legal owner
self._checkOwner(owner=conference.organizerUserId)
# Get Parent Key
parent_key = conference.key
# Set session as child of user supplied conference
# Associate data and put session object
session = Session(parent=parent_key, **clean_data)
session.put()
# Update featured speaker key in memcache
# Get the current speaker
speaker = session.speakerDisplayName
# Get the number of session hosted by current speaker
number_sessions = self._getNumberOfConferenceSessionBySpeaker(
speaker, request.websafeConferenceKey)
# If number of sessions greater than one set featured speaker
if number_sessions > 1:
taskqueue.add(
params={'speaker': speaker,
'websafeConferenceKey': request.websafeConferenceKey},
url='/tasks/set_featured_speaker')
return self._copySessionToForm(session=session)
示例10: createSession
# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import put [as 别名]
def createSession(self, request):
"""Create session in the conference identified by websafeConferenceKey."""
# Get Conference object from request and raise exception if not found
conf = ndb.Key(urlsafe=request.websafeConferenceKey).get()
if not conf:
raise endpoints.NotFoundException(
'No conference found with key: %s' % request.websafeConferenceKey)
if not isinstance(conf, Conference):
raise endpoints.BadRequestException('Key must refer to Conference')
# preload necessary data items
user = endpoints.get_current_user()
if not user:
raise endpoints.UnauthorizedException('Authorization required')
user_id = getUserId(user)
if user_id != conf.organizerUserId:
raise endpoints.UnauthorizedException("Only the user who created the conference can add sessions")
if not request.name:
raise endpoints.BadRequestException("Session 'name' is a required field")
if not request.speaker:
raise endpoints.BadRequestException("Session 'speaker' is a required field")
# Copying SessionForm/ProtoRPC Message into dictionary
# getattr is required to access the values
data = {field.name: getattr(request, field.name) for field in request.all_fields()}
del data['websafeConferenceKey']
del data['websafeKey']
# Parsing date strings to get Date objects
# The month is set based on start date
if data['date']:
data['date'] = datetime.strptime(data['date'][:10], "%Y-%m-%d").date()
else:
data['date'] = conf.startDate
if data['startTime']:
data['startTime'] = datetime.strptime(data['startTime'][:5], "%H:%M").time()
data['typeOfSession'] = str(data['typeOfSession'])
s_id = Session.allocate_ids(size=1, parent=conf.key)[0]
s_key = ndb.Key(Session, s_id, parent=conf.key)
data['key'] = s_key
session = Session(**data)
session.put()
taskqueue.add(params={'speaker': data['speaker'],
'wcsk': request.websafeConferenceKey},
url='/tasks/set_feature_session_announcement'
)
return self._copySessionToForm(session)
示例11: _createSessionObject
# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import put [as 别名]
def _createSessionObject(self, request):
"""Create or update Session object, returning SessionForm/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("Session 'name' field required.")
if not request.speakerName:
raise endpoints.BadRequestException("Session 'speakerName' field is required.")
# Get the existing conference
conf_key = ndb.Key(urlsafe=request.websafeConferenceKey)
conf = conf_key.get()
# If current User did not create the conference, user cannot create session
if conf.organizerUserId != user_id:
raise endpoints.UnauthorizedException("Must be the creator of the conference to make a session.")
# copy SessionForm/ProtoRPC Message into dict
data = {field.name: getattr(request, field.name) for field in request.all_fields()}
del data["websafeConferenceKey"]
del data["websafeSessionKey"]
# Convert date from string type to date format
if data["date"]:
data["date"] = datetime.strptime(data["date"][:10], "%Y-%m-%d").date()
# Convert startTime from string type to time format
if data["startTime"]:
data["startTime"] = datetime.strptime(data["startTime"][:5], "%H:%M").time()
# 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])
# Generate Session Key based on Conference Key
s_id = Session.allocate_ids(size=1, parent=conf_key)[0]
s_key = ndb.Key(Session, s_id, parent=conf_key)
print s_key
data["key"] = s_key
# create session
newSession = Session(**data)
# Save session
newSession.put()
taskqueue.add(params={"sessionKey": s_key.urlsafe()}, url="/tasks/set_featured_speaker", method="GET")
# Return SessionForm back to user
return self._copySessionToForm(newSession)
示例12: _createSessionObject
# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import put [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)
示例13: _createSessionObject
# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import put [as 别名]
def _createSessionObject(request, conference):
"""Create or update Session object, returning SessionForm/request."""
# preload necessary data items
if not request.name:
raise endpoints.BadRequestException("Session 'name' field required")
speaker_wskey = None
if not request.speakerWSKey:
if request.speakerName:
speaker = Speaker.query(Speaker.name == request.speakerName).get()
if speaker:
speaker_wskey = speaker.key.urlsafe()
else:
speaker_id = Speaker.allocate_ids(size=1)[0]
speaker_key = ndb.Key(Speaker, speaker_id)
speaker_wskey = speaker_key.urlsafe()
speaker = Speaker(**{'key': speaker_key,'name': request.speakerName})
speaker.put()
else:
raise endpoints.BadRequestException("Session speaker required")
else:
speaker_wskey = request.speakerWSKey
# copy SessionForm/ProtoRPC Message into dict
data = {field.name: getattr(request, field.name) for field in request.all_fields()}
del data['sessionWSKey']
del data['speakerWSKey']
del data['speakerName']
del data['conferenceWSKey']
del data['startDateHour']
print '1:' + str(data.keys())
# 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 dates from strings to Date objects; set month based on start_date
if data['startDate'] and isinstance(data['startDate'], types.StringType):
data['startDate'] = datetime.strptime(data['startDate'][:10], "%Y-%m-%d").datetime()
session_id = Session.allocate_ids(size=1, parent=conference.key)[0]
session_key = ndb.Key(Session, session_id, parent=conference.key)
data['key'] = session_key
data['speakerKey'] = speaker_wskey
# create Session, send email to organizer confirming creation of Session & return (modified) SessionForm
session = Session(**data)
session.put()
# taskqueue.add(params={'email': user.email(), 'conferenceInfo': repr(request)}, url='/tasks/send_confirmation_email')
return session
示例14: _create_session_object
# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import put [as 别名]
def _create_session_object(self, request):
"""Create or update Session object, returning SessionForm/request"""
user = endpoints.get_current_user()
if not user:
raise endpoints.UnauthorizedException("Authorization required")
# get Conference object from request; bail 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)
# Check if user is authorized to create sessions for this conference
user_id = get_user_id(user)
p_key = ndb.Key(Profile, user_id)
profile = p_key.get()
c_owner = conf.key.parent().get()
if profile is not c_owner:
raise endpoints.UnauthorizedException(
"Sessions can be only created by conference owner")
if not request.name:
raise endpoints.BadRequestException("Name field required")
if not request.speaker:
raise endpoints.BadRequestException("Speaker field required")
# copy SessionForm/ProtoRPC Message into dict
data = {field.name: getattr(request, field.name) for field in
request.all_fields()}
del data['websafeConferenceKey']
del data['websafeSessionKey']
# convert dates and times from strings to Date 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()
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
session = Session(**data)
session.put()
taskqueue.add(params={'speaker': request.speaker,
'websafeConferenceKey': request.websafeConferenceKey},
url='/tasks/set_featured_speaker')
return self._copy_session_to_form(session)
示例15: login
# 需要导入模块: from models import Session [as 别名]
# 或者: from models.Session import put [as 别名]
def login(self, user):
token = create_token(user.email)
session = Session(id=token)
session.token = token
session.user = user.key
session.put()
self.session["token"] = token
return