本文整理汇总了Python中models.Session类的典型用法代码示例。如果您正苦于以下问题:Python Session类的具体用法?Python Session怎么用?Python Session使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Session类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _createSessionObject
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: _getSessions
def _getSessions(self, request):
"""Return sessions by conference and optionally filter by typeOfSession or duartion or date.
Or return sessions by speaker."""
# Get conference
if hasattr(request, 'websafeConferenceKey') and request.websafeConferenceKey:
urlkey = request.websafeConferenceKey
conf_key = ndb.Key(urlsafe = urlkey)
conf = conf_key.get()
# create ancestor query for all key matches for this user
sessions = Session.query(ancestor = conf_key)
# if typeOfSession has been specified, filter by that
if hasattr(request, 'typeOfSession') and request.typeOfSession:
sessions = sessions.filter(Session.typeOfSession == request.typeOfSession)
# if duration has been specified, filter by that
if hasattr(request, 'duration') and request.duration:
sessions = sessions.filter(Session.duration <= int(request.duration))
sessions = sessions.filter(Session.duration > 0)
# if date has been specified, filter by that
if hasattr(request, 'date') and request.date:
sessions = sessions.filter(Session.date == datetime.strptime(request.date[:10], "%Y-%m-%d").date())
elif request.speaker:
sessions = Session.query()
sessions = sessions.filter(Session.speaker == request.speaker)
return SessionForms(
items=[self._copySessionToForm(session) for session in sessions]
)
示例3: post
def post(self, id = None):
request = self.wsgi_request
response = self.wsgi_response
c = self.context
param_dict = dict(
title = request.params.title,
conf_id = request.params.conf_id,
desc = request.params.desc,
venue = request.params.venue,
talk_type = request.params.talk_type,
start_date = parse(request.params.start_date),
end_date = parse(request.params.end_date),
duration = request.params.duration,
speaker_title = request.params.speaker_title)
content = param_dict
session = Session(**param_dict)
session = session.save()
conf = Conference.get(session.conf_id)
if conf:
conf.add_session(session)
self.set_body(session.to_json())
response.headers['content-type'] = 'application/json'
return self.render()
示例4: createSession
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)
示例5: save
def save(request):
results = simplejson.loads(request.POST['results'])
session_key = request.session.session_key #request.COOKIES[settings.SESSION_COOKIE_NAME]
session = Session(key=session_key, global_time=time())
session.save()
# Convert user results to Result table row
db_results = []
for result in results:
db_result = Result(
session = session,
time = result['time'],
selection = result['selection'],
)
db_result.image_id = result['id']
db_results.append(db_result)
try:
# This could be done better with a transaction
for db_result in db_results:
db_result.save()
except Exception as e:
print e
pass
return HttpResponseRedirect('/static/thankyou.html')
示例6: _cacheFeaturedSpeaker
def _cacheFeaturedSpeaker(session_key):
"""Assign Featured Speaker to memcache; used by getFeaturedSpeaker"""
# Use the urlsafe key to grab the session key
session = ndb.Key(urlsafe=session_key).get()
# Set the key for the memcache based on the confKey
featured = 'fs_' + str(session.key.parent().urlsafe())
print 'In cacheFeaturedSpeaker'
# Get all of the sessions for the conference
sessions = Session.query(ancestor=session.key.parent()).fetch()
count = 0
# Iterate through the sessions to find the speaker with the most sessions
for sess in sessions:
spk_sess = Session.query(ancestor=session.key.parent()).filter(Session.speaker==sess.speaker)
spk_count = spk_sess.count()
if spk_count > count:
count = spk_count
# Save the speaker and sessions for the speaker with the most
featured_speaker = sess.speaker
fs_sessions = spk_sess
# Grab the speaker
speaker = ndb.Key(urlsafe=featured_speaker).get()
# Set the speaker name and their sessions in a string
fs_data = {}
fs_data['name'] = speaker.name
fs_data['sessions'] = []
for sess in fs_sessions:
fs_data['sessions'].append(sess.name)
mem_val = json.dumps(fs_data)
# Set the created json string in memcache
memcache.set(key=featured, value=fs_data)
示例7: getQueryProblem
def getQueryProblem(self, request):
# make sure user is Authorized
user = endpoints.get_current_user()
if not user:
raise endpoints.UnauthorizedException('Authorization required')
# create query all non-workshop sessions before 7pm
# User would set Equal_to_Type = False, meaning they don't want that type
# User would set Before_OR_After = Before(string), and set the starttime to 7pm.
if request.Before_OR_After == "Before" :
Sessions = Session.query(Session.startTime <= request.startTime)
Sessions = Sessions.order(Session.startTime)
temp = []
for sess in Sessions:
if request.typeOfSession in sess.typeOfSession and request.matchSessionType:
temp.append(sess)
elif request.typeOfSession not in sess.typeOfSession and not request.matchSessionType:
temp.append(sess)
Sessions = temp
else:
Sessions = Session.query(Session.startTime >= request.startTime)
Sessions = Sessions.order(Session.startTime)
temp = []
for sess in Sessions:
if request.typeOfSession in sess.typeOfSession and request.matchSessionType:
temp.append(sess)
elif request.typeOfSession not in sess.typeOfSession and not request.matchSessionType:
temp.append(sess)
Sessions = temp
return SessionForms(
items=[self._copySessionToForm(sess) for sess in Sessions]
)
示例8: addFeaturedSession
def addFeaturedSession(speaker, sessionName, confKey):
"""
This is an task that can add a session into the
FeaturedSpeakerQueryForm in memcache
"""
if not speaker:
return
c_key = ndb.Key(urlsafe=confKey)
speakerSessionQuant = Session.query(
ancestor=c_key).filter(Session.speaker == speaker).count()
if speakerSessionQuant > 1:
cacheForm = memcache.get(MEMCACHE_FEATUREDSPEAKER_KEY)
# if the input speaker is the featured speaker, we add the session
# to the featured sessions list and save it to memcache
if cacheForm and cacheForm.featuredSpeaker == speaker:
cacheForm.featuredSessions.append(sessionName)
memcache.set(MEMCACHE_FEATUREDSPEAKER_KEY, cacheForm)
else:
# if the input speaker is not featured speaker, we have to
# scan the conference and add associated sessions
ancestor_key = ndb.Key(urlsafe=confKey)
sessions = Session.query(ancestor=ancestor_key).fetch()
featuredSessions = []
for session in sessions:
if session.speaker == speaker:
featuredSessions.append(session.name)
cacheForm = FeaturedSpeakerQueryForm(
featuredSpeaker=speaker,
featuredSessions=featuredSessions
)
memcache.set(MEMCACHE_FEATUREDSPEAKER_KEY, cacheForm)
示例9: update_monthly_games_played
def update_monthly_games_played():
gc = gspread.login('[email protected]', 'muatkienjwxfpnxn')
player_cell_locations = {'thewarmth00':'B51',
'rob_chainsaw':'B53',
'mashley93':'B55',
'peachy36west':'B57',
'm_sibs':'B59',
'rc_van':'B61',
'soviet_canuck':'B63',
'undertheblanket':'B65',
'vsmewen':'B67',
'hokagesama1':'B69',
'lnferno31':'H86'}
sheet = gc.open_by_key('0Ak-m4uT6aXL1dExuUHdLV0x2aTNFSGNRMTV2WWdLX2c').get_worksheet(9)
session = Session()
our_players = session.query(Player).all()
for player in our_players:
cell_location = player_cell_locations[player.username.lower()]
games_played = len(session.query(GamePlayed).filter_by(player_id=player.id).all())
value = sheet.acell(cell_location).value
sheet.update_acell(cell_location, str(games_played))
if sheet.acell(cell_location).value != value:
pass
else:
pass
示例10: getFeaturedSpeaker
def getFeaturedSpeaker(self, request):
"""Returns the sessions of the featured speaker"""
# try to get data from memcache
data = memcache.get(MEMCACHE_FEATURED_SPEAKER_KEY)
sessions = []
sessionNames = []
speaker = None
if data and data.has_key('speaker') and data.has_key('sessionNames'):
speaker = data['speaker']
sessionNames = data['sessionNames']
# if data is not on memcache, get speaker from upcoming session
else:
nextSession = Session.query(Session.date >= datetime.now()).order(Session.date, Session.startTime).get()
if nextSession:
speaker = nextSession.speaker
sessions = Session.query(Session.speaker == speaker)
sessionNames = [session.name for session in sessions]
# fill speaker form
speaker_form = SpeakerForm()
for field in speaker_form.all_fields():
if field.name == 'sessionNames':
setattr(speaker_form, field.name, sessionNames)
elif field.name == 'speaker':
setattr(speaker_form, field.name, speaker)
speaker_form.check_initialized()
return speaker_form
示例11: post
def post(self):
game_id = self.get_argument('game_id')
game_password = self.get_argument('game_password')
username = self.get_argument('username')
session = Session()
try:
user = get_user(username)
game = get_game(game_id=game_id, game_password=game_password)
try:
usergame = get_usergame(user.id, game.id)
if usergame is not None:
response_dict = get_response_dict(True)
except NoResultFound:
if not game.started:
game.add_user(user)
response_dict = get_response_dict(True)
else:
response_dict = get_response_dict(False, 'Game has started; you cannot join.')
except Exception as e:
session.rollback()
response_dict = get_response_dict(False, e.message)
finally:
Session.remove()
self.finish(simplejson.dumps(response_dict))
示例12: add_session
def add_session(request, instance_name):
start_date = request.POST['start_date']
end_date = request.POST['end_date']
instance = get_object_or_404(ExperimentInstance, name=instance_name)
session = Session(instance=instance, start_date=start_date, end_date=end_date)
session.save()
return JsonResponse({'ok': 'ok'})
示例13: _getConferenceSessions
def _getConferenceSessions(self, request, typeOfSession=None, speaker=None):
"""Its a multi purpose method which will return session forms for below three combination
- websafeConferenceKey
- websafeConferenceKey with typeOfSession
- speaker """
wsck = request.websafeConferenceKey
# If type of session provided without conference key then its an error
if typeOfSession and not wsck:
raise endpoints.BadRequestException("If typeOfSession given then confernce key should also be provided.")
if wsck:
# if conf key availabe then get all its child sessions
conf = ndb.Key(urlsafe=wsck).get()
conf_key = conf.key
if not conf:
raise endpoints.NotFoundException('conference is invalid')
sessions = Session.query(ancestor=conf_key)
# filter type of session if provided
if typeOfSession is not None:
sessions = sessions.filter(Session.typeOfSession == typeOfSession)
else: # if conf key is none then filter by speaker only
sessions = Session.query(Session.speaker == speaker)
return SessionForms(
sessions = [self._copySessionToForm(session)for session in sessions])
示例14: NonWorkshopSessionsBefore7pm
def NonWorkshopSessionsBefore7pm(self, request):
"""Return Non-Workshop Sessions Before 7pm."""
# make sure user is authed
user = endpoints.get_current_user()
if not user:
raise endpoints.UnauthorizedException('Authorization required')
# user_id = getUserId(user)
theStartTime = datetime.strptime("19:00", "%H:%M").time()
# idea from reading answers from Tim Hoffman
# (http://stackoverflow.com/users/1201324/tim-hoffman)
# and Brent Washburne
# (http://stackoverflow.com/users/584846/brent-washburne)
# specifically Brent's answer here:
# https://stackoverflow.com/questions/33549573/combining-results-of-multiple-ndb-inequality-queries
# create two separate inequality queries and get the keys from each
# then use set.intersection method to get the
# intersection of the two sets
query1 = Session.query(Session.typeOfSession != "Workshop").fetch(
keys_only=True)
query2 = Session.query(Session.startTime < theStartTime).fetch(
keys_only=True)
sessions = ndb.get_multi(set(query1).intersection(query2))
# return set of SessionForm objects per Conference
return SessionForms(
items=[self._copySessionToForm(session) for session in sessions]
)
示例15: Post
class Post(bourbon.ModelInterface):
@staticmethod
def all():
sess = Session()
return [post.id for post in sess.query(PostModel).all()]
@staticmethod
def open(identifier):
self = Post()
self.sess = Session()
self.post = self.sess.query(PostModel).filter_by(id=identifier).scalar()
if self.post is None:
self.post = PostModel()
return self
@staticmethod
def stat(identifier):
post = Post.open(identifier)
return bourbon.Stat.as_file(len(post.read())).as_dict()
def close(self):
self.sess.add(self.post)
self.sess.commit()
del self.sess
del self.post
return True
def read(self):
return self.post.text
def write(self, data):
self.post.text = data
def getattr(self):
return bourbon.FILE