desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Ensure all logging output has been flushed. This version does nothing and is intended to be implemented by subclasses.'
def flush(self):
pass
'Tidy up any resources used by the handler. This version removes the handler from an internal map of handlers, _handlers, which is used for handler lookup by name. Subclasses should ensure that this gets called from overridden close() methods.'
def close(self):
_acquireLock() try: if (self._name and (self._name in _handlers)): del _handlers[self._name] finally: _releaseLock()
'Handle errors which occur during an emit() call. This method should be called from handlers when an exception is encountered during an emit() call. If raiseExceptions is false, exceptions get silently ignored. This is what is mostly wanted for a logging system - most users will not care about errors in the logging sys...
def handleError(self, record):
if (raiseExceptions and sys.stderr): (t, v, tb) = sys.exc_info() try: sys.stderr.write('--- Logging error ---\n') traceback.print_exception(t, v, tb, None, sys.stderr) sys.stderr.write('Call stack:\n') frame = tb.tb_frame while ...
'Initialize the handler. If stream is not specified, sys.stderr is used.'
def __init__(self, stream=None):
Handler.__init__(self) if (stream is None): stream = sys.stderr self.stream = stream
'Flushes the stream.'
def flush(self):
self.acquire() try: if (self.stream and hasattr(self.stream, 'flush')): self.stream.flush() finally: self.release()
'Emit a record. If a formatter is specified, it is used to format the record. The record is then written to the stream with a trailing newline. If exception information is present, it is formatted using traceback.print_exception and appended to the stream. If the stream has an \'encoding\' attribute, it is used to de...
def emit(self, record):
try: msg = self.format(record) stream = self.stream stream.write(msg) stream.write(self.terminator) self.flush() except Exception: self.handleError(record)
'Open the specified file and use it as the stream for logging.'
def __init__(self, filename, mode='a', encoding=None, delay=False):
self.baseFilename = os.path.abspath(filename) self.mode = mode self.encoding = encoding self.delay = delay if delay: Handler.__init__(self) self.stream = None else: StreamHandler.__init__(self, self._open())
'Closes the stream.'
def close(self):
self.acquire() try: if self.stream: self.flush() if hasattr(self.stream, 'close'): self.stream.close() self.stream = None StreamHandler.close(self) finally: self.release()
'Open the current base file with the (original) mode and encoding. Return the resulting stream.'
def _open(self):
return open(self.baseFilename, self.mode, encoding=self.encoding)
'Emit a record. If the stream was not opened because \'delay\' was specified in the constructor, open it before calling the superclass\'s emit.'
def emit(self, record):
if (self.stream is None): self.stream = self._open() StreamHandler.emit(self, record)
'Initialize the handler.'
def __init__(self, level=NOTSET):
Handler.__init__(self, level)
'Initialize with the specified logger being a child of this placeholder.'
def __init__(self, alogger):
self.loggerMap = {alogger: None}
'Add the specified logger as a child of this placeholder.'
def append(self, alogger):
if (alogger not in self.loggerMap): self.loggerMap[alogger] = None
'Initialize the manager with the root node of the logger hierarchy.'
def __init__(self, rootnode):
self.root = rootnode self.disable = 0 self.emittedNoHandlerWarning = False self.loggerDict = {} self.loggerClass = None self.logRecordFactory = None
'Get a logger with the specified name (channel name), creating it if it doesn\'t yet exist. This name is a dot-separated hierarchical name, such as "a", "a.b", "a.b.c" or similar. If a PlaceHolder existed for the specified name [i.e. the logger didn\'t exist but a child of it did], replace it with the created logger an...
def getLogger(self, name):
rv = None if (not isinstance(name, str)): raise TypeError('A logger name must be a string') _acquireLock() try: if (name in self.loggerDict): rv = self.loggerDict[name] if isinstance(rv, PlaceHolder): ph = rv rv = ...
'Set the class to be used when instantiating a logger with this Manager.'
def setLoggerClass(self, klass):
if (klass != Logger): if (not issubclass(klass, Logger)): raise TypeError(('logger not derived from logging.Logger: ' + klass.__name__)) self.loggerClass = klass
'Set the factory to be used when instantiating a log record with this Manager.'
def setLogRecordFactory(self, factory):
self.logRecordFactory = factory
'Ensure that there are either loggers or placeholders all the way from the specified logger to the root of the logger hierarchy.'
def _fixupParents(self, alogger):
name = alogger.name i = name.rfind('.') rv = None while ((i > 0) and (not rv)): substr = name[:i] if (substr not in self.loggerDict): self.loggerDict[substr] = PlaceHolder(alogger) else: obj = self.loggerDict[substr] if isinstance(obj, Logger):...
'Ensure that children of the placeholder ph are connected to the specified logger.'
def _fixupChildren(self, ph, alogger):
name = alogger.name namelen = len(name) for c in ph.loggerMap.keys(): if (c.parent.name[:namelen] != name): alogger.parent = c.parent c.parent = alogger
'Initialize the logger with a name and an optional level.'
def __init__(self, name, level=NOTSET):
Filterer.__init__(self) self.name = name self.level = _checkLevel(level) self.parent = None self.propagate = True self.handlers = [] self.disabled = False
'Set the logging level of this logger. level must be an int or a str.'
def setLevel(self, level):
self.level = _checkLevel(level)
'Log \'msg % args\' with severity \'DEBUG\'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.debug("Houston, we have a %s", "thorny problem", exc_info=1)'
def debug(self, msg, *args, **kwargs):
if self.isEnabledFor(DEBUG): self._log(DEBUG, msg, args, **kwargs)
'Log \'msg % args\' with severity \'INFO\'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.info("Houston, we have a %s", "interesting problem", exc_info=1)'
def info(self, msg, *args, **kwargs):
if self.isEnabledFor(INFO): self._log(INFO, msg, args, **kwargs)
'Log \'msg % args\' with severity \'WARNING\'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.warning("Houston, we have a %s", "bit of a problem", exc_info=1)'
def warning(self, msg, *args, **kwargs):
if self.isEnabledFor(WARNING): self._log(WARNING, msg, args, **kwargs)
'Log \'msg % args\' with severity \'ERROR\'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.error("Houston, we have a %s", "major problem", exc_info=1)'
def error(self, msg, *args, **kwargs):
if self.isEnabledFor(ERROR): self._log(ERROR, msg, args, **kwargs)
'Convenience method for logging an ERROR with exception information.'
def exception(self, msg, *args, **kwargs):
kwargs['exc_info'] = True self.error(msg, *args, **kwargs)
'Log \'msg % args\' with severity \'CRITICAL\'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.critical("Houston, we have a %s", "major disaster", exc_info=1)'
def critical(self, msg, *args, **kwargs):
if self.isEnabledFor(CRITICAL): self._log(CRITICAL, msg, args, **kwargs)
'Log \'msg % args\' with the integer severity \'level\'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.log(level, "We have a %s", "mysterious problem", exc_info=1)'
def log(self, level, msg, *args, **kwargs):
if (not isinstance(level, int)): if raiseExceptions: raise TypeError('level must be an integer') else: return if self.isEnabledFor(level): self._log(level, msg, args, **kwargs)
'Find the stack frame of the caller so that we can note the source file name, line number and function name.'
def findCaller(self, stack_info=False):
f = currentframe() if (f is not None): f = f.f_back rv = ('(unknown file)', 0, '(unknown function)', None) while hasattr(f, 'f_code'): co = f.f_code filename = os.path.normcase(co.co_filename) if (filename == _srcfile): f = f.f_back continue ...
'A factory method which can be overridden in subclasses to create specialized LogRecords.'
def makeRecord(self, name, level, fn, lno, msg, args, exc_info, func=None, extra=None, sinfo=None):
rv = _logRecordFactory(name, level, fn, lno, msg, args, exc_info, func, sinfo) if (extra is not None): for key in extra: if ((key in ['message', 'asctime']) or (key in rv.__dict__)): raise KeyError(('Attempt to overwrite %r in LogRecord' % key)) rv....
'Low-level logging routine which creates a LogRecord and then calls all the handlers of this logger to handle the record.'
def _log(self, level, msg, args, exc_info=None, extra=None, stack_info=False):
sinfo = None if _srcfile: try: (fn, lno, func, sinfo) = self.findCaller(stack_info) except ValueError: (fn, lno, func) = ('(unknown file)', 0, '(unknown function)') else: (fn, lno, func) = ('(unknown file)', 0, '(unknown function)') if exc_info...
'Call the handlers for the specified record. This method is used for unpickled records received from a socket, as well as those created locally. Logger-level filtering is applied.'
def handle(self, record):
if ((not self.disabled) and self.filter(record)): self.callHandlers(record)
'Add the specified handler to this logger.'
def addHandler(self, hdlr):
_acquireLock() try: if (not (hdlr in self.handlers)): self.handlers.append(hdlr) finally: _releaseLock()
'Remove the specified handler from this logger.'
def removeHandler(self, hdlr):
_acquireLock() try: if (hdlr in self.handlers): self.handlers.remove(hdlr) finally: _releaseLock()
'See if this logger has any handlers configured. Loop through all handlers for this logger and its parents in the logger hierarchy. Return True if a handler was found, else False. Stop searching up the hierarchy whenever a logger with the "propagate" attribute set to zero is found - that will be the last logger which i...
def hasHandlers(self):
c = self rv = False while c: if c.handlers: rv = True break if (not c.propagate): break else: c = c.parent return rv
'Pass a record to all relevant handlers. Loop through all handlers for this logger and its parents in the logger hierarchy. If no handler was found, output a one-off error message to sys.stderr. Stop searching up the hierarchy whenever a logger with the "propagate" attribute set to zero is found - that will be the last...
def callHandlers(self, record):
c = self found = 0 while c: for hdlr in c.handlers: found = (found + 1) if (record.levelno >= hdlr.level): hdlr.handle(record) if (not c.propagate): c = None else: c = c.parent if (found == 0): if lastResort:...
'Get the effective level for this logger. Loop through this logger and its parents in the logger hierarchy, looking for a non-zero logging level. Return the first one found.'
def getEffectiveLevel(self):
logger = self while logger: if logger.level: return logger.level logger = logger.parent return NOTSET
'Is this logger enabled for level \'level\'?'
def isEnabledFor(self, level):
if (self.manager.disable >= level): return False return (level >= self.getEffectiveLevel())
'Get a logger which is a descendant to this one. This is a convenience method, such that logging.getLogger(\'abc\').getChild(\'def.ghi\') is the same as logging.getLogger(\'abc.def.ghi\') It\'s useful, for example, when the parent logger is named using __name__ rather than a literal string.'
def getChild(self, suffix):
if (self.root is not self): suffix = '.'.join((self.name, suffix)) return self.manager.getLogger(suffix)
'Initialize the logger with the name "root".'
def __init__(self, level):
Logger.__init__(self, 'root', level)
'Initialize the adapter with a logger and a dict-like object which provides contextual information. This constructor signature allows easy stacking of LoggerAdapters, if so desired. You can effectively pass keyword arguments as shown in the following example: adapter = LoggerAdapter(someLogger, dict(p1=v1, p2="v2"))'
def __init__(self, logger, extra):
self.logger = logger self.extra = extra
'Process the logging message and keyword arguments passed in to a logging call to insert contextual information. You can either manipulate the message itself, the keyword args or both. Return the message and kwargs modified (or not) to suit your needs. Normally, you\'ll only need to override this one method in a Logger...
def process(self, msg, kwargs):
kwargs['extra'] = self.extra return (msg, kwargs)
'Delegate a debug call to the underlying logger.'
def debug(self, msg, *args, **kwargs):
self.log(DEBUG, msg, *args, **kwargs)
'Delegate an info call to the underlying logger.'
def info(self, msg, *args, **kwargs):
self.log(INFO, msg, *args, **kwargs)
'Delegate a warning call to the underlying logger.'
def warning(self, msg, *args, **kwargs):
self.log(WARNING, msg, *args, **kwargs)
'Delegate an error call to the underlying logger.'
def error(self, msg, *args, **kwargs):
self.log(ERROR, msg, *args, **kwargs)
'Delegate an exception call to the underlying logger.'
def exception(self, msg, *args, **kwargs):
kwargs['exc_info'] = True self.log(ERROR, msg, *args, **kwargs)
'Delegate a critical call to the underlying logger.'
def critical(self, msg, *args, **kwargs):
self.log(CRITICAL, msg, *args, **kwargs)
'Delegate a log call to the underlying logger, after adding contextual information from this adapter instance.'
def log(self, level, msg, *args, **kwargs):
if self.isEnabledFor(level): (msg, kwargs) = self.process(msg, kwargs) self.logger._log(level, msg, args, **kwargs)
'Is this logger enabled for level \'level\'?'
def isEnabledFor(self, level):
if (self.logger.manager.disable >= level): return False return (level >= self.getEffectiveLevel())
'Set the specified level on the underlying logger.'
def setLevel(self, level):
self.logger.setLevel(level)
'Get the effective level for the underlying logger.'
def getEffectiveLevel(self):
return self.logger.getEffectiveLevel()
'See if the underlying logger has any handlers.'
def hasHandlers(self):
return self.logger.hasHandlers()
'Test that a character pointer-to-pointer is correctly passed'
def test_charpp(self):
dll = CDLL(_ctypes_test.__file__) func = dll._testfunc_c_p_p func.restype = c_char_p argv = (c_char_p * 2)() argc = c_int(2) argv[0] = 'hello' argv[1] = 'world' result = func(byref(argc), argv) self.assertEqual(result, 'world')
'Write the snapshot into a file.'
def dump(self, filename):
with open(filename, 'wb') as fp: pickle.dump(self, fp, pickle.HIGHEST_PROTOCOL)
'Load a snapshot from a file.'
@staticmethod def load(filename):
with open(filename, 'rb') as fp: return pickle.load(fp)
'Create a new Snapshot instance with a filtered traces sequence, filters is a list of Filter instances. If filters is an empty list, return a new Snapshot instance with a copy of the traces.'
def filter_traces(self, filters):
if (not isinstance(filters, Iterable)): raise TypeError(('filters must be a list of filters, not %s' % type(filters).__name__)) if filters: include_filters = [] exclude_filters = [] for trace_filter in filters: if trace_filter.inclusive: ...
'Group statistics by key_type. Return a sorted list of Statistic instances.'
def statistics(self, key_type, cumulative=False):
grouped = self._group_by(key_type, cumulative) statistics = list(grouped.values()) statistics.sort(reverse=True, key=Statistic._sort_key) return statistics
'Compute the differences with an old snapshot old_snapshot. Get statistics as a sorted list of StatisticDiff instances, grouped by group_by.'
def compare_to(self, old_snapshot, key_type, cumulative=False):
new_group = self._group_by(key_type, cumulative) old_group = old_snapshot._group_by(key_type, cumulative) statistics = _compare_grouped_stats(old_group, new_group) statistics.sort(reverse=True, key=StatisticDiff._sort_key) return statistics
'real_value, coded_value = value_decode(STRING) Called prior to setting a cookie\'s value from the network representation. The VALUE is the value read from HTTP header. Override this function to modify the behavior of cookies.'
def value_decode(self, val):
return (val, val)
'real_value, coded_value = value_encode(VALUE) Called prior to setting a cookie\'s value from the dictionary representation. The VALUE is the value being assigned. Override this function to modify the behavior of cookies.'
def value_encode(self, val):
strval = str(val) return (strval, strval)
'Private method for setting a cookie\'s value'
def __set(self, key, real_value, coded_value):
M = self.get(key, Morsel()) M.set(key, real_value, coded_value) dict.__setitem__(self, key, M)
'Dictionary style assignment.'
def __setitem__(self, key, value):
(rval, cval) = self.value_encode(value) self.__set(key, rval, cval)
'Return a string suitable for HTTP.'
def output(self, attrs=None, header='Set-Cookie:', sep='\r\n'):
result = [] items = sorted(self.items()) for (key, value) in items: result.append(value.output(attrs, header)) return sep.join(result)
'Return a string suitable for JavaScript.'
def js_output(self, attrs=None):
result = [] items = sorted(self.items()) for (key, value) in items: result.append(value.js_output(attrs)) return _nulljoin(result)
'Load cookies from a string (presumably HTTP_COOKIE) or from a dictionary. Loading cookies from a dictionary \'d\' is equivalent to calling: map(Cookie.__setitem__, d.keys(), d.values())'
def load(self, rawdata):
if isinstance(rawdata, str): self.__parse_string(rawdata) else: for (key, value) in rawdata.items(): self[key] = value return
'Override server_bind to store the server name.'
def server_bind(self):
socketserver.TCPServer.server_bind(self) (host, port) = self.socket.getsockname()[:2] self.server_name = socket.getfqdn(host) self.server_port = port
'Parse a request (internal). The request should be stored in self.raw_requestline; the results are in self.command, self.path, self.request_version and self.headers. Return True for success, False for failure; on failure, an error is sent back.'
def parse_request(self):
self.command = None self.request_version = version = self.default_request_version self.close_connection = 1 requestline = str(self.raw_requestline, 'iso-8859-1') requestline = requestline.rstrip('\r\n') self.requestline = requestline words = requestline.split() if (len(words) == 3): ...
'Decide what to do with an "Expect: 100-continue" header. If the client is expecting a 100 Continue response, we must respond with either a 100 Continue or a final response before waiting for the request body. The default is to always respond with a 100 Continue. You can behave differently (for example, reject unauthor...
def handle_expect_100(self):
self.send_response_only(100) self.end_headers() return True
'Handle a single HTTP request. You normally don\'t need to override this method; see the class __doc__ string for information on how to handle specific HTTP commands such as GET and POST.'
def handle_one_request(self):
try: self.raw_requestline = self.rfile.readline(65537) if (len(self.raw_requestline) > 65536): self.requestline = '' self.request_version = '' self.command = '' self.send_error(414) return if (not self.raw_requestline): ...
'Handle multiple requests if necessary.'
def handle(self):
self.close_connection = 1 self.handle_one_request() while (not self.close_connection): self.handle_one_request()
'Send and log an error reply. Arguments are * code: an HTTP error code 3 digits * message: a simple optional 1 line reason phrase. *( HTAB / SP / VCHAR / %x80-FF ) defaults to short entry matching the response code * explain: a detailed message defaults to the long entry matching the response code. This sends an err...
def send_error(self, code, message=None, explain=None):
try: (shortmsg, longmsg) = self.responses[code] except KeyError: (shortmsg, longmsg) = ('???', '???') if (message is None): message = shortmsg if (explain is None): explain = longmsg self.log_error('code %d, message %s', code, message) content = (self.err...
'Add the response header to the headers buffer and log the response code. Also send two standard headers with the server software version and the current date.'
def send_response(self, code, message=None):
self.log_request(code) self.send_response_only(code, message) self.send_header('Server', self.version_string()) self.send_header('Date', self.date_time_string())
'Send the response header only.'
def send_response_only(self, code, message=None):
if (message is None): if (code in self.responses): message = self.responses[code][0] else: message = '' if (self.request_version != 'HTTP/0.9'): if (not hasattr(self, '_headers_buffer')): self._headers_buffer = [] self._headers_buffer.append(('...
'Send a MIME header to the headers buffer.'
def send_header(self, keyword, value):
if (self.request_version != 'HTTP/0.9'): if (not hasattr(self, '_headers_buffer')): self._headers_buffer = [] self._headers_buffer.append(('%s: %s\r\n' % (keyword, value)).encode('latin-1', 'strict')) if (keyword.lower() == 'connection'): if (value.lower() == 'close'): ...
'Send the blank line ending the MIME headers.'
def end_headers(self):
if (self.request_version != 'HTTP/0.9'): self._headers_buffer.append('\r\n') self.flush_headers()
'Log an accepted request. This is called by send_response().'
def log_request(self, code='-', size='-'):
self.log_message('"%s" %s %s', self.requestline, str(code), str(size))
'Log an error. This is called when a request cannot be fulfilled. By default it passes the message on to log_message(). Arguments are the same as for log_message(). XXX This should go to the separate error log.'
def log_error(self, format, *args):
self.log_message(format, *args)
'Log an arbitrary message. This is used by all other logging functions. Override it if you have specific logging wishes. The first argument, FORMAT, is a format string for the message to be logged. If the format string contains any % escapes requiring parameters, they should be specified as subsequent arguments (it\'...
def log_message(self, format, *args):
sys.stderr.write(('%s - - [%s] %s\n' % (self.address_string(), self.log_date_time_string(), (format % args))))
'Return the server software version string.'
def version_string(self):
return ((self.server_version + ' ') + self.sys_version)
'Return the current date and time formatted for a message header.'
def date_time_string(self, timestamp=None):
if (timestamp is None): timestamp = time.time() (year, month, day, hh, mm, ss, wd, y, z) = time.gmtime(timestamp) s = ('%s, %02d %3s %4d %02d:%02d:%02d GMT' % (self.weekdayname[wd], day, self.monthname[month], year, hh, mm, ss)) return s
'Return the current time formatted for logging.'
def log_date_time_string(self):
now = time.time() (year, month, day, hh, mm, ss, x, y, z) = time.localtime(now) s = ('%02d/%3s/%04d %02d:%02d:%02d' % (day, self.monthname[month], year, hh, mm, ss)) return s
'Return the client address.'
def address_string(self):
return self.client_address[0]
'Serve a GET request.'
def do_GET(self):
f = self.send_head() if f: try: self.copyfile(f, self.wfile) finally: f.close()
'Serve a HEAD request.'
def do_HEAD(self):
f = self.send_head() if f: f.close()
'Common code for GET and HEAD commands. This sends the response code and MIME headers. Return value is either a file object (which has to be copied to the outputfile by the caller unless the command was HEAD, and must be closed by the caller under all circumstances), or None, in which case the caller has nothing furthe...
def send_head(self):
path = self.translate_path(self.path) f = None if os.path.isdir(path): if (not self.path.endswith('/')): self.send_response(301) self.send_header('Location', (self.path + '/')) self.end_headers() return None for index in ('index.html', 'index.h...
'Helper to produce a directory listing (absent index.html). Return value is either a file object, or None (indicating an error). In either case, the headers are sent, making the interface the same as for send_head().'
def list_directory(self, path):
try: list = os.listdir(path) except OSError: self.send_error(404, 'No permission to list directory') return None list.sort(key=(lambda a: a.lower())) r = [] try: displaypath = urllib.parse.unquote(self.path, errors='surrogatepass') except UnicodeDecode...
'Translate a /-separated PATH to the local filename syntax. Components that mean special things to the local file system (e.g. drive or directory names) are ignored. (XXX They should probably be diagnosed.)'
def translate_path(self, path):
path = path.split('?', 1)[0] path = path.split('#', 1)[0] trailing_slash = path.rstrip().endswith('/') try: path = urllib.parse.unquote(path, errors='surrogatepass') except UnicodeDecodeError: path = urllib.parse.unquote(path) path = posixpath.normpath(path) words = path.spli...
'Copy all data between two file objects. The SOURCE argument is a file object open for reading (or anything with a read() method) and the DESTINATION argument is a file object open for writing (or anything with a write() method). The only reason for overriding this would be to change the block size or perhaps to replac...
def copyfile(self, source, outputfile):
shutil.copyfileobj(source, outputfile)
'Guess the type of a file. Argument is a PATH (a filename). Return value is a string of the form type/subtype, usable for a MIME Content-type header. The default implementation looks the file\'s extension up in the table self.extensions_map, using application/octet-stream as a default; however it would be permissible (...
def guess_type(self, path):
(base, ext) = posixpath.splitext(path) if (ext in self.extensions_map): return self.extensions_map[ext] ext = ext.lower() if (ext in self.extensions_map): return self.extensions_map[ext] else: return self.extensions_map['']
'Serve a POST request. This is only implemented for CGI scripts.'
def do_POST(self):
if self.is_cgi(): self.run_cgi() else: self.send_error(501, 'Can only POST to CGI scripts')
'Version of send_head that support CGI scripts'
def send_head(self):
if self.is_cgi(): return self.run_cgi() else: return SimpleHTTPRequestHandler.send_head(self)
'Test whether self.path corresponds to a CGI script. Returns True and updates the cgi_info attribute to the tuple (dir, rest) if self.path requires running a CGI script. Returns False otherwise. If any exception is raised, the caller should assume that self.path was rejected as invalid and act accordingly. The default ...
def is_cgi(self):
collapsed_path = _url_collapse_path(urllib.parse.unquote(self.path)) dir_sep = collapsed_path.find('/', 1) (head, tail) = (collapsed_path[:dir_sep], collapsed_path[(dir_sep + 1):]) if (head in self.cgi_directories): self.cgi_info = (head, tail) return True return False
'Test whether argument path is an executable file.'
def is_executable(self, path):
return executable(path)
'Test whether argument path is a Python script.'
def is_python(self, path):
(head, tail) = os.path.splitext(path) return (tail.lower() in ('.py', '.pyw'))
'Execute a CGI script.'
def run_cgi(self):
(dir, rest) = self.cgi_info path = ((dir + '/') + rest) i = path.find('/', (len(dir) + 1)) while (i >= 0): nextdir = path[:i] nextrest = path[(i + 1):] scriptdir = self.translate_path(nextdir) if os.path.isdir(scriptdir): (dir, rest) = (nextdir, nextrest) ...
'Return the dict for the current thread. Raises KeyError if none defined.'
def get_dict(self):
thread = current_thread() return self.dicts[id(thread)][1]
'Create a new dict for the current thread, and return it.'
def create_dict(self):
localdict = {} key = self.key thread = current_thread() idt = id(thread) def local_deleted(_, key=key): thread = wrthread() if (thread is not None): del thread.__dict__[key] def thread_deleted(_, idt=idt): local = wrlocal() if (local is not None): ...
'Get optional transport information.'
def get_extra_info(self, name, default=None):
return self._extra.get(name, default)
'Close the transport. Buffered data will be flushed asynchronously. No more data will be received. After all buffered data is flushed, the protocol\'s connection_lost() method will (eventually) called with None as its argument.'
def close(self):
raise NotImplementedError