desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.'
def get(self, key, default=None):
if (not self.loaded): self.load() return self._data.get(key, default)
'D.update(E) -> None. Update D from E: for k in E: D[k] = E[k].'
def update(self, d):
if (not self.loaded): self.load() self._data.update(d)
'D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D.'
def setdefault(self, key, default=None):
if (not self.loaded): self.load() return self._data.setdefault(key, default)
'D.clear() -> None. Remove all items from D.'
def clear(self):
if (not self.loaded): self.load() self._data.clear()
'D.keys() -> list of D\'s keys.'
def keys(self):
if (not self.loaded): self.load() return self._data.keys()
'D.items() -> list of D\'s (key, value) pairs, as 2-tuples.'
def items(self):
if (not self.loaded): self.load() return self._data.items()
'D.values() -> list of D\'s values.'
def values(self):
if (not self.loaded): self.load() return self._data.values()
'Clean up expired sessions.'
def clean_up(self):
now = self.now() for (_id, (data, expiration_time)) in copyitems(self.cache): if (expiration_time <= now): try: del self.cache[_id] except KeyError: pass try: if self.locks[_id].acquire(blocking=False): ...
'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):
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)
'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 checker = locking.LockChecker(self.id, self.lock_timeout) while (not checker.expired()): try: self.lock = lockfile.LockFile(path) except lockfile.LockError: time.sleep(0.1) el...
'Release the lock on the currently-loaded session data.'
def release_lock(self, path=None):
self.lock.release() self.lock.remove() 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) if self.debug: cherrypy.log('Clean...
'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,)) if self.debug: cherrypy.log('Lock acquired.', 'TOOLS.SESSIONS')
'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() if self.debug: cherrypy.log('Lock acquired.', 'TOOLS.SESSIONS')
'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 = StringIO() 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(...
'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. 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() self._debug_message('No session[username], trying anonymous') if ...
'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):
return list(self.encode_header_items(self.items()))
'Prepare the sequence of name, value tuples into a form suitable for transmitting on the wire for HTTP.'
def encode_header_items(cls, header_items):
for (k, v) in header_items: if isinstance(k, unicodestr): k = cls.encode(k) if (not isinstance(v, basestring)): v = str(v) if isinstance(v, unicodestr): v = cls.encode(v) k = k.translate(header_translate_table, header_translate_deletechars) ...
'Return the given header name or value, encoded for HTTP output.'
def encode(cls, v):
for enc in cls.encodings: try: return v.encode(enc) except UnicodeEncodeError: continue if ((cls.protocol == (1, 1)) and cls.use_rfc_2047): v = b2a_base64(v.encode('utf-8')) return ((ntob('=?utf-8?b?') + v.strip(ntob('\n'))) + ntob('?=')) raise ValueEr...
'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
'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, **mapper_options):
import routes self.full_result = full_result self.controllers = {} self.mapper = routes.Mapper(**mapper_options) 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)
'Handle the last unanticipated exception. (Core)'
def handle_error(self):
try: self.hooks.run('before_error_response') if self.error_response: self.error_response() self.hooks.run('after_error_response') cherrypy.serving.response.finalize() except cherrypy.HTTPRedirect: inst = sys.exc_info()[1] inst.set_response() ch...
'Collapse self.body to a single string; replace it and return it.'
def collapse_body(self):
if isinstance(self.body, basestring): return self.body newbody = [] for chunk in self.body: if (py3k and (not isinstance(chunk, bytes))): raise TypeError(("Chunk %s is not of type 'bytes'." % repr(chunk))) newbody.append(chunk) newbody = ntob('').joi...
'Transform headers (and cookies) into self.header_list. (Core)'
def finalize(self):
try: (code, reason, _) = httputil.valid_status(self.status) except ValueError: raise cherrypy.HTTPError(500, sys.exc_info()[1].args[0]) headers = self.headers self.status = ('%s %s' % (code, reason)) self.output_status = ((ntob(str(code), 'ascii') + ntob(' ')) + headers.encode(...
'If now > self.time + self.timeout, set self.timed_out. This purposefully sets a flag, rather than raising an error, so that a monitor thread can interrupt the Response thread.'
def check_timeout(self):
if (time.time() > (self.time + self.timeout)): self.timed_out = True
'Create new Popen instance.'
def __init__(self, args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=False, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0):
_cleanup() self._child_created = False if (not isinstance(bufsize, (int, long))): raise TypeError('bufsize must be an integer') if mswindows: if (preexec_fn is not None): raise ValueError('preexec_fn is not supported on Windows platforms') ...
'Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate. The optional input argument should be a string to be sent to the child process, or None, if no data should be sent to the child. communicate() returns a tuple (stdout, stderr).'
def communicate(self, input=None):
if ([self.stdin, self.stdout, self.stderr].count(None) >= 2): stdout = None stderr = None if self.stdin: if input: try: self.stdin.write(input) except IOError as e: if ((e.errno != errno.EPIPE) and (e.errno !...
'Parse the next HTTP request start-line and message-headers.'
def parse_request(self):
self.rfile = SizeCheckWrapper(self.conn.rfile, self.server.max_request_header_size) try: success = self.read_request_line() except MaxSizeExceeded: self.simple_response('414 Request-URI Too Long', 'The Request-URI sent with the request exceeds the maximum ...
'Read self.rfile into self.inheaders. Return success.'
def read_request_headers(self):
try: read_headers(self.rfile, self.inheaders) except ValueError: ex = sys.exc_info()[1] self.simple_response('400 Bad Request', ex.args[0]) return False mrbs = self.server.max_request_body_size if (mrbs and (int(self.inheaders.get('Content-Length', 0)) > mrbs)): ...
'Parse a Request-URI into (scheme, authority, path). Note that Request-URI\'s must be one of:: Request-URI = "*" | absoluteURI | abs_path | authority Therefore, a Request-URI which starts with a double forward-slash cannot be a "net_path":: net_path = "//" authority [ abs_path ] Instead, it must be interpreted ...
def parse_request_uri(self, uri):
if (uri == ASTERISK): return (None, None, uri) (scheme, sep, remainder) = uri.partition('://') if (sep and (QUESTION_MARK not in scheme)): (authority, path_a, path_b) = remainder.partition(FORWARD_SLASH) return (scheme.lower(), authority, (path_a + path_b)) if uri.startswith(FORW...
'takes quoted string and unquotes % encoded values'
def unquote_bytes(self, path):
res = path.split('%') for i in range(1, len(res)): item = res[i] try: res[i] = (bytes([int(item[:2], 16)]) + item[2:]) except ValueError: raise return ''.join(res)
'Call the gateway and write its iterable output.'
def respond(self):
mrbs = self.server.max_request_body_size if self.chunked_read: self.rfile = ChunkedRFile(self.conn.rfile, mrbs) else: cl = int(self.inheaders.get('Content-Length', 0)) if (mrbs and (mrbs < cl)): if (not self.sent_headers): self.simple_response('413 Requ...
'Write a simple response back to the client.'
def simple_response(self, status, msg=''):
status = str(status) buf = [(((bytes(self.server.protocol, 'ascii') + SPACE) + bytes(status, 'ISO-8859-1')) + CRLF), bytes(('Content-Length: %s\r\n' % len(msg)), 'ISO-8859-1'), 'Content-Type: text/plain\r\n'] if (status[:3] in ('413', '414')): self.close_connection = True if (self.resp...
'Write unbuffered data to the client.'
def write(self, chunk):
if (self.chunked_write and chunk): buf = [bytes(hex(len(chunk)), 'ASCII')[2:], CRLF, chunk, CRLF] self.conn.wfile.write(EMPTY.join(buf)) else: self.conn.wfile.write(chunk)
'Assert, process, and send the HTTP response message-headers. You must set self.status, and self.outheaders before calling this.'
def send_headers(self):
hkeys = [key.lower() for (key, value) in self.outheaders] status = int(self.status[:3]) if (status == 413): self.close_connection = True elif ('content-length' not in hkeys): if ((status < 200) or (status in (204, 205, 304))): pass elif ((self.response_protocol == 'HT...
'Read each request and respond appropriately.'
def communicate(self):
request_seen = False try: while True: req = None req = self.RequestHandlerClass(self.server, self) req.parse_request() if self.server.stats['Enabled']: self.requests_seen += 1 if (not req.ready): return ...
'Close the socket underlying this connection.'
def close(self):
self.rfile.close() if (not self.linger): self.socket.close() else: pass
'Start the pool of threads.'
def start(self):
for i in range(self.min): self._threads.append(WorkerThread(self.server)) for worker in self._threads: worker.setName(('CP Server ' + worker.getName())) worker.start() for worker in self._threads: while (not worker.ready): time.sleep(0.1)
'Number of worker threads which are idle. Read-only.'
def _get_idle(self):
return len([t for t in self._threads if (t.conn is None)])
'Spawn new worker threads (not above self.max).'
def grow(self, amount):
if (self.max > 0): budget = max((self.max - len(self._threads)), 0) else: budget = float('inf') n_new = min(amount, budget) workers = [self._spawn_worker() for i in range(n_new)] while (not all((worker.ready for worker in workers))): time.sleep(0.1) self._threads.extend(w...
'Kill off worker threads (not below self.min).'
def shrink(self, amount):
for t in self._threads: if (not t.isAlive()): self._threads.remove(t) amount -= 1 n_extra = max((len(self._threads) - self.min), 0) n_to_remove = min(amount, n_extra) for n in range(n_to_remove): self._queue.put(_SHUTDOWNREQUEST)
'Run the server forever.'
def start(self):
self._interrupt = None if (self.software is None): self.software = ('%s Server' % self.version) if isinstance(self.bind_addr, basestring): try: os.unlink(self.bind_addr) except: pass try: os.chmod(self.bind_addr, 511) except: ...
'Create (or recreate) the actual socket object.'
def bind(self, family, type, proto=0):
self.socket = socket.socket(family, type, proto) prevent_socket_inheritance(self.socket) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) if (self.nodelay and (not isinstance(self.bind_addr, str))): self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) if (self.s...
'Accept a new connection and put it on the Queue.'
def tick(self):
try: (s, addr) = self.socket.accept() if self.stats['Enabled']: self.stats['Accepts'] += 1 if (not self.ready): return prevent_socket_inheritance(s) if hasattr(s, 'settimeout'): s.settimeout(self.timeout) makefile = CP_makefile ...
'Gracefully shutdown a server that is serving forever.'
def stop(self):
self.ready = False if (self._start_time is not None): self._run_time += (time.time() - self._start_time) self._start_time = None sock = getattr(self, 'socket', None) if sock: if (not isinstance(self.bind_addr, basestring)): try: (host, port) = sock.getsock...
'Process the current request. Must be overridden in a subclass.'
def respond(self):
raise NotImplemented