desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Check timeout on all responses. (Internal)'
| def run(self):
| for (req, resp) in self.servings:
resp.check_timeout()
|
'Remove all attributes of self.'
| def clear(self):
| self.__dict__.clear()
|
'Log the given message to the app.log or global log as appropriate.'
| def __call__(self, *args, **kwargs):
| if (hasattr(request, 'app') and hasattr(request.app, 'log')):
log = request.app.log
else:
log = self
return log.error(*args, **kwargs)
|
'Log an access message to the app.log or global log as appropriate.'
| def access(self):
| try:
return request.app.log.access()
except AttributeError:
return _cplogging.LogManager.access(self)
|
'Update self from a dict, file or filename.'
| def update(self, config):
| if isinstance(config, basestring):
cherrypy.engine.autoreload.files.add(config)
reprconf.Config.update(self, config)
|
'Update self from a dict.'
| def _apply(self, config):
| if isinstance(config.get('global', None), dict):
if (len(config) > 1):
cherrypy.checker.global_config_contained_paths = True
config = config['global']
if ('tools.staticdir.dir' in config):
config['tools.staticdir.section'] = 'global'
reprconf.Config._apply(self, config)
|
'Decorator for page handlers to set _cp_config.'
| def __call__(self, *args, **kwargs):
| if args:
raise TypeError('The cherrypy.config decorator does not accept positional arguments; you must use keyword arguments.')
def tool_decorator(f):
if (not hasattr(f, '_cp_config')):
f._cp_config = {}
for (k, v) in kwargs.items():
... |
'Merge the given config into self.config.'
| def merge(self, config):
| _cpconfig.merge(self.config, config)
self.namespaces(self.config.get('/', {}))
|
'Return the most-specific value for key along path, or default.'
| def find_config(self, path, key, default=None):
| trail = (path or '/')
while trail:
nodeconf = self.config.get(trail, {})
if (key in nodeconf):
return nodeconf[key]
lastslash = trail.rfind('/')
if (lastslash == (-1)):
break
elif ((lastslash == 0) and (trail != '/')):
trail = '/'
... |
'Create and return a Request and Response object.'
| def get_serving(self, local, remote, scheme, sproto):
| req = self.request_class(local, remote, scheme, sproto)
req.app = self
for (name, toolbox) in self.toolboxes.items():
req.namespaces[name] = toolbox
resp = self.response_class()
cherrypy.serving.load(req, resp)
cherrypy.engine.publish('acquire_thread')
cherrypy.engine.publish('before... |
'Release the current serving (request and response).'
| def release_serving(self):
| req = cherrypy.serving.request
cherrypy.engine.publish('after_request')
try:
req.close()
except:
cherrypy.log(traceback=True, severity=40)
cherrypy.serving.clear()
|
'Mount a new app from a root object, script_name, and config.
root
An instance of a "controller class" (a collection of page
handler methods) which represents the root of the application.
This may also be an Application instance, or None if using
a dispatcher other than the default.
script_name
A string containing the ... | def mount(self, root, script_name='', config=None):
| if (script_name is None):
raise TypeError("The 'script_name' argument may not be None. Application objects may, however, possess a script_name of None (in order to inpect the WSGI environ for SCRIPT_NAME upon each request). ... |
'Mount a wsgi callable at the given script_name.'
| def graft(self, wsgi_callable, script_name=''):
| script_name = script_name.rstrip('/')
self.apps[script_name] = wsgi_callable
|
'The script_name of the app at the given path, or None.
If path is None, cherrypy.request is used.'
| def script_name(self, path=None):
| if (path is None):
try:
request = cherrypy.serving.request
path = httputil.urljoin(request.script_name, request.path_info)
except AttributeError:
return None
while True:
if (path in self.apps):
return path
if (path == ''):
... |
'Modify cherrypy.response status, headers, and body to represent self.
CherryPy uses this internally, but you can also use it to create an
HTTPRedirect object and set its output without *raising* the exception.'
| def set_response(self):
| import cherrypy
response = cherrypy.serving.response
response.status = status = self.status
if (status in (300, 301, 302, 303, 307)):
response.headers['Content-Type'] = 'text/html;charset=utf-8'
response.headers['Location'] = self.urls[0]
msg = {300: "This resource can b... |
'Use this exception as a request.handler (raise self).'
| def __call__(self):
| raise self
|
'Modify cherrypy.response status, headers, and body to represent self.
CherryPy uses this internally, but you can also use it to create an
HTTPError object and set its output without *raising* the exception.'
| def set_response(self):
| import cherrypy
response = cherrypy.serving.response
clean_headers(self.code)
response.status = self.status
tb = None
if cherrypy.serving.request.show_tracebacks:
tb = format_exc()
response.headers['Content-Type'] = 'text/html;charset=utf-8'
response.headers.pop('Content-Length',... |
'Use this exception as a request.handler (raise self).'
| def __call__(self):
| raise self
|
'Register this object as a (multi-channel) listener on the bus.'
| def subscribe(self):
| for channel in self.bus.listeners:
method = getattr(self, channel, None)
if (method is not None):
self.bus.subscribe(channel, method)
|
'Unregister this object as a listener on the bus.'
| def unsubscribe(self):
| for channel in self.bus.listeners:
method = getattr(self, channel, None)
if (method is not None):
self.bus.unsubscribe(channel, method)
|
'Subscribe self.handlers to signals.'
| def subscribe(self):
| for (sig, func) in self.handlers.items():
try:
self.set_handler(sig, func)
except ValueError:
pass
|
'Unsubscribe self.handlers from signals.'
| def unsubscribe(self):
| for (signum, handler) in self._previous_handlers.items():
signame = self.signals[signum]
if (handler is None):
self.bus.log(('Restoring %s handler to SIG_DFL.' % signame))
handler = _signal.SIG_DFL
else:
self.bus.log(('Restoring %s handle... |
'Subscribe a handler for the given signal (number or name).
If the optional \'listener\' argument is provided, it will be
subscribed as a listener for the given signal\'s channel.
If the given signal name or number is not available on the current
platform, ValueError is raised.'
| def set_handler(self, signal, listener=None):
| if isinstance(signal, basestring):
signum = getattr(_signal, signal, None)
if (signum is None):
raise ValueError(('No such signal: %r' % signal))
signame = signal
else:
try:
signame = self.signals[signal]
except KeyError:
raise... |
'Python signal handler (self.set_handler subscribes it for you).'
| def _handle_signal(self, signum=None, frame=None):
| signame = self.signals[signum]
self.bus.log(('Caught signal %s.' % signame))
self.bus.publish(signame)
|
'Restart if daemonized, else exit.'
| def handle_SIGHUP(self):
| if os.isatty(sys.stdin.fileno()):
self.bus.log('SIGHUP caught but not daemonized. Exiting.')
self.bus.exit()
else:
self.bus.log('SIGHUP caught while daemonized. Restarting.')
self.bus.restart()
|
'Start our callback in its own background thread.'
| def start(self):
| if (self.frequency > 0):
threadname = (self.name or self.__class__.__name__)
if (self.thread is None):
self.thread = BackgroundTask(self.frequency, self.callback, bus=self.bus)
self.thread.setName(threadname)
self.thread.start()
self.bus.log(('Started ... |
'Stop our callback\'s background task thread.'
| def stop(self):
| if (self.thread is None):
self.bus.log((('No thread running for %s.' % self.name) or self.__class__.__name__))
else:
if (self.thread is not threading.currentThread()):
name = self.thread.getName()
self.thread.cancel()
if (not get_daemon(self.thread... |
'Stop the callback\'s background task thread and restart it.'
| def graceful(self):
| self.stop()
self.start()
|
'Start our own background task thread for self.run.'
| def start(self):
| if (self.thread is None):
self.mtimes = {}
Monitor.start(self)
|
'Return a Set of sys.modules filenames to monitor.'
| def sysfiles(self):
| files = set()
for (k, m) in sys.modules.items():
if re.match(self.match, k):
if (hasattr(m, '__loader__') and hasattr(m.__loader__, 'archive')):
f = m.__loader__.archive
else:
f = getattr(m, '__file__', None)
if ((f is not None) and... |
'Reload the process if registered files have been modified.'
| def run(self):
| for filename in (self.sysfiles() | self.files):
if filename:
if filename.endswith('.pyc'):
filename = filename[:(-1)]
oldtime = self.mtimes.get(filename, 0)
if (oldtime is None):
continue
try:
mtime = os.stat(fil... |
'Run \'start_thread\' listeners for the current thread.
If the current thread has already been seen, any \'start_thread\'
listeners will not be run again.'
| def acquire_thread(self):
| thread_ident = get_thread_ident()
if (thread_ident not in self.threads):
i = (len(self.threads) + 1)
self.threads[thread_ident] = i
self.bus.publish('start_thread', i)
|
'Release the current thread and run \'stop_thread\' listeners.'
| def release_thread(self):
| thread_ident = get_thread_ident()
i = self.threads.pop(thread_ident, None)
if (i is not None):
self.bus.publish('stop_thread', i)
|
'Release all threads and run all \'stop_thread\' listeners.'
| def stop(self):
| for (thread_ident, i) in self.threads.items():
self.bus.publish('stop_thread', i)
self.threads.clear()
|
'Append the current exception to self.'
| def handle_exception(self):
| self._exceptions.append(sys.exc_info()[1])
|
'Return a list of seen exception instances.'
| def get_instances(self):
| return self._exceptions[:]
|
'Add the given callback at the given channel (if not present).'
| def subscribe(self, channel, callback, priority=None):
| if (channel not in self.listeners):
self.listeners[channel] = set()
self.listeners[channel].add(callback)
if (priority is None):
priority = getattr(callback, 'priority', 50)
self._priorities[(channel, callback)] = priority
|
'Discard the given callback (if present).'
| def unsubscribe(self, channel, callback):
| listeners = self.listeners.get(channel)
if (listeners and (callback in listeners)):
listeners.discard(callback)
del self._priorities[(channel, callback)]
|
'Return output of all subscribers for the given channel.'
| def publish(self, channel, *args, **kwargs):
| if (channel not in self.listeners):
return []
exc = ChannelFailures()
output = []
items = [(self._priorities[(channel, listener)], listener) for listener in self.listeners[channel]]
try:
items.sort(key=(lambda item: item[0]))
except TypeError:
items.sort()
for (priori... |
'An atexit handler which asserts the Bus is not running.'
| def _clean_exit(self):
| if (self.state != states.EXITING):
warnings.warn(('The main thread is exiting, but the Bus is in the %r state; shutting it down automatically now. You must either call bus.block() after start(), or call bus.exit() before ... |
'Start all services.'
| def start(self):
| atexit.register(self._clean_exit)
self.state = states.STARTING
self.log('Bus STARTING')
try:
self.publish('start')
self.state = states.STARTED
self.log('Bus STARTED')
except (KeyboardInterrupt, SystemExit):
raise
except:
self.log('Shutting down ... |
'Stop all services and prepare to exit the process.'
| def exit(self):
| exitstate = self.state
try:
self.stop()
self.state = states.EXITING
self.log('Bus EXITING')
self.publish('exit')
self.log('Bus EXITED')
except:
os._exit(70)
if (exitstate == states.STARTING):
os._exit(70)
|
'Restart the process (may close connections).
This method does not restart the process from the calling thread;
instead, it stops the bus and asks the main thread to call execv.'
| def restart(self):
| self.execv = True
self.exit()
|
'Advise all services to reload.'
| def graceful(self):
| self.log('Bus graceful')
self.publish('graceful')
|
'Wait for the EXITING state, KeyboardInterrupt or SystemExit.
This function is intended to be called only by the main thread.
After waiting for the EXITING state, it also waits for all threads
to terminate, and then calls os.execv if self.execv is True. This
design allows another thread to call bus.restart, yet have th... | def block(self, interval=0.1):
| try:
self.wait(states.EXITING, interval=interval, channel='main')
except (KeyboardInterrupt, IOError):
self.log('Keyboard Interrupt: shutting down bus')
self.exit()
except SystemExit:
self.log('SystemExit raised: shutting down bus')
self.exit()... |
'Poll for the given state(s) at intervals; publish to channel.'
| def wait(self, state, interval=0.1, channel=None):
| if isinstance(state, (tuple, list)):
states = state
else:
states = [state]
def _wait():
while (self.state not in states):
time.sleep(interval)
self.publish(channel)
try:
sys.modules['psyco'].cannotcompile(_wait)
except (KeyError, AttributeError... |
'Re-execute the current process.
This must be called from the main thread, because certain platforms
(OS X) don\'t allow execv to be called in a child thread very well.'
| def _do_execv(self):
| args = sys.argv[:]
self.log(('Re-spawning %s' % ' '.join(args)))
if (sys.platform[:4] == 'java'):
from _systemrestart import SystemRestart
raise SystemRestart
else:
args.insert(0, sys.executable)
if (sys.platform == 'win32'):
args = [('"%s"' % arg) for a... |
'Set the CLOEXEC flag on all open files (except stdin/out/err).
If self.max_cloexec_files is an integer (the default), then on
platforms which support it, it represents the max open files setting
for the operating system. This function will be called just before
the process is restarted via os.execv() to prevent open f... | def _set_cloexec(self):
| for fd in range(3, self.max_cloexec_files):
try:
flags = fcntl.fcntl(fd, fcntl.F_GETFD)
except IOError:
continue
fcntl.fcntl(fd, fcntl.F_SETFD, (flags | fcntl.FD_CLOEXEC))
|
'Stop all services.'
| def stop(self):
| self.state = states.STOPPING
self.log('Bus STOPPING')
self.publish('stop')
self.state = states.STOPPED
self.log('Bus STOPPED')
|
'Start \'func\' in a new thread T, then start self (and return T).'
| def start_with_callback(self, func, args=None, kwargs=None):
| if (args is None):
args = ()
if (kwargs is None):
kwargs = {}
args = ((func,) + args)
def _callback(func, *a, **kw):
self.wait(states.STARTED)
func(*a, **kw)
t = threading.Thread(target=_callback, args=args, kwargs=kwargs)
t.setName(('Bus Callback ' + t.getN... |
'Log the given message. Append the last traceback if requested.'
| def log(self, msg='', level=20, traceback=False):
| if traceback:
msg += ('\n' + ''.join(_traceback.format_exception(*sys.exc_info())))
self.publish('log', msg, level)
|
'Handle console control events (like Ctrl-C).'
| def handle(self, event):
| if (event in (win32con.CTRL_C_EVENT, win32con.CTRL_LOGOFF_EVENT, win32con.CTRL_BREAK_EVENT, win32con.CTRL_SHUTDOWN_EVENT, win32con.CTRL_CLOSE_EVENT)):
self.bus.log(('Console event %s: shutting down bus' % event))
try:
self.stop()
except ValueError:
pass... |
'Return a win32event for the given state (creating it if needed).'
| def _get_state_event(self, state):
| try:
return self.events[state]
except KeyError:
event = win32event.CreateEvent(None, 0, 0, ('WSPBus %s Event (pid=%r)' % (state.name, os.getpid())))
self.events[state] = event
return event
|
'Wait for the given state(s), KeyboardInterrupt or SystemExit.
Since this class uses native win32event objects, the interval
argument is ignored.'
| def wait(self, state, interval=0.1, channel=None):
| if isinstance(state, (tuple, list)):
if (self.state not in state):
events = tuple([self._get_state_event(s) for s in state])
win32event.WaitForMultipleObjects(events, 0, win32event.INFINITE)
elif (self.state != state):
event = self._get_state_event(state)
win32eve... |
'For the given value, return its corresponding key.'
| def key_for(self, obj):
| for (key, val) in self.items():
if (val is obj):
return key
raise ValueError(('The given object could not be found: %r' % obj))
|
'Start the HTTP server.'
| def start(self):
| if (self.bind_addr is None):
on_what = 'unknown interface (dynamic?)'
elif isinstance(self.bind_addr, tuple):
(host, port) = self.bind_addr
on_what = ('%s:%s' % (host, port))
else:
on_what = ('socket file: %s' % self.bind_addr)
if self.running:
self.bu... |
'HTTP servers MUST be running in new threads, so that the
main thread persists to receive KeyboardInterrupt\'s. If an
exception is raised in the httpserver\'s thread then it\'s
trapped here, and the bus (and therefore our httpserver)
are shut down.'
| def _start_http_thread(self):
| try:
self.httpserver.start()
except KeyboardInterrupt:
self.bus.log('<Ctrl-C> hit: shutting down HTTP server')
self.interrupt = sys.exc_info()[1]
self.bus.exit()
except SystemExit:
self.bus.log('SystemExit raised: shutting down HTTP serve... |
'Wait until the HTTP server is ready to receive requests.'
| def wait(self):
| while (not getattr(self.httpserver, 'ready', False)):
if self.interrupt:
raise self.interrupt
time.sleep(0.1)
if isinstance(self.bind_addr, tuple):
(host, port) = self.bind_addr
wait_for_occupied_port(host, port)
|
'Stop the HTTP server.'
| def stop(self):
| if self.running:
self.httpserver.stop()
if isinstance(self.bind_addr, tuple):
wait_for_free_port(*self.bind_addr)
self.running = False
self.bus.log(('HTTP Server %s shut down' % self.httpserver))
else:
self.bus.log(('HTTP Server %s already... |
'Restart the HTTP server.'
| def restart(self):
| self.stop()
self.start()
|
'Start the CGI server.'
| def start(self):
| from flup.server.cgi import WSGIServer
self.cgiserver = WSGIServer(*self.args, **self.kwargs)
self.ready = True
self.cgiserver.run()
|
'Stop the HTTP server.'
| def stop(self):
| self.ready = False
|
'Start the FCGI server.'
| def start(self):
| from flup.server.fcgi import WSGIServer
self.fcgiserver = WSGIServer(*self.args, **self.kwargs)
self.fcgiserver._installSignalHandlers = (lambda : None)
self.fcgiserver._oldSIGs = []
self.ready = True
self.fcgiserver.run()
|
'Stop the HTTP server.'
| def stop(self):
| self.fcgiserver._keepGoing = False
self.fcgiserver._threadPool.maxSpare = self.fcgiserver._threadPool._idleCount
self.ready = False
|
'Start the SCGI server.'
| def start(self):
| from flup.server.scgi import WSGIServer
self.scgiserver = WSGIServer(*self.args, **self.kwargs)
self.scgiserver._installSignalHandlers = (lambda : None)
self.scgiserver._oldSIGs = []
self.ready = True
self.scgiserver.run()
|
'Stop the HTTP server.'
| def stop(self):
| self.ready = False
self.scgiserver._keepGoing = False
self.scgiserver._threadPool.maxSpare = 0
|
'Return the current variant if in the cache, else None.'
| def get(self):
| raise NotImplemented
|
'Store the current variant in the cache.'
| def put(self, obj, size):
| raise NotImplemented
|
'Remove ALL cached variants of the current resource.'
| def delete(self):
| raise NotImplemented
|
'Reset the cache to its initial, empty state.'
| def clear(self):
| raise NotImplemented
|
'Return the cached value for the given key, or None.
If timeout is not None, and the value is already
being calculated by another thread, wait until the given timeout has
elapsed. If the value is available before the timeout expires, it is
returned. If not, None is returned, and a sentinel placed in the cache
to signal... | def wait(self, key, timeout=5, debug=False):
| value = self.get(key)
if isinstance(value, threading._Event):
if (timeout is None):
if debug:
cherrypy.log('No timeout', 'TOOLS.CACHING')
return None
if debug:
cherrypy.log(('Waiting up to %s seconds' % timeout), 'TOOLS.CACHING')... |
'Set the cached value for the given key.'
| def __setitem__(self, key, value):
| existing = self.get(key)
dict.__setitem__(self, key, value)
if isinstance(existing, threading._Event):
existing.result = value
existing.set()
|
'Reset the cache to its initial, empty state.'
| def clear(self):
| self.store = {}
self.expirations = {}
self.tot_puts = 0
self.tot_gets = 0
self.tot_hist = 0
self.tot_expires = 0
self.tot_non_modified = 0
self.cursize = 0
|
'Continuously examine cached objects, expiring stale ones.
This function is designed to be run in its own daemon thread,
referenced at ``self.expiration_thread``.'
| def expire_cache(self):
| while time:
now = time.time()
for (expiration_time, objects) in copyitems(self.expirations):
if (expiration_time <= now):
for (obj_size, uri, sel_header_values) in objects:
try:
del self.store[uri][tuple(sel_header_values)]
... |
'Return the current variant if in the cache, else None.'
| def get(self):
| request = cherrypy.serving.request
self.tot_gets += 1
uri = cherrypy.url(qs=request.query_string)
uricache = self.store.get(uri)
if (uricache is None):
return None
header_values = [request.headers.get(h, '') for h in uricache.selecting_headers]
variant = uricache.wait(key=tuple(sorte... |
'Store the current variant in the cache.'
| def put(self, variant, size):
| request = cherrypy.serving.request
response = cherrypy.serving.response
uri = cherrypy.url(qs=request.query_string)
uricache = self.store.get(uri)
if (uricache is None):
uricache = AntiStampedeCache()
uricache.selecting_headers = [e.value for e in response.headers.elements('Vary')]
... |
'Remove ALL cached variants of the current resource.'
| def delete(self):
| uri = cherrypy.url(qs=cherrypy.serving.request.query_string)
self.store.pop(uri, None)
|
'Encode a streaming response body.
Use a generator wrapper, and just pray it works as the stream is
being written out.'
| def encode_stream(self, encoding):
| if (encoding in self.attempted_charsets):
return False
self.attempted_charsets.add(encoding)
def encoder(body):
for chunk in body:
if isinstance(chunk, unicodestr):
chunk = chunk.encode(encoding, self.errors)
(yield chunk)
self.body = encoder(self.... |
'Encode a buffered response body.'
| def encode_string(self, encoding):
| if (encoding in self.attempted_charsets):
return False
self.attempted_charsets.add(encoding)
try:
body = []
for chunk in self.body:
if isinstance(chunk, unicodestr):
chunk = chunk.encode(encoding, self.errors)
body.append(chunk)
self.bo... |
'Validate the nonce.
Returns True if nonce was generated by synthesize_nonce() and the timestamp
is not spoofed, else returns False.
s
A string related to the resource, such as the hostname of the server.
key
A secret string known only to the server.
Both s and key must be the same values which were used to synthesize ... | def validate_nonce(self, s, key):
| try:
(timestamp, hashpart) = self.nonce.split(':', 1)
(s_timestamp, s_hashpart) = synthesize_nonce(s, key, timestamp).split(':', 1)
is_valid = (s_hashpart == hashpart)
if self.debug:
TRACE(('validate_nonce: %s' % is_valid))
return is_valid
except ValueError... |
'Returns True if a validated nonce is stale. The nonce contains a
timestamp in plaintext and also a secure hash of the timestamp. You should
first validate the nonce to ensure the plaintext timestamp is not spoofed.'
| def is_nonce_stale(self, max_age_seconds=600):
| try:
(timestamp, hashpart) = self.nonce.split(':', 1)
if ((int(timestamp) + max_age_seconds) > int(time.time())):
return False
except ValueError:
pass
if self.debug:
TRACE('nonce is stale')
return True
|
'Returns the H(A2) string. See :rfc:`2617` section 3.2.2.3.'
| def HA2(self, entity_body=''):
| if ((self.qop is None) or (self.qop == 'auth')):
a2 = ('%s:%s' % (self.http_method, self.uri))
elif (self.qop == 'auth-int'):
a2 = ('%s:%s:%s' % (self.http_method, self.uri, H(entity_body)))
else:
raise ValueError(self.errmsg('Unrecognized value for qop!'))
return H(a2)
|
'Calculates the Request-Digest. See :rfc:`2617` section 3.2.2.1.
ha1
The HA1 string obtained from the credentials store.
entity_body
If \'qop\' is set to \'auth-int\', then A2 includes a hash
of the "entity body". The entity body is the part of the
message which follows the HTTP headers. See :rfc:`2617` section
4.3. ... | def request_digest(self, ha1, entity_body=''):
| ha2 = self.HA2(entity_body)
if self.qop:
req = ('%s:%s:%s:%s:%s' % (self.nonce, self.nc, self.cnonce, self.qop, ha2))
else:
req = ('%s:%s' % (self.nonce, ha2))
if (self.algorithm == 'MD5-sess'):
ha1 = H(('%s:%s:%s' % (ha1, self.nonce, self.cnonce)))
digest = H(('%s:%s' % (ha1... |
'Generate the session specific concept of \'now\'.
Other session providers can override this to use alternative,
possibly timezone aware, versions of \'now\'.'
| def now(self):
| return datetime.datetime.now()
|
'Replace the current session (with a new id).'
| def regenerate(self):
| self.regenerated = True
self._regenerate()
|
'Clean up expired sessions.'
| def clean_up(self):
| pass
|
'Return a new session id.'
| def generate_id(self):
| return random20()
|
'Save session data.'
| def save(self):
| try:
if self.loaded:
t = datetime.timedelta(seconds=(self.timeout * 60))
expiration_time = (self.now() + t)
if self.debug:
cherrypy.log(('Saving with expiry %s' % expiration_time), 'TOOLS.SESSIONS')
self._save(expiration_time)
fina... |
'Copy stored session data into this session instance.'
| def load(self):
| data = self._load()
if ((data is None) or (data[1] < self.now())):
if self.debug:
cherrypy.log('Expired session, flushing data', 'TOOLS.SESSIONS')
self._data = {}
else:
self._data = data[0]
self.loaded = True
cls = self.__class__
if (self.clean_freq a... |
'Delete stored session data.'
| def delete(self):
| self._delete()
|
'Remove the specified key and return the corresponding value.
If key is not found, default is returned if given,
otherwise KeyError is raised.'
| def pop(self, key, default=missing):
| if (not self.loaded):
self.load()
if (default is missing):
return self._data.pop(key)
else:
return self._data.pop(key, default)
|
'D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.'
| def get(self, key, default=None):
| if (not self.loaded):
self.load()
return self._data.get(key, default)
|
'D.update(E) -> None. Update D from E: for k in E: D[k] = E[k].'
| def update(self, d):
| if (not self.loaded):
self.load()
self._data.update(d)
|
'D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D.'
| def setdefault(self, key, default=None):
| if (not self.loaded):
self.load()
return self._data.setdefault(key, default)
|
'D.clear() -> None. Remove all items from D.'
| def clear(self):
| if (not self.loaded):
self.load()
self._data.clear()
|
'D.keys() -> list of D\'s keys.'
| def keys(self):
| if (not self.loaded):
self.load()
return self._data.keys()
|
'D.items() -> list of D\'s (key, value) pairs, as 2-tuples.'
| def items(self):
| if (not self.loaded):
self.load()
return self._data.items()
|
'D.values() -> list of D\'s values.'
| def values(self):
| if (not self.loaded):
self.load()
return self._data.values()
|
'Clean up expired sessions.'
| def clean_up(self):
| now = self.now()
for (id, (data, expiration_time)) in copyitems(self.cache):
if (expiration_time <= now):
try:
del self.cache[id]
except KeyError:
pass
try:
del self.locks[id]
except KeyError:
... |
'Acquire an exclusive lock on the currently-loaded session data.'
| def acquire_lock(self):
| self.locked = True
self.locks.setdefault(self.id, threading.RLock()).acquire()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.