desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Read lines from the request body and return them.'
def readlines(self, sizehint=None):
if (self.length is not None): if (sizehint is None): sizehint = (self.length - self.bytes_read) else: sizehint = min(sizehint, (self.length - self.bytes_read)) lines = [] seen = 0 while True: line = self.readline() if (not line): break ...
'Include body params in request params.'
def process(self):
h = cherrypy.serving.request.headers if ((u'Content-Length' not in h) and (u'Transfer-Encoding' not in h)): raise cherrypy.HTTPError(411) self.fp = SizedReader(self.fp, self.length, self.maxbytes, bufsize=self.bufsize, has_trailers=('Trailer' in h)) super(RequestBody, self).process() request...
'Close and reopen all file handlers.'
def reopen_files(self):
for log in (self.error_log, self.access_log): for h in log.handlers: if isinstance(h, logging.FileHandler): h.acquire() h.stream.close() h.stream = open(h.baseFilename, h.mode) h.release()
'Write to the error log. This is not just for errors! Applications may call this at any time to log application-specific information.'
def error(self, msg='', context='', severity=logging.INFO, traceback=False):
if traceback: msg += _cperror.format_exc() self.error_log.log(severity, ' '.join((self.time(), context, msg)))
'Write to the error log. This is not just for errors! Applications may call this at any time to log application-specific information.'
def __call__(self, *args, **kwargs):
return self.error(*args, **kwargs)
'Write to the access log (in Apache/NCSA Combined Log format). Like Apache started doing in 2.0.46, non-printable and other special characters in %r (and we expand that to all parts) are escaped using \xhh sequences, where hh stands for the hexadecimal representation of the raw byte. Exceptions from this rule are " and...
def access(self):
request = cherrypy.serving.request remote = request.remote response = cherrypy.serving.response outheaders = response.headers inheaders = request.headers if (response.output_status is None): status = '-' else: status = response.output_status.split(' ', 1)[0] atoms = {'...
'Return now() in Apache Common Log Format (no timezone).'
def time(self):
now = datetime.datetime.now() monthnames = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'] month = monthnames[(now.month - 1)].capitalize() return ('[%02d/%s/%04d:%02d:%02d:%02d]' % (now.day, month, now.year, now.hour, now.minute, now.second))
'Flushes the stream.'
def flush(self):
try: stream = cherrypy.serving.request.wsgi_environ.get('wsgi.errors') except (AttributeError, KeyError): pass else: stream.flush()
'Emit a record.'
def emit(self, record):
try: stream = cherrypy.serving.request.wsgi_environ.get('wsgi.errors') except (AttributeError, KeyError): pass else: try: msg = self.format(record) fs = '%s\n' import types if (not hasattr(types, 'UnicodeType')): stream....
'Run all check_* methods.'
def __call__(self):
if self.on: oldformatwarning = warnings.formatwarning warnings.formatwarning = self.formatwarning try: for name in dir(self): if name.startswith('check_'): method = getattr(self, name) if (method and callable(method)): ...
'Function to format a warning.'
def formatwarning(self, message, category, filename, lineno, line=None):
return ('CherryPy Checker:\n%s\n\n' % message)
'Process config and warn on each obsolete or deprecated entry.'
def _compat(self, config):
for (section, conf) in config.items(): if isinstance(conf, dict): for (k, v) in conf.items(): if (k in self.obsolete): warnings.warn(('%r is obsolete. Use %r instead.\nsection: [%s]' % (k, self.obsolete[k], section))) elif (k ...
'Process config and warn on each obsolete or deprecated entry.'
def check_compatibility(self):
self._compat(cherrypy.config) for (sn, app) in cherrypy.tree.apps.items(): if (not isinstance(app, cherrypy.Application)): continue self._compat(app.config)
'Process config and warn on each unknown config namespace.'
def check_config_namespaces(self):
for (sn, app) in cherrypy.tree.apps.items(): if (not isinstance(app, cherrypy.Application)): continue self._known_ns(app)
'Assert that config values are of the same type as default values.'
def check_config_types(self):
self._known_types(cherrypy.config) for (sn, app) in cherrypy.tree.apps.items(): if (not isinstance(app, cherrypy.Application)): continue self._known_types(app.config)
'Warn if any socket_host is \'localhost\'. See #711.'
def check_localhost(self):
for (k, v) in cherrypy.config.items(): if ((k == 'server.socket_host') and (v == 'localhost')): warnings.warn("The use of 'localhost' as a socket host can cause problems on newer systems, since 'localhost' can map to either an IPv4 ...
'Copy func parameter names to obj attributes.'
def _setargs(self):
try: for arg in _getargs(self.callable): setattr(self, arg, None) except (TypeError, AttributeError): if hasattr(self.callable, '__call__'): for arg in _getargs(self.callable.__call__): setattr(self, arg, None) except NotImplementedError: pass ...
'Return a dict of configuration entries for this Tool.'
def _merged_args(self, d=None):
if d: conf = d.copy() else: conf = {} tm = cherrypy.serving.request.toolmaps[self.namespace] if (self._name in tm): conf.update(tm[self._name]) if ('on' in conf): del conf['on'] return conf
'Compile-time decorator (turn on the tool in config). For example: @tools.proxy() def whats_my_base(self): return cherrypy.request.base whats_my_base.exposed = True'
def __call__(self, *args, **kwargs):
if args: raise TypeError(('The %r Tool does not accept positional arguments; you must use keyword arguments.' % self._name)) def tool_decorator(f): if (not hasattr(f, '_cp_config')): f._cp_config = {} subspace = (((self.namespace + '.') + s...
'Hook this tool into cherrypy.request. The standard CherryPy request object will automatically call this method when the tool is "turned on" in config.'
def _setup(self):
conf = self._merged_args() p = conf.pop('priority', None) if (p is None): p = getattr(self.callable, 'priority', self._priority) cherrypy.serving.request.hooks.attach(self._point, self.callable, priority=p, **conf)
'Use this tool as a CherryPy page handler. For example: class Root: nav = tools.staticdir.handler(section="/nav", dir="nav", root=absDir)'
def handler(self, *args, **kwargs):
def handle_func(*a, **kw): handled = self.callable(*args, **self._merged_args(kwargs)) if (not handled): raise cherrypy.NotFound() return cherrypy.serving.response.body handle_func.exposed = True return handle_func
'Hook this tool into cherrypy.request. The standard CherryPy request object will automatically call this method when the tool is "turned on" in config.'
def _setup(self):
conf = self._merged_args() p = conf.pop('priority', None) if (p is None): p = getattr(self.callable, 'priority', self._priority) cherrypy.serving.request.hooks.attach(self._point, self._wrapper, priority=p, **conf)
'Hook this tool into cherrypy.request. The standard CherryPy request object will automatically call this method when the tool is "turned on" in config.'
def _setup(self):
cherrypy.serving.request.error_response = self._wrapper
'Hook this tool into cherrypy.request. The standard CherryPy request object will automatically call this method when the tool is "turned on" in config.'
def _setup(self):
hooks = cherrypy.serving.request.hooks conf = self._merged_args() p = conf.pop('priority', None) if (p is None): p = getattr(self.callable, 'priority', self._priority) hooks.attach(self._point, self.callable, priority=p, **conf) locking = conf.pop('locking', 'implicit') if (locking =...
'Drop the current session and make a new one (with a new id).'
def regenerate(self):
sess = cherrypy.serving.session sess.regenerate() conf = dict([(k, v) for (k, v) in self._merged_args().items() if (k in ('path', 'path_header', 'name', 'timeout', 'domain', 'secure'))]) _sessions.set_response_cookie(**conf)
'Hook caching into cherrypy.request.'
def _setup(self):
conf = self._merged_args() p = conf.pop('priority', None) cherrypy.serving.request.hooks.attach('before_handler', self._wrapper, priority=p, **conf)
'Populate request.toolmaps from tools specified in config.'
def __enter__(self):
cherrypy.serving.request.toolmaps[self.namespace] = map = {} def populate(k, v): (toolname, arg) = k.split('.', 1) bucket = map.setdefault(toolname, {}) bucket[arg] = v return populate
'Run tool._setup() for each tool in our toolmap.'
def __exit__(self, exc_type, exc_val, exc_tb):
map = cherrypy.serving.request.toolmaps.get(self.namespace) if map: for (name, settings) in map.items(): if settings.get('on', False): tool = getattr(self, name) tool._setup()
'Metaclass for declaring docstrings for class attributes. Base Python doesn\'t provide any syntax for setting docstrings on \'data attributes\' (non-callables). This metaclass allows class definitions to follow the declaration of a data attribute with a docstring for that attribute; the attribute docstring will be popp...
def __init__(cls, name, bases, dct):
newdoc = [(cls.__doc__ or '')] dctkeys = dct.keys() dctkeys.sort() for name in dctkeys: if name.endswith('__doc'): if hasattr(cls, name): delattr(cls, name) val = '\n'.join([(' ' + line.strip()) for line in dct[name].split('\n')]) ...
'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()
'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.timeout_monitor.acquire() cherrypy.engine.publish('acquir...
'Release the current serving (request and response).'
def release_serving(self):
req = cherrypy.serving.request cherrypy.engine.timeout_monitor.release() 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 th...
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 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)
'Start our callback in its own perpetual timer thread.'
def start(self):
if (self.frequency > 0): threadname = (self.name or self.__class__.__name__) if (self.thread is None): self.thread = PerpetualTimer(self.frequency, self.callback) self.thread.bus = self.bus self.thread.setName(threadname) self.thread.start() ...
'Stop our callback\'s perpetual timer 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() self.thread.join() ...
'Stop the callback\'s perpetual timer thread and restart it.'
def graceful(self):
self.stop() self.start()
'Start our own perpetual timer thread for self.run.'
def start(self):
if (self.thread is None): self.mtimes = {} Monitor.start(self)
'Return a Set of filenames which the Autoreloader will 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 = thread.get_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 = threading._get_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()
'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]] items.sort() for (priority, listener) in items: try: output.append(listener(*args, **k...
'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()...
'Wait for the given state(s).'
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))) args.insert(0, sys.executable) if (sys.platform == 'win32'): args = [('"%s"' % arg) for arg in args] os.chdir(_startup_cwd) os.execv(sys.executable, args)
'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: exc = sys.exc_info() msg += ('\n' + ''.join(_traceback.format_exception(*exc))) 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 as exc: self.bus.log('<Ctrl-C> hit: shutting down HTTP server') self.interrupt = exc self.bus.exit() except SystemExit as exc: 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 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 cached value for the given key, or None. If timeout is not None (the default), 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 c...
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
'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] header_values.sort() variant = uric...
'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, unicode): chunk = chunk.encode(encoding, self.errors) (yield chunk) self.body = encoder(self.bod...
'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, unicode): chunk = chunk.encode(encoding, self.errors) body.append(chunk) self.body ...
'Validate the nonce. Returns True if nonce was generated by synthesize_nonce() and the timestamp is not spoofed, else returns False. Args: 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 syn...
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 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 3.2.2.1. Arguments: 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...
'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
'Save session data.'
def save(self):
try: if self.loaded: t = datetime.timedelta(seconds=(self.timeout * 60)) expiration_time = (datetime.datetime.now() + t) if self.debug: cherrypy.log(('Saving with expiry %s' % expiration_time), 'TOOLS.SESSIONS') self._save(expiration_t...