Python cherrypy.session() Examples
The following are 30
code examples of cherrypy.session().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
cherrypy
, or try the search function
.
Example #1
Source File: cptools.py From cherrypy with BSD 3-Clause "New" or "Revised" License | 7 votes |
def do_login(self, username, password, from_page='..', **kwargs): """Login. May raise redirect, or return True if request handled.""" response = cherrypy.serving.response error_msg = self.check_username_and_password(username, password) if error_msg: body = self.login_screen(from_page, username, error_msg) response.body = body if 'Content-Length' in response.headers: # Delete Content-Length header so finalize() recalcs it. del response.headers['Content-Length'] return True else: cherrypy.serving.request.login = username cherrypy.session[self.session_key] = username self.on_login(username) raise cherrypy.HTTPRedirect(from_page or '/')
Example #2
Source File: scoreboard_controller.py From SA-ctf_scoreboard with Creative Commons Zero v1.0 Universal | 6 votes |
def get_kv_lookup(self, lookup_file, namespace='lookup_editor', owner=None): ''' Get the contents of a KV store lookup. ''' try: if owner is None: owner = 'nobody' # Get the session key session_key = cherrypy.session.get('sessionKey') # Get the contents _, content = splunk.rest.simpleRequest('/servicesNS/' + owner + '/' + namespace + '/storage/collections/data/' + lookup_file, sessionKey=session_key, getargs={'output_mode': 'json'}) return content except: logger_admin.error('KV store lookup could not be loaded')
Example #3
Source File: sessions.py From cherrypy with BSD 3-Clause "New" or "Revised" License | 6 votes |
def generate_id(self): """Return a new session id.""" return binascii.hexlify(os.urandom(20)).decode('ascii')
Example #4
Source File: cptools.py From cherrypy with BSD 3-Clause "New" or "Revised" License | 6 votes |
def do_check(self): """Assert username. Raise redirect, or return True if request handled. """ sess = cherrypy.session request = cherrypy.serving.request response = cherrypy.serving.response username = sess.get(self.session_key) if not username: sess[self.session_key] = username = self.anonymous() self._debug_message('No session[username], trying anonymous') if not username: url = cherrypy.url(qs=request.query_string) self._debug_message( 'No username, routing to login_screen with from_page %(url)r', locals(), ) response.body = self.login_screen(url) if 'Content-Length' in response.headers: # Delete Content-Length header so finalize() recalcs it. del response.headers['Content-Length'] return True self._debug_message('Setting request.login to %(username)r', locals()) request.login = username self.on_check(username)
Example #5
Source File: sessions.py From cherrypy with BSD 3-Clause "New" or "Revised" License | 6 votes |
def save(self): """Save session data.""" try: # If session data has never been loaded then it's never been # accessed: no need to save it if self.loaded: t = datetime.timedelta(seconds=self.timeout * 60) expiration_time = self.now() + t if self.debug: cherrypy.log('Saving session %r with expiry %s' % (self.id, expiration_time), 'TOOLS.SESSIONS') self._save(expiration_time) else: if self.debug: cherrypy.log( 'Skipping save of session %r (no session loaded).' % self.id, 'TOOLS.SESSIONS') finally: if self.locked: # Always release the lock if the user didn't release it self.release_lock() if self.debug: cherrypy.log('Lock released after save.', 'TOOLS.SESSIONS')
Example #6
Source File: sessions.py From cherrypy with BSD 3-Clause "New" or "Revised" License | 6 votes |
def _load(self, path=None): assert self.locked, ('The session load without being locked. ' "Check your tools' priority levels.") if path is None: path = self._get_file_path() try: f = open(path, 'rb') try: return pickle.load(f) finally: f.close() except (IOError, EOFError): e = sys.exc_info()[1] if self.debug: cherrypy.log('Error loading the session pickle: %s' % e, 'TOOLS.SESSIONS') return None
Example #7
Source File: sessions.py From cherrypy with BSD 3-Clause "New" or "Revised" License | 6 votes |
def acquire_lock(self, path=None): """Acquire an exclusive lock on the currently-loaded session data.""" if path is None: path = self._get_file_path() path += self.LOCK_SUFFIX checker = locking.LockChecker(self.id, self.lock_timeout) while not checker.expired(): try: self.lock = zc.lockfile.LockFile(path) except zc.lockfile.LockError: time.sleep(0.1) else: break self.locked = True if self.debug: cherrypy.log('Lock acquired.', 'TOOLS.SESSIONS')
Example #8
Source File: sessions.py From cherrypy with BSD 3-Clause "New" or "Revised" License | 6 votes |
def save(): """Save any changed session data.""" if not hasattr(cherrypy.serving, 'session'): return request = cherrypy.serving.request response = cherrypy.serving.response # Guard against running twice if hasattr(request, '_sessionsaved'): return request._sessionsaved = True if response.stream: # If the body is being streamed, we have to save the data # *after* the response has been written out request.hooks.attach('on_end_request', cherrypy.session.save) else: # If the body is not being streamed, we save the data now # (so we can release the lock). if is_iterator(response.body): response.collapse_body() cherrypy.session.save()
Example #9
Source File: main.py From labs with MIT License | 6 votes |
def calculeaza(val1, operator, val2): """Solve an equation Grade 1.""" for key, value in cherrypy.session.items(): val1 = val1.replace(key, value) operator = operator.replace(key, value) val2 = val2.replace(key, value) try: if operator == "+": return str(int(val1) + int(val2)) elif operator == "-": return str(int(val1) - int(val2)) elif operator == "*": return str(int(val1) * int(val2)) elif operator == "/": return str(int(val1) / int(val2)) except ValueError: return "Respecta constrangerile pentru: {} {} {}".format( val1, operator, val2) except ZeroDivisionError: return "Div by zero"
Example #10
Source File: cptools.py From opsbro with MIT License | 6 votes |
def do_login(self, username, password, from_page='..', **kwargs): """Login. May raise redirect, or return True if request handled.""" response = cherrypy.serving.response error_msg = self.check_username_and_password(username, password) if error_msg: body = self.login_screen(from_page, username, error_msg) response.body = body if "Content-Length" in response.headers: # Delete Content-Length header so finalize() recalcs it. del response.headers["Content-Length"] return True else: cherrypy.serving.request.login = username cherrypy.session[self.session_key] = username self.on_login(username) raise cherrypy.HTTPRedirect(from_page or "/")
Example #11
Source File: sessions.py From opsbro with MIT License | 6 votes |
def save(self): """Save session data.""" try: # If session data has never been loaded then it's never been # accessed: no need to save it if self.loaded: t = datetime.timedelta(seconds=self.timeout * 60) expiration_time = self.now() + t if self.debug: cherrypy.log('Saving session %r with expiry %s' % (self.id, expiration_time), 'TOOLS.SESSIONS') self._save(expiration_time) else: if self.debug: cherrypy.log( 'Skipping save of session %r (no session loaded).' % self.id, 'TOOLS.SESSIONS') finally: if self.locked: # Always release the lock if the user didn't release it self.release_lock() if self.debug: cherrypy.log('Lock released after save.', 'TOOLS.SESSIONS')
Example #12
Source File: sessions.py From opsbro with MIT License | 6 votes |
def _load(self, path=None): assert self.locked, ("The session load without being locked. " "Check your tools' priority levels.") if path is None: path = self._get_file_path() try: f = open(path, "rb") try: return pickle.load(f) finally: f.close() except (IOError, EOFError): e = sys.exc_info()[1] if self.debug: cherrypy.log("Error loading the session pickle: %s" % e, 'TOOLS.SESSIONS') return None
Example #13
Source File: __init__.py From ldapcherry with MIT License | 6 votes |
def _selfmodify(self, params): cherrypy.log.error( msg="modify user form attributes: " + str(params), severity=logging.DEBUG ) sess = cherrypy.session username = sess.get(SESSION_KEY, None) badd = self._modify_attrs( params, self.attributes.get_selfattributes(), username, ) cherrypy.log.error( msg="user '" + username + "' modified his attributes", severity=logging.INFO ) cherrypy.log.error( msg="user '" + username + "' attributes: " + str(badd), severity=logging.DEBUG )
Example #14
Source File: __init__.py From ldapcherry with MIT License | 6 votes |
def index(self): """main page rendering """ self._check_auth(must_admin=False) is_admin = self._check_admin() sess = cherrypy.session user = sess.get(SESSION_KEY, None) if self.auth_mode == 'none': user_attrs = None else: user_attrs = self._get_user(user) attrs_list = self.attributes.get_search_attributes() return self.temp['index.tmpl'].render( is_admin=is_admin, attrs_list=attrs_list, searchresult=user_attrs, notifications=self._empty_notification(), )
Example #15
Source File: sessions.py From opsbro with MIT License | 5 votes |
def load(self): """Copy stored session data into this session instance.""" data = self._load() # data is either None or a tuple (session_data, expiration_time) if data is None or data[1] < self.now(): if self.debug: cherrypy.log('Expired session %r, flushing data.' % self.id, 'TOOLS.SESSIONS') self._data = {} else: if self.debug: cherrypy.log('Data loaded for session %r.' % self.id, 'TOOLS.SESSIONS') self._data = data[0] self.loaded = True # Stick the clean_thread in the class, not the instance. # The instances are created and destroyed per-request. cls = self.__class__ if self.clean_freq and not cls.clean_thread: # clean_up is an instancemethod and not a classmethod, # so that tool config can be accessed inside the method. t = cherrypy.process.plugins.Monitor( cherrypy.engine, self.clean_up, self.clean_freq * 60, name='Session cleanup') t.subscribe() cls.clean_thread = t t.start() if self.debug: cherrypy.log('Started cleanup thread.', 'TOOLS.SESSIONS')
Example #16
Source File: sessions.py From opsbro with MIT License | 5 votes |
def _get_file_path(self): f = os.path.join(self.storage_path, self.SESSION_PREFIX + self.id) if not os.path.abspath(f).startswith(self.storage_path): raise cherrypy.HTTPError(400, "Invalid session id in cookie.") return f
Example #17
Source File: sessions.py From opsbro with MIT License | 5 votes |
def release_lock(self): """Release the lock on the currently-loaded session data.""" self.locks[self.id].release() self.locked = False
Example #18
Source File: sessions.py From opsbro with MIT License | 5 votes |
def delete(self): """Delete stored session data.""" self._delete() if self.debug: cherrypy.log('Deleted session %s.' % self.id, 'TOOLS.SESSIONS') # -------------------- Application accessor methods -------------------- #
Example #19
Source File: sessions.py From opsbro with MIT License | 5 votes |
def generate_id(self): """Return a new session id.""" return random20()
Example #20
Source File: sessions.py From opsbro with MIT License | 5 votes |
def _regenerate(self): if self.id is not None: if self.debug: cherrypy.log( 'Deleting the existing session %r before ' 'regeneration.' % self.id, 'TOOLS.SESSIONS') self.delete() old_session_was_locked = self.locked if old_session_was_locked: self.release_lock() if self.debug: cherrypy.log('Old lock released.', 'TOOLS.SESSIONS') self.id = None while self.id is None: self.id = self.generate_id() # Assert that the generated id is not already stored. if self._exists(): self.id = None if self.debug: cherrypy.log('Set id to generated %s.' % self.id, 'TOOLS.SESSIONS') if old_session_was_locked: self.acquire_lock() if self.debug: cherrypy.log('Regenerated lock acquired.', 'TOOLS.SESSIONS')
Example #21
Source File: sessions.py From opsbro with MIT License | 5 votes |
def now(self): """Generate the session specific concept of 'now'. Other session providers can override this to use alternative, possibly timezone aware, versions of 'now'. """ return datetime.datetime.now()
Example #22
Source File: sessions.py From cherrypy with BSD 3-Clause "New" or "Revised" License | 5 votes |
def now(self): """Generate the session specific concept of 'now'. Other session providers can override this to use alternative, possibly timezone aware, versions of 'now'. """ return datetime.datetime.now()
Example #23
Source File: sessions.py From cherrypy with BSD 3-Clause "New" or "Revised" License | 5 votes |
def id(self): """Return the current session id.""" return self._id
Example #24
Source File: sessions.py From opsbro with MIT License | 5 votes |
def _save(self, expiration_time): assert self.locked, ("The session was saved without being locked. " "Check your tools' priority levels.") f = open(self._get_file_path(), "wb") try: pickle.dump((self._data, expiration_time), f, self.pickle_protocol) finally: f.close()
Example #25
Source File: sessions.py From opsbro with MIT License | 5 votes |
def _delete(self): assert self.locked, ("The session deletion without being locked. " "Check your tools' priority levels.") try: os.unlink(self._get_file_path()) except OSError: pass
Example #26
Source File: sessions.py From opsbro with MIT License | 5 votes |
def release_lock(self, path=None): """Release the lock on the currently-loaded session data.""" self.lock.release() self.lock.remove() self.locked = False
Example #27
Source File: sessions.py From opsbro with MIT License | 5 votes |
def clean_up(self): """Clean up expired sessions.""" now = self.now() # Iterate over all session files in self.storage_path for fname in os.listdir(self.storage_path): if (fname.startswith(self.SESSION_PREFIX) and not fname.endswith(self.LOCK_SUFFIX)): # We have a session file: lock and load it and check # if it's expired. If it fails, nevermind. path = os.path.join(self.storage_path, fname) self.acquire_lock(path) if self.debug: # This is a bit of a hack, since we're calling clean_up # on the first instance rather than the entire class, # so depending on whether you have "debug" set on the # path of the first session called, this may not run. cherrypy.log('Cleanup lock acquired.', 'TOOLS.SESSIONS') try: contents = self._load(path) # _load returns None on IOError if contents is not None: data, expiration_time = contents if expiration_time < now: # Session expired: deleting it os.unlink(path) finally: self.release_lock(path)
Example #28
Source File: sessions.py From opsbro with MIT License | 5 votes |
def _exists(self): # Select session data from table self.cursor.execute('select data, expiration_time from session ' 'where id=%s', (self.id,)) rows = self.cursor.fetchall() return bool(rows)
Example #29
Source File: sessions.py From opsbro with MIT License | 5 votes |
def release_lock(self): """Release the lock on the currently-loaded session data.""" # We just close the cursor and that will remove the lock # introduced by the "for update" clause self.cursor.close() self.locked = False
Example #30
Source File: sessions.py From opsbro with MIT License | 5 votes |
def _load(self): # Select session data from table self.cursor.execute('select data, expiration_time from session ' 'where id=%s', (self.id,)) rows = self.cursor.fetchall() if not rows: return None pickled_data, expiration_time = rows[0] data = pickle.loads(pickled_data) return data, expiration_time