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 lines.append(line) seen += len(line) if (seen >= sizehint): break return lines
'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_params = self.request_params for (key, value) in self.params.items(): if isinstance(key, unicode): key = key.encode('ISO-8859-1') if (key in request_params): if (not isinstance(request_params[key], list)): request_params[key] = [request_params[key]] request_params[key].append(value) else: request_params[key] = value
'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 \, which are escaped by prepending a backslash, and all whitespace characters, which are written in their C-style notation (\n, \t, etc).'
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 = {'h': (remote.name or remote.ip), 'l': '-', 'u': (getattr(request, 'login', None) or '-'), 't': self.time(), 'r': request.request_line, 's': status, 'b': (dict.get(outheaders, 'Content-Length', '') or '-'), 'f': dict.get(inheaders, 'Referer', ''), 'a': dict.get(inheaders, 'User-Agent', '')} for (k, v) in atoms.items(): if isinstance(v, unicode): v = v.encode('utf8') elif (not isinstance(v, str)): v = str(v) v = repr(v)[1:(-1)] atoms[k] = v.replace('"', '\\"') try: self.access_log.log(logging.INFO, (self.access_log_format % atoms)) except: self(traceback=True)
'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.write((fs % msg)) else: try: stream.write((fs % msg)) except UnicodeError: stream.write((fs % msg.encode('UTF-8'))) self.flush() except: self.handleError(record)
'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)): method() finally: warnings.formatwarning = oldformatwarning
'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 in self.deprecated): warnings.warn(('%r is deprecated. Use %r instead.\nsection: [%s]' % (k, self.deprecated[k], section))) elif (section in self.obsolete): warnings.warn(('%r is obsolete. Use %r instead.' % (section, self.obsolete[section]))) elif (section in self.deprecated): warnings.warn(('%r is deprecated. Use %r instead.' % (section, self.deprecated[section])))
'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 or an IPv6 address. You should use '127.0.0.1' or '[::1]' instead.")
'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 except IndexError: 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 + '.') + self._name) + '.') f._cp_config[(subspace + 'on')] = True for (k, v) in kwargs.items(): f._cp_config[(subspace + k)] = v return f return tool_decorator
'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 == 'implicit'): hooks.attach('before_handler', self._lock_session) elif (locking == 'early'): hooks.attach('before_request_body', self._lock_session, priority=60) else: pass hooks.attach('before_finalize', _sessions.save) hooks.attach('on_end_request', _sessions.close)
'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 popped from the class dict and folded into the class docstring. The naming convention for attribute docstrings is: <attrname> + "__doc". For example: class Thing(object): """A thing and its properties.""" __metaclass__ = cherrypy._AttributeDocstrings height = 50 height__doc = """The height of the Thing in inches.""" In which case, help(Thing) starts like this: >>> help(mod.Thing) Help on class Thing in module pkg.mod: class Thing(__builtin__.object) | A thing and its properties. | height [= 50]: | The height of the Thing in inches. The benefits of this approach over hand-edited class docstrings: 1. Places the docstring nearer to the attribute declaration. 2. Makes attribute docs more uniform ("name (default): doc"). 3. Reduces mismatches of attribute _names_ between the declaration and the documentation. 4. Reduces mismatches of attribute default _values_ between the declaration and the documentation. The benefits of a metaclass approach over other approaches: 1. Simpler ("less magic") than interface-based solutions. 2. __metaclass__ can be specified at the module global level for classic classes. For various formatting reasons, you should write multiline docs with a leading newline and not a trailing one: response__doc = """ The response object for the current thread. In the main thread, and any threads which are not HTTP requests, this is None.""" The type of the attribute is intentionally not included, because that\'s not How Python Works. Quack.'
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')]) attrname = name[:(-5)] try: attrval = getattr(cls, attrname) except AttributeError: attrval = 'missing' newdoc.append(('%s [= %r]:\n%s' % (attrname, attrval, val))) cls.__doc__ = '\n\n'.join(newdoc)
'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(): f._cp_config[k] = v return f return tool_decorator
'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 = '/' else: trail = trail[:lastslash] return default
'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('acquire_thread') return (req, resp)
'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 the "mount point" of the application. This should start with a slash, and be the path portion of the URL at which to mount the given root. For example, if root.index() will handle requests to "http://www.example.com:8080/dept/app1/", then the script_name argument would be "/dept/app1". It MUST NOT end in a slash. If the script_name refers to the root of the URI, it MUST be an empty string (not "/"). config: a file or dict containing application config.'
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). You cannot mount such Applications on this Tree; you must pass them to a WSGI server interface directly.") script_name = script_name.rstrip('/') if isinstance(root, Application): app = root if ((script_name != '') and (script_name != app.script_name)): raise ValueError('Cannot specify a different script name and pass an Application instance to cherrypy.mount') script_name = app.script_name else: app = Application(root, script_name) if ((script_name == '') and (root is not None) and (not hasattr(root, 'favicon_ico'))): favicon = os.path.join(os.getcwd(), os.path.dirname(__file__), 'favicon.ico') root.favicon_ico = tools.staticfile.handler(favicon) if config: app.merge(config) self.apps[script_name] = app return app
'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 == ''): return None path = path[:path.rfind('/')]
'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 be found at <a href='%s'>%s</a>.", 301: "This resource has permanently moved to <a href='%s'>%s</a>.", 302: "This resource resides temporarily at <a href='%s'>%s</a>.", 303: "This resource can be found at <a href='%s'>%s</a>.", 307: "This resource has moved temporarily to <a href='%s'>%s</a>."}[status] msgs = [(msg % (u, u)) for u in self.urls] response.body = '<br />\n'.join(msgs) response.headers.pop('Content-Length', None) elif (status == 304): for key in ('Allow', 'Content-Encoding', 'Content-Language', 'Content-Length', 'Content-Location', 'Content-MD5', 'Content-Range', 'Content-Type', 'Expires', 'Last-Modified'): if (key in response.headers): del response.headers[key] response.body = None response.headers.pop('Content-Length', None) elif (status == 305): response.headers['Location'] = self.urls[0] response.body = None response.headers.pop('Content-Length', None) else: raise ValueError(('The %s status code is unknown.' % status))
'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', None) content = self.get_error_page(self.status, traceback=tb, message=self._message) response.body = content _be_ie_unfriendly(self.code)
'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 ValueError(('No such signal: %r' % signal)) signum = signal prev = _signal.signal(signum, self._handle_signal) self._previous_handlers[signum] = prev if (listener is not None): self.bus.log(('Listening for %s.' % signame)) self.bus.subscribe(signame, listener)
'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() self.bus.log(('Started monitor thread %r.' % threadname)) else: self.bus.log(('Monitor thread %r already started.' % threadname))
'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() self.bus.log(('Stopped thread %r.' % name)) self.thread = None
'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 (not os.path.isabs(f))): f = os.path.normpath(os.path.join(_module__file__base, f)) files.add(f) return files
'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(filename).st_mtime except OSError: mtime = None if (filename not in self.mtimes): self.mtimes[filename] = mtime elif ((mtime is None) or (mtime > oldtime)): self.bus.log(('Restarting because %s changed.' % filename)) self.thread.cancel() self.bus.log(('Stopped thread %r.' % self.thread.getName())) self.bus.restart() return
'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, **kwargs)) except KeyboardInterrupt: raise except SystemExit as e: if (exc and (e.code == 0)): e.code = 1 raise except: exc.handle_exception() if (channel == 'log'): pass else: self.log(('Error in %r listener %r' % (channel, listener)), level=40, traceback=True) if exc: raise exc return output
'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 the main thread exits.' % self.state), RuntimeWarning) self.exit()
'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 due to error in start listener:', level=40, traceback=True) e_info = sys.exc_info() try: self.exit() except: pass raise e_info[0], e_info[1], e_info[2]
'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 the main thread perform the actual execv call (required on some platforms).'
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() raise self.log('Waiting for child threads to terminate...') for t in threading.enumerate(): if ((t != threading.currentThread()) and t.isAlive()): if hasattr(threading.Thread, 'daemon'): d = t.daemon else: d = t.isDaemon() if (not d): t.join() if self.execv: self._do_execv()
'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): pass _wait()
'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.getName())) t.start() self.start() return t
'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 self.bus.exit() return 1 return 0
'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) win32event.WaitForSingleObject(event, win32event.INFINITE)
'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.bus.log(('Already serving on %s' % on_what)) return self.interrupt = None if (not self.httpserver): raise ValueError('No HTTP server has been created.') if isinstance(self.bind_addr, tuple): wait_for_free_port(*self.bind_addr) import threading t = threading.Thread(target=self._start_http_thread) t.setName(('HTTPServer ' + t.getName())) t.start() self.wait() self.running = True self.bus.log(('Serving on %s' % on_what))
'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 server') self.interrupt = exc self.bus.exit() raise except: import sys self.interrupt = sys.exc_info()[1] self.bus.log('Error in HTTP server: shutting down', traceback=True, level=40) self.bus.exit() raise
'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 shut down' % self.httpserver))
'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 cache to signal other threads to wait. If timeout is None, no waiting is performed nor sentinels used.'
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') value.wait(timeout) if (value.result is not None): if debug: cherrypy.log('Result!', 'TOOLS.CACHING') return value.result if debug: cherrypy.log('Timed out', 'TOOLS.CACHING') e = threading.Event() e.result = None dict.__setitem__(self, key, e) return None elif (value is None): if debug: cherrypy.log('Timed out', 'TOOLS.CACHING') e = threading.Event() e.result = None dict.__setitem__(self, key, e) return value
'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 = uricache.wait(key=tuple(header_values), timeout=self.antistampede_timeout, debug=self.debug) if (variant is not None): self.tot_hist += 1 return variant
'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')] self.store[uri] = uricache if (len(self.store) < self.maxobjects): total_size = (self.cursize + size) if ((size < self.maxobj_size) and (total_size < self.maxsize)): expiration_time = (response.time + self.delay) bucket = self.expirations.setdefault(expiration_time, []) bucket.append((size, uri, uricache.selecting_headers)) header_values = [request.headers.get(h, '') for h in uricache.selecting_headers] header_values.sort() uricache[tuple(header_values)] = variant self.tot_puts += 1 self.cursize = total_size
'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.body) return True
'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 = body except (LookupError, UnicodeError): return False else: return True
'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 synthesize the nonce we are trying to validate.'
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: pass return False
'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. This refers to the entity the user agent sent in the request which has the Authorization header. Typically GET requests don\'t have an entity, and POST requests do.'
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, req))) return digest
'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_time) finally: if self.locked: self.release_lock()