desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Release the lock on the currently-loaded session data.'
def release_lock(self):
self.locks[self.id].release() self.locked = False
'Return the number of active sessions.'
def __len__(self):
return len(self.cache)
'Set up the storage system for file-based sessions. This should only be called once per process; this will be done automatically when using sessions.init (as the built-in Tool does).'
def setup(cls, **kwargs):
kwargs['storage_path'] = os.path.abspath(kwargs['storage_path']) for (k, v) in kwargs.items(): setattr(cls, k, v) lockfiles = [fname for fname in os.listdir(cls.storage_path) if (fname.startswith(cls.SESSION_PREFIX) and fname.endswith(cls.LOCK_SUFFIX))] if lockfiles: plural = ('', 's')[(...
'Acquire an exclusive lock on the currently-loaded session data.'
def acquire_lock(self, path=None):
if (path is None): path = self._get_file_path() path += self.LOCK_SUFFIX while True: try: lockfd = os.open(path, ((os.O_CREAT | os.O_WRONLY) | os.O_EXCL)) except OSError: time.sleep(0.1) else: os.close(lockfd) break self.loc...
'Release the lock on the currently-loaded session data.'
def release_lock(self, path=None):
if (path is None): path = self._get_file_path() os.unlink((path + self.LOCK_SUFFIX)) self.locked = False
'Clean up expired sessions.'
def clean_up(self):
now = self.now() for fname in os.listdir(self.storage_path): if (fname.startswith(self.SESSION_PREFIX) and (not fname.endswith(self.LOCK_SUFFIX))): path = os.path.join(self.storage_path, fname) self.acquire_lock(path) try: contents = self._load(path) ...
'Return the number of active sessions.'
def __len__(self):
return len([fname for fname in os.listdir(self.storage_path) if (fname.startswith(self.SESSION_PREFIX) and (not fname.endswith(self.LOCK_SUFFIX)))])
'Set up the storage system for Postgres-based sessions. This should only be called once per process; this will be done automatically when using sessions.init (as the built-in Tool does).'
def setup(cls, **kwargs):
for (k, v) in kwargs.items(): setattr(cls, k, v) self.db = self.get_db()
'Acquire an exclusive lock on the currently-loaded session data.'
def acquire_lock(self):
self.locked = True self.cursor.execute('select id from session where id=%s for update', (self.id,))
'Release the lock on the currently-loaded session data.'
def release_lock(self):
self.cursor.close() self.locked = False
'Clean up expired sessions.'
def clean_up(self):
self.cursor.execute('delete from session where expiration_time < %s', (self.now(),))
'Set up the storage system for memcached-based sessions. This should only be called once per process; this will be done automatically when using sessions.init (as the built-in Tool does).'
def setup(cls, **kwargs):
for (k, v) in kwargs.items(): setattr(cls, k, v) import memcache cls.cache = memcache.Client(cls.servers)
'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()
'Release the lock on the currently-loaded session data.'
def release_lock(self):
self.locks[self.id].release() self.locked = False
'Return the number of active sessions.'
def __len__(self):
raise NotImplementedError
'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):
if appstats.get('Enabled', False): cherrypy.Tool._setup(self) self.record_start()
'Record the beginning of a request.'
def record_start(self):
request = cherrypy.serving.request if (not hasattr(request.rfile, 'bytes_read')): request.rfile = ByteCountWrapper(request.rfile) request.body.fp = request.rfile r = request.remote appstats['Current Requests'] += 1 appstats['Total Requests'] += 1 appstats['Requests'][thread...
'Record the end of a request.'
def record_stop(self, uriset=None, slow_queries=1.0, slow_queries_count=100, debug=False, **kwargs):
resp = cherrypy.serving.response w = appstats['Requests'][threading._get_ident()] r = cherrypy.request.rfile.bytes_read w['Bytes Read'] = r appstats['Total Bytes Read'] += r if resp.stream: w['Bytes Written'] = 'chunked' else: cl = int(resp.headers.get('Content-Le...
'Yield (title, scalars, collections) for each namespace.'
def get_namespaces(self):
s = extrapolate_statistics(logging.statistics) for (title, ns) in sorted(s.items()): scalars = [] collections = [] ns_fmt = self.formatting.get(title, {}) for (k, v) in sorted(ns.items()): fmt = ns_fmt.get(k, {}) if isinstance(v, dict): (he...
'Return ([headers], [rows]) for the given collection.'
def get_dict_collection(self, v, formatting):
headers = [] for record in v.itervalues(): for k3 in record: format = formatting.get(k3, missing) if (format is None): continue if (k3 not in headers): headers.append(k3) headers.sort() subrows = [] for (k2, record) in sorte...
'Return ([headers], [subrows]) for the given collection.'
def get_list_collection(self, v, formatting):
headers = [] for record in v: for k3 in record: format = formatting.get(k3, missing) if (format is None): continue if (k3 not in headers): headers.append(k3) headers.sort() subrows = [] for record in v: subrow = [] ...
'Dump profile data into self.path.'
def run(self, func, *args, **params):
global _count c = _count = (_count + 1) path = os.path.join(self.path, ('cp_%04d.prof' % c)) prof = profile.Profile() result = prof.runcall(func, *args, **params) prof.dump_stats(path) return result
':rtype: list of available profiles.'
def statfiles(self):
return [f for f in os.listdir(self.path) if (f.startswith('cp_') and f.endswith('.prof'))]
':rtype stats(index): output of print_stats() for the given profile.'
def stats(self, filename, sortby='cumulative'):
sio = BytesIO() if (sys.version_info >= (2, 5)): s = pstats.Stats(os.path.join(self.path, filename), stream=sio) s.strip_dirs() s.sort_stats(sortby) s.print_stats() else: s = pstats.Stats(os.path.join(self.path, filename)) s.strip_dirs() s.sort_stats(s...
'Make a WSGI middleware app which wraps \'nextapp\' with profiling. nextapp the WSGI application to wrap, usually an instance of cherrypy.Application. path where to dump the profiling output. aggregate if True, profile data for all HTTP requests will go in a single file. If False (the default), each HTTP request will d...
def __init__(self, nextapp, path=None, aggregate=False):
if ((profile is None) or (pstats is None)): msg = "Your installation of Python does not have a profile module. If you're on Debian, try `sudo apt-get install python-profiler`. See http://www.cherrypy.org/wiki/ProfilingOnDebian for details." ...
'Return a nested list containing referrers of the given object.'
def ascend(self, obj, depth=1):
depth += 1 parents = [] refs = gc.get_referrers(obj) self.ignore.append(refs) if (len(refs) > self.maxparents): return [(('[%s referrers]' % len(refs)), [])] try: ascendcode = self.ascend.__code__ except AttributeError: ascendcode = self.ascend.im_func.func_code ...
'Return s, restricted to a sane length.'
def peek(self, s):
if (len(s) > (self.peek_length + 3)): half = (self.peek_length // 2) return ((s[:half] + '...') + s[(- half):]) else: return s
'Return a string representation of a single object.'
def _format(self, obj, descend=True):
if inspect.isframe(obj): (filename, lineno, func, context, index) = inspect.getframeinfo(obj) return ("<frame of function '%s'>" % func) if (not descend): return self.peek(repr(obj)) if isinstance(obj, dict): return (('{' + ', '.join([('%s: %s' % (self._format(...
'Return a list of string reprs from a nested list of referrers.'
def format(self, tree):
output = [] def ascend(branch, depth=1): for (parent, grandparents) in branch: output.append(((' ' * depth) + self._format(parent))) if grandparents: ascend(grandparents, (depth + 1)) ascend(tree) return output
'Provide a temporary user name for anonymous users.'
def anonymous(self):
pass
'Login. May raise redirect, or return True if request handled.'
def do_login(self, username, password, from_page='..', **kwargs):
response = cherrypy.serving.response error_msg = self.check_username_and_password(username, password) if error_msg: body = self.login_screen(from_page, username, error_msg) response.body = body if ('Content-Length' in response.headers): del response.headers['Content-Lengt...
'Logout. May raise redirect, or return True if request handled.'
def do_logout(self, from_page='..', **kwargs):
sess = cherrypy.session username = sess.get(self.session_key) sess[self.session_key] = None if username: cherrypy.serving.request.login = None self.on_logout(username) raise cherrypy.HTTPRedirect(from_page)
'Assert username. May raise redirect, or return True if request handled.'
def do_check(self):
sess = cherrypy.session request = cherrypy.serving.request response = cherrypy.serving.response username = sess.get(self.session_key) if (not username): sess[self.session_key] = username = self.anonymous() if self.debug: cherrypy.log('No session[username], trying ...
'Transform \'token;key=val\' to (\'token\', {\'key\': \'val\'}).'
def parse(elementstr):
atoms = [x.strip() for x in elementstr.split(';') if x.strip()] if (not atoms): initial_value = '' else: initial_value = atoms.pop(0).strip() params = {} for atom in atoms: atom = [x.strip() for x in atom.split('=', 1) if x.strip()] key = atom.pop(0) if atom: ...
'Construct an instance from a string of the form \'token;key=val\'.'
def from_str(cls, elementstr):
(ival, params) = cls.parse(elementstr) return cls(ival, params)
'Return a sorted list of HeaderElements for the given header.'
def elements(self, key):
key = str(key).title() value = self.get(key) return header_elements(key, value)
'Return a sorted list of HeaderElement.value for the given header.'
def values(self, key):
return [e.value for e in self.elements(key)]
'Transform self into a list of (name, value) tuples.'
def output(self):
header_list = [] for (k, v) in self.items(): if isinstance(k, unicodestr): k = self.encode(k) if (not isinstance(v, basestring)): v = str(v) if isinstance(v, unicodestr): v = self.encode(v) k = k.translate(header_translate_table, header_transla...
'Return the given header name or value, encoded for HTTP output.'
def encode(self, v):
for enc in self.encodings: try: return v.encode(enc) except UnicodeEncodeError: continue if ((self.protocol == (1, 1)) and self.use_rfc_2047): v = b2a_base64(v.encode('utf-8')) return ((ntob('=?utf-8?b?') + v.strip(ntob('\n'))) + ntob('?=')) raise Valu...
'Iterate through config and pass it to each namespace handler. config A flat dict, where keys use dots to separate namespaces, and values are arbitrary. The first name in each config key is used to look up the corresponding namespace handler. For example, a config entry of {\'tools.gzip.on\': v} will call the \'tools\'...
def __call__(self, config):
ns_confs = {} for k in config: if ('.' in k): (ns, name) = k.split('.', 1) bucket = ns_confs.setdefault(ns, {}) bucket[name] = config[k] for (ns, handler) in self.items(): exit = getattr(handler, '__exit__', None) if exit: callable = ha...
'Reset self to default values.'
def reset(self):
self.clear() dict.update(self, self.defaults)
'Update self from a dict, file or filename.'
def update(self, config):
if isinstance(config, basestring): config = Parser().dict_from_file(config) elif hasattr(config, 'read'): config = Parser().dict_from_file(config) else: config = config.copy() self._apply(config)
'Update self from a dict.'
def _apply(self, config):
which_env = config.get('environment') if which_env: env = self.environments[which_env] for k in env: if (k not in config): config[k] = env[k] dict.update(self, config) self.namespaces(config)
'Convert an INI file to a dictionary'
def as_dict(self, raw=False, vars=None):
result = {} for section in self.sections(): if (section not in result): result[section] = {} for option in self.options(section): value = self.get(section, option, raw=raw, vars=vars) try: value = unrepr(value) except Exception: ...
'Return a Python2 ast Node compiled from a string.'
def astnode(self, s):
try: import compiler except ImportError: return eval(s) p = compiler.parse(('__tempvalue__ = ' + s)) return p.getChildren()[1].getChildren()[0].getChildren()[1]
'Return a Python3 ast Node compiled from a string.'
def astnode(self, s):
try: import ast except ImportError: return eval(s) p = ast.parse(('__tempvalue__ = ' + s)) return p.body[0].value
'Overwrite self.logfile with 0 bytes.'
def emptyLog(self):
open(self.logfile, 'wb').write('')
'Insert a marker line into the log and set self.lastmarker.'
def markLog(self, key=None):
if (key is None): key = str(time.time()) self.lastmarker = key open(self.logfile, 'ab+').write(ntob(('%s%s\n' % (self.markerPrefix, key)), 'utf-8'))
'Return lines from self.logfile in the marked region. If marker is None, self.lastmarker is used. If the log hasn\'t been marked (using self.markLog), the entire log will be returned.'
def _read_marked_region(self, marker=None):
logfile = self.logfile marker = (marker or self.lastmarker) if (marker is None): return open(logfile, 'rb').readlines() if isinstance(marker, unicodestr): marker = marker.encode('utf-8') data = [] in_region = False for line in open(logfile, 'rb'): if in_region: ...
'Fail if the given (partial) line is not in the log. The log will be searched from the given marker to the next marker. If marker is None, self.lastmarker is used. If the log hasn\'t been marked (using self.markLog), the entire log will be searched.'
def assertInLog(self, line, marker=None):
data = self._read_marked_region(marker) for logline in data: if (line in logline): return msg = ('%r not found in log' % line) self._handleLogError(msg, data, marker, line)
'Fail if the given (partial) line is in the log. The log will be searched from the given marker to the next marker. If marker is None, self.lastmarker is used. If the log hasn\'t been marked (using self.markLog), the entire log will be searched.'
def assertNotInLog(self, line, marker=None):
data = self._read_marked_region(marker) for logline in data: if (line in logline): msg = ('%r found in log' % line) self._handleLogError(msg, data, marker, line)
'Fail if log.readlines()[sliceargs] is not contained in \'lines\'. The log will be searched from the given marker to the next marker. If marker is None, self.lastmarker is used. If the log hasn\'t been marked (using self.markLog), the entire log will be searched.'
def assertLog(self, sliceargs, lines, marker=None):
data = self._read_marked_region(marker) if isinstance(sliceargs, int): if isinstance(lines, (tuple, list)): lines = lines[0] if isinstance(lines, unicodestr): lines = lines.encode('utf-8') if (lines not in data[sliceargs]): msg = ('%r not found ...
'Gracefully shutdown a server that is serving forever.'
def stop(self):
read_process(APACHE_PATH, '-k stop') helper.LocalWSGISupervisor.stop(self)
'Run the given test case or test suite.'
def run(self, test):
result = self._makeResult() test(result) result.printErrors() if (not result.wasSuccessful()): self.stream.write('FAILED (') (failed, errored) = list(map(len, (result.failures, result.errors))) if failed: self.stream.write(('failures=%d' % failed)) if error...
'Return a suite of all tests cases given a string specifier. The name may resolve either to a module, a test case class, a test method within a test case class, or a callable object which returns a TestCase or TestSuite instance. The method optionally resolves the names relative to a given module.'
def loadTestsFromName(self, name, module=None):
parts = name.split('.') unused_parts = [] if (module is None): if (not parts): raise ValueError(('incomplete test name: %s' % name)) else: parts_copy = parts[:] while parts_copy: target = '.'.join(parts_copy) if (ta...
'Return a connection to our HTTP server.'
def get_conn(self, auto_open=False):
if (self.scheme == 'https'): cls = HTTPSConnection else: cls = HTTPConnection conn = cls(self.interface(), self.PORT) conn.auto_open = auto_open conn.connect() return conn
'Make our HTTP_CONN persistent (or not). If the \'on\' argument is True (the default), then self.HTTP_CONN will be set to an instance of HTTPConnection (or HTTPS if self.scheme is "https"). This will then persist across requests. We only allow for a single open connection, so if you call this and we currently have an o...
def set_persistent(self, on=True, auto_open=False):
try: self.HTTP_CONN.close() except (TypeError, AttributeError): pass if on: self.HTTP_CONN = self.get_conn(auto_open=auto_open) elif (self.scheme == 'https'): self.HTTP_CONN = HTTPSConnection else: self.HTTP_CONN = HTTPConnection
'Return an IP address for a client connection. If the server is listening on \'0.0.0.0\' (INADDR_ANY) or \'::\' (IN6ADDR_ANY), this will return the proper localhost.'
def interface(self):
return interface(self.HOST)
'Open the url with debugging support. Return status, headers, body.'
def getPage(self, url, headers=None, method='GET', body=None, protocol=None):
ServerError.on = False if isinstance(url, unicodestr): url = url.encode('utf-8') if isinstance(body, unicodestr): body = body.encode('utf-8') self.url = url self.time = None start = time.time() result = openURL(url, headers, method, body, self.HOST, self.PORT, self.HTTP_CONN,...
'Fail if self.status != status.'
def assertStatus(self, status, msg=None):
if isinstance(status, basestring): if (not (self.status == status)): if (msg is None): msg = ('Status (%r) != %r' % (self.status, status)) self._handlewebError(msg) elif isinstance(status, int): code = int(self.status[:3]) if (code != stat...
'Fail if (key, [value]) not in self.headers.'
def assertHeader(self, key, value=None, msg=None):
lowkey = key.lower() for (k, v) in self.headers: if (k.lower() == lowkey): if ((value is None) or (str(value) == v)): return v if (msg is None): if (value is None): msg = ('%r not in headers' % key) else: msg = ('%r:%r n...
'Fail if the header does not contain the specified value'
def assertHeaderItemValue(self, key, value, msg=None):
actual_value = self.assertHeader(key, msg=msg) header_values = map(str.strip, actual_value.split(',')) if (value in header_values): return value if (msg is None): msg = ('%r not in %r' % (value, header_values)) self._handlewebError(msg)
'Fail if key in self.headers.'
def assertNoHeader(self, key, msg=None):
lowkey = key.lower() matches = [k for (k, v) in self.headers if (k.lower() == lowkey)] if matches: if (msg is None): msg = ('%r in headers' % key) self._handlewebError(msg)
'Fail if value != self.body.'
def assertBody(self, value, msg=None):
if isinstance(value, unicodestr): value = value.encode(self.encoding) if (value != self.body): if (msg is None): msg = ('expected body:\n%r\n\nactual body:\n%r' % (value, self.body)) self._handlewebError(msg)
'Fail if value not in self.body.'
def assertInBody(self, value, msg=None):
if isinstance(value, unicodestr): value = value.encode(self.encoding) if (value not in self.body): if (msg is None): msg = ('%r not in body: %s' % (value, self.body)) self._handlewebError(msg)
'Fail if value in self.body.'
def assertNotInBody(self, value, msg=None):
if isinstance(value, unicodestr): value = value.encode(self.encoding) if (value in self.body): if (msg is None): msg = ('%r found in body' % value) self._handlewebError(msg)
'Fail if value (a regex pattern) is not in self.body.'
def assertMatchesBody(self, pattern, msg=None, flags=0):
if isinstance(pattern, unicodestr): pattern = pattern.encode(self.encoding) if (re.search(pattern, self.body, flags) is None): if (msg is None): msg = ('No match for %r in body' % pattern) self._handlewebError(msg)
'Load and start the HTTP server.'
def start(self, modulename=None):
if modulename: cherrypy.server.httpserver = None cherrypy.engine.start() self.sync_apps()
'Tell the server about any apps which the setup functions mounted.'
def sync_apps(self):
pass
'Hook a new WSGI app into the origin server.'
def sync_apps(self):
cherrypy.server.httpserver.wsgi_app = self.get_app()
'Obtain a new (decorated) WSGI app to hook into the origin server.'
def get_app(self, app=None):
if (app is None): app = cherrypy.tree if self.conquer: try: import wsgiconq except ImportError: warnings.warn('Error importing wsgiconq. pyconquer will not run.') else: app = wsgiconq.WSGILogger(app, c_calls=True) if self....
''
def setup_class(cls):
conf = get_tst_config() supervisor_factory = cls.available_servers.get(conf.get('server', 'wsgi')) if (supervisor_factory is None): raise RuntimeError(('Unknown server in config: %s' % conf['server'])) supervisor = supervisor_factory(**conf) cherrypy.config.reset() baseconf =...
''
def teardown_class(cls):
if hasattr(cls, 'setup_server'): cls.supervisor.stop()
'Open the url. Return status, headers, body.'
def getPage(self, url, headers=None, method='GET', body=None, protocol=None):
if self.script_name: url = httputil.urljoin(self.script_name, url) return webtest.WebCase.getPage(self, url, headers, method, body, protocol)
'Compare the response body with a built in error page. The function will optionally look for the regexp pattern, within the exception embedded in the error page.'
def assertErrorPage(self, status, message=None, pattern=''):
page = cherrypy._cperror.get_error_page(status, message=message) esc = re.escape epage = esc(page) epage = epage.replace(esc('<pre id="traceback"></pre>'), ((esc('<pre id="traceback">') + '(.*)') + esc('</pre>'))) m = re.match(ntob(epage, self.encoding), self.body, re.DOTALL) if (not m): ...
'Assert abs(dt1 - dt2) is within Y seconds.'
def assertEqualDates(self, dt1, dt2, seconds=None):
if (seconds is None): seconds = self.date_tolerance if (dt1 > dt2): diff = (dt1 - dt2) else: diff = (dt2 - dt1) if (not (diff < datetime.timedelta(seconds=seconds))): raise AssertionError(('%r and %r are not within %r seconds.' % (dt1, dt2, seconds)))...
'Start cherryd in a subprocess.'
def start(self, imports=None):
cherrypy._cpserver.wait_for_free_port(self.host, self.port) args = [sys.executable, os.path.join(thisdir, '..', 'cherryd'), '-c', self.config_file, '-p', self.pid_file] if (not isinstance(imports, (list, tuple))): imports = [imports] for i in imports: if i: args.append('-i') ...
'Wait for the process to exit.'
def join(self):
try: try: os.wait() except AttributeError: try: pid = self.get_pid() except IOError: pass else: os.waitpid(pid, 0) except OSError: x = sys.exc_info()[1] if (x.args != (10, 'No child...
'Gracefully shutdown a server that is serving forever.'
def stop(self):
read_process(APACHE_PATH, '-k stop')
'Gracefully shutdown a server that is serving forever.'
def stop(self):
read_process(APACHE_PATH, '-k stop')
'Gracefully shutdown a server that is serving forever.'
def stop(self):
read_process(APACHE_PATH, '-k stop') helper.LocalServer.stop(self)
'Set handler and config for the current request.'
def __call__(self, path_info):
request = cherrypy.serving.request (func, vpath) = self.find_handler(path_info) if func: vpath = [x.replace('%2F', '/') for x in vpath] request.handler = LateParamPageHandler(func, *vpath) else: request.handler = cherrypy.NotFound()
'Return the appropriate page handler, plus any virtual path. This will return two objects. The first will be a callable, which can be used to generate page output. Any parameters from the query string or request body will be sent to that callable as keyword arguments. The callable is found by traversing the application...
def find_handler(self, path):
request = cherrypy.serving.request app = request.app root = app.root dispatch_name = self.dispatch_method_name fullpath = ([x for x in path.strip('/').split('/') if x] + ['index']) fullpath_len = len(fullpath) segleft = fullpath_len nodeconf = {} if hasattr(root, '_cp_config'): ...
'Set handler and config for the current request.'
def __call__(self, path_info):
request = cherrypy.serving.request (resource, vpath) = self.find_handler(path_info) if resource: avail = [m for m in dir(resource) if m.isupper()] if (('GET' in avail) and ('HEAD' not in avail)): avail.append('HEAD') avail.sort() cherrypy.serving.response.headers[...
'Routes dispatcher Set full_result to True if you wish the controller and the action to be passed on to the page handler parameters. By default they won\'t be.'
def __init__(self, full_result=False):
import routes self.full_result = full_result self.controllers = {} self.mapper = routes.Mapper() self.mapper.controller_scan = self.controllers.keys
'Set handler and config for the current request.'
def __call__(self, path_info):
func = self.find_handler(path_info) if func: cherrypy.serving.request.handler = LateParamPageHandler(func) else: cherrypy.serving.request.handler = cherrypy.NotFound()
'Find the right page handler, and set request.config.'
def find_handler(self, path_info):
import routes request = cherrypy.serving.request config = routes.request_config() config.mapper = self.mapper if hasattr(request, 'wsgi_environ'): config.environ = request.wsgi_environ config.host = request.headers.get('Host', None) config.protocol = request.scheme config.redirec...
'Return a (httpserver, bind_addr) pair based on self attributes.'
def httpserver_from_self(self, httpserver=None):
if (httpserver is None): httpserver = self.instance if (httpserver is None): from cherrypy import _cpwsgi_server httpserver = _cpwsgi_server.CPWSGIServer(self) if isinstance(httpserver, basestring): httpserver = attributes(httpserver)(self) return (httpserver, self.bind_a...
'Start the HTTP server.'
def start(self):
if (not self.httpserver): (self.httpserver, self.bind_addr) = self.httpserver_from_self() ServerAdapter.start(self)
'Return the base (scheme://host[:port] or sock file) for this server.'
def base(self):
if self.socket_file: return self.socket_file host = self.socket_host if (host in ('0.0.0.0', '::')): import socket host = socket.gethostname() port = self.socket_port if self.ssl_certificate: scheme = 'https' if (port != 443): host += (':%s' % port...
'Run self.callback(**self.kwargs).'
def __call__(self):
return self.callback(**self.kwargs)
'Append a new Hook made from the supplied arguments.'
def attach(self, point, callback, failsafe=None, priority=None, **kwargs):
self[point].append(Hook(callback, failsafe, priority, **kwargs))
'Execute all registered Hooks (callbacks) for the given point.'
def run(self, point):
exc = None hooks = self[point] hooks.sort() for hook in hooks: if ((exc is None) or hook.failsafe): try: hook() except (KeyboardInterrupt, SystemExit): raise except (cherrypy.HTTPError, cherrypy.HTTPRedirect, cherrypy.InternalRe...
'Populate a new Request object. local_host should be an httputil.Host object with the server info. remote_host should be an httputil.Host object with the client info. scheme should be a string, either "http" or "https".'
def __init__(self, local_host, remote_host, scheme='http', server_protocol='HTTP/1.1'):
self.local = local_host self.remote = remote_host self.scheme = scheme self.server_protocol = server_protocol self.closed = False self.error_page = self.error_page.copy() self.namespaces = self.namespaces.copy() self.stage = None
'Run cleanup code. (Core)'
def close(self):
if (not self.closed): self.closed = True self.stage = 'on_end_request' self.hooks.run('on_end_request') self.stage = 'close'
'Process the Request. (Core) method, path, query_string, and req_protocol should be pulled directly from the Request-Line (e.g. "GET /path?key=val HTTP/1.0"). path This should be %XX-unquoted, but query_string should not be. When using Python 2, they both MUST be byte strings, not unicode strings. When using Python 3, ...
def run(self, method, path, query_string, req_protocol, headers, rfile):
response = cherrypy.serving.response self.stage = 'run' try: self.error_response = cherrypy.HTTPError(500).set_response self.method = method path = (path or '/') self.query_string = (query_string or '') self.params = {} rp = (int(req_protocol[5]), int(req_prot...
'Generate a response for the resource at self.path_info. (Core)'
def respond(self, path_info):
response = cherrypy.serving.response try: try: if (self.app is None): raise cherrypy.NotFound() self.stage = 'process_headers' self.process_headers() self.hooks = self.__class__.hooks.copy() self.toolmaps = {} self.s...
'Parse the query string into Python structures. (Core)'
def process_query_string(self):
try: p = httputil.parse_query_string(self.query_string, encoding=self.query_string_encoding) except UnicodeDecodeError: raise cherrypy.HTTPError(404, ('The given query string could not be processed. Query strings for this resource must be encoded w...
'Parse HTTP header data into Python structures. (Core)'
def process_headers(self):
headers = self.headers for (name, value) in self.header_list: name = name.title() value = value.strip() if ('=?' in value): dict.__setitem__(headers, name, httputil.decode_TEXT(value)) else: dict.__setitem__(headers, name, value) if (name == 'Cooki...
'Call a dispatcher (which sets self.handler and .config). (Core)'
def get_resource(self, path):
dispatch = self.app.find_config(path, 'request.dispatch', self.dispatch) dispatch(path)