desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Rename this path to the given path, clobbering the existing destination if it exists.'
def replace(self, target):
if self._closed: self._raise_closed() self._accessor.replace(self, target)
'Make this path a symlink pointing to the given path. Note the order of arguments (self, target) is the reverse of os.symlink\'s.'
def symlink_to(self, target, target_is_directory=False):
if self._closed: self._raise_closed() self._accessor.symlink(target, self, target_is_directory)
'Whether this path exists.'
def exists(self):
try: self.stat() except OSError as e: if (e.errno != ENOENT): raise return False return True
'Whether this path is a directory.'
def is_dir(self):
try: return S_ISDIR(self.stat().st_mode) except OSError as e: if (e.errno != ENOENT): raise return False
'Whether this path is a regular file (also True for symlinks pointing to regular files).'
def is_file(self):
try: return S_ISREG(self.stat().st_mode) except OSError as e: if (e.errno != ENOENT): raise return False
'Whether this path is a symbolic link.'
def is_symlink(self):
try: return S_ISLNK(self.lstat().st_mode) except OSError as e: if (e.errno != ENOENT): raise return False
'Whether this path is a block device.'
def is_block_device(self):
try: return S_ISBLK(self.stat().st_mode) except OSError as e: if (e.errno != ENOENT): raise return False
'Whether this path is a character device.'
def is_char_device(self):
try: return S_ISCHR(self.stat().st_mode) except OSError as e: if (e.errno != ENOENT): raise return False
'Whether this path is a FIFO.'
def is_fifo(self):
try: return S_ISFIFO(self.stat().st_mode) except OSError as e: if (e.errno != ENOENT): raise return False
'Whether this path is a socket.'
def is_socket(self):
try: return S_ISSOCK(self.stat().st_mode) except OSError as e: if (e.errno != ENOENT): raise return False
'Create a new HMAC object. key: key for the keyed hash object. msg: Initial input for the hash, if provided. digestmod: A module supporting PEP 247. *OR* A hashlib constructor returning a new hash object. *OR* A hash name suitable for hashlib.new(). Defaults to hashlib.md5. Implicit default to hashlib.md5 ...
def __init__(self, key, msg=None, digestmod=None):
if (not isinstance(key, (bytes, bytearray))): raise TypeError(('key: expected bytes or bytearray, but got %r' % type(key).__name__)) if (digestmod is None): _warnings.warn('HMAC() without an explicit digestmod argument is deprecated.', PendingDeprecation...
'Update this hashing object with the string msg.'
def update(self, msg):
self.inner.update(msg)
'Return a separate copy of this hashing object. An update to this copy won\'t affect the original object.'
def copy(self):
other = self.__class__.__new__(self.__class__) other.digest_cons = self.digest_cons other.digest_size = self.digest_size other.inner = self.inner.copy() other.outer = self.outer.copy() return other
'Return a hash object for the current state. To be used only internally with digest() and hexdigest().'
def _current(self):
h = self.outer.copy() h.update(self.inner.digest()) return h
'Return the hash value of this hashing object. This returns a string containing 8-bit data. The object is not altered in any way by this function; you can continue updating the object after calling this function.'
def digest(self):
h = self._current() return h.digest()
'Like digest(), but returns a string of hexadecimal digits instead.'
def hexdigest(self):
h = self._current() return h.hexdigest()
'Called when the given test is about to be run'
def startTest(self, test):
self.testsRun += 1 self._mirrorOutput = False self._setupStdout()
'Called when the given test has been run'
def stopTest(self, test):
self._restoreStdout() self._mirrorOutput = False
'Called when an error has occurred. \'err\' is a tuple of values as returned by sys.exc_info().'
@failfast def addError(self, test, err):
self.errors.append((test, self._exc_info_to_string(err, test))) self._mirrorOutput = True
'Called when an error has occurred. \'err\' is a tuple of values as returned by sys.exc_info().'
@failfast def addFailure(self, test, err):
self.failures.append((test, self._exc_info_to_string(err, test))) self._mirrorOutput = True
'Called at the end of a subtest. \'err\' is None if the subtest ended successfully, otherwise it\'s a tuple of values as returned by sys.exc_info().'
@failfast def addSubTest(self, test, subtest, err):
if (err is not None): if issubclass(err[0], test.failureException): errors = self.failures else: errors = self.errors errors.append((subtest, self._exc_info_to_string(err, test))) self._mirrorOutput = True
'Called when a test has completed successfully'
def addSuccess(self, test):
pass
'Called when a test is skipped.'
def addSkip(self, test, reason):
self.skipped.append((test, reason))
'Called when an expected failure/error occured.'
def addExpectedFailure(self, test, err):
self.expectedFailures.append((test, self._exc_info_to_string(err, test)))
'Called when a test was expected to fail, but succeed.'
@failfast def addUnexpectedSuccess(self, test):
self.unexpectedSuccesses.append(test)
'Tells whether or not this result was a success.'
def wasSuccessful(self):
return ((len(self.failures) == len(self.errors) == 0) and ((not hasattr(self, 'unexpectedSuccesses')) or (len(self.unexpectedSuccesses) == 0)))
'Indicates that the tests should be aborted.'
def stop(self):
self.shouldStop = True
'Converts a sys.exc_info()-style tuple of values into a string.'
def _exc_info_to_string(self, err, test):
(exctype, value, tb) = err while (tb and self._is_relevant_tb_level(tb)): tb = tb.tb_next if (exctype is test.failureException): length = self._count_relevant_tb_levels(tb) msgLines = traceback.format_exception(exctype, value, tb, length) else: msgLines = traceback.format...
'Run the given test case or test suite.'
def run(self, test):
result = self._makeResult() registerResult(result) result.failfast = self.failfast result.buffer = self.buffer with warnings.catch_warnings(): if self.warnings: warnings.simplefilter(self.warnings) if (self.warnings in ['default', 'always']): warnings....
'Tests shortDescription() for a method with a docstring.'
@unittest.skipIf((sys.flags.optimize >= 2), 'Docstrings are omitted with -O2 and above') def testShortDescriptionWithOneLineDocstring(self):
self.assertEqual(self.shortDescription(), 'Tests shortDescription() for a method with a docstring.')
'Tests shortDescription() for a method with a longer docstring. This method ensures that only the first line of a docstring is returned used in the short description, no matter how long the whole thing is.'
@unittest.skipIf((sys.flags.optimize >= 2), 'Docstrings are omitted with -O2 and above') def testShortDescriptionWithMultiLineDocstring(self):
self.assertEqual(self.shortDescription(), 'Tests shortDescription() for a method with a longer docstring.')
'Test that the deprecated methods raise a DeprecationWarning. See #9424.'
def testDeprecatedMethodNames(self):
old = ((self.failIfEqual, (3, 5)), (self.assertNotEquals, (3, 5)), (self.failUnlessEqual, (3, 3)), (self.assertEquals, (3, 3)), (self.failUnlessAlmostEqual, (2.0, 2.0)), (self.assertAlmostEquals, (2.0, 2.0)), (self.failIfAlmostEqual, (3.0, 5.0)), (self.assertNotAlmostEquals, (3.0, 5.0)), (self.failUnless, (True,)),...
'Test that the deprecated fail* methods get removed in 3.x'
def _testDeprecatedFailMethods(self):
if (sys.version_info[:2] < (3, 3)): return deprecated_names = ['failIfEqual', 'failUnlessEqual', 'failUnlessAlmostEqual', 'failIfAlmostEqual', 'failUnless', 'failUnlessRaises', 'failIf', 'assertDictContainsSubset'] for deprecated_name in deprecated_names: with self.assertRaises(AttributeErro...
'Check that warnings argument of TextTestRunner correctly affects the behavior of the warnings.'
def test_warnings(self):
def get_parse_out_err(p): return [b.splitlines() for b in p.communicate()] opts = dict(stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=os.path.dirname(__file__)) ae_msg = 'Please use assertEqual instead.' at_msg = 'Please use assertTrue instead.' p = subprocess.Popen([s...
'Test the warnings argument'
def testWarning(self):
class FakeTP(unittest.TestProgram, ): def parseArgs(self, *args, **kw): pass def runTests(self, *args, **kw): pass warnoptions = sys.warnoptions[:] try: sys.warnoptions[:] = [] self.assertEqual(FakeTP().warnings, 'default') self.assertEqual(Fak...
'Stop holding a reference to the TestCase at index.'
def _removeTestAtIndex(self, index):
try: test = self._tests[index] except TypeError: pass else: if hasattr(test, 'countTestCases'): self._removed_tests += test.countTestCases() self._tests[index] = None
'Run the tests without collecting errors in a TestResult'
def debug(self):
for test in self: test.debug()
'Run the tests without collecting errors in a TestResult'
def debug(self):
debug = _DebugResult() self.run(debug, True)
'Read at least wtd bytes (or until EOF)'
def read(self, totalwtd):
decdata = '' wtd = totalwtd while (wtd > 0): if self.eof: return decdata wtd = (((wtd + 2) // 3) * 4) data = self.ifp.read(wtd) while True: try: (decdatacur, self.eof) = binascii.a2b_hqx(data) break except bi...
'The implementation for this class returns the max_count attribute from the specialized header class that would be used to construct a header of type \'name\'.'
def header_max_count(self, name):
return self.header_factory[name].max_count
'The name is parsed as everything up to the \':\' and returned unmodified. The value is determined by stripping leading whitespace off the remainder of the first line, joining all subsequent lines together, and stripping any trailing carriage return or linefeed characters. (This is the same as Compat32).'
def header_source_parse(self, sourcelines):
(name, value) = sourcelines[0].split(':', 1) value = (value.lstrip(' DCTB ') + ''.join(sourcelines[1:])) return (name, value.rstrip('\r\n'))
'The name is returned unchanged. If the input value has a \'name\' attribute and it matches the name ignoring case, the value is returned unchanged. Otherwise the name and value are passed to header_factory method, and the resulting custom header object is returned as the value. In this case a ValueError is raised i...
def header_store_parse(self, name, value):
if (hasattr(value, 'name') and (value.name.lower() == name.lower())): return (name, value) if (isinstance(value, str) and (len(value.splitlines()) > 1)): raise ValueError('Header values may not contain linefeed or carriage return characters') return (name, self.hea...
'If the value has a \'name\' attribute, it is returned to unmodified. Otherwise the name and the value with any linesep characters removed are passed to the header_factory method, and the resulting custom header object is returned. Any surrogateescaped bytes get turned into the unicode unknown-character glyph.'
def header_fetch_parse(self, name, value):
if hasattr(value, 'name'): return value return self.header_factory(name, ''.join(value.splitlines()))
'Header folding is controlled by the refold_source policy setting. A value is considered to be a \'source value\' if and only if it does not have a \'name\' attribute (having a \'name\' attribute means it is a header object of some sort). If a source value needs to be refolded according to the policy, it is converted...
def fold(self, name, value):
return self._fold(name, value, refold_binary=True)
'The same as fold if cte_type is 7bit, except that the returned value is bytes. If cte_type is 8bit, non-ASCII binary data is converted back into bytes. Headers with binary data are not refolded, regardless of the refold_header setting, since there is no way to know whether the binary data consists of single byte char...
def fold_binary(self, name, value):
folded = self._fold(name, value, refold_binary=(self.cte_type == '7bit')) return folded.encode('ascii', 'surrogateescape')
'Initialize a new instance. `field\' is an unparsed address header field, containing one or more addresses.'
def __init__(self, field):
self.specials = '()<>@,:;."[]' self.pos = 0 self.LWS = ' DCTB ' self.CR = '\r\n' self.FWS = (self.LWS + self.CR) self.atomends = ((self.specials + self.LWS) + self.CR) self.phraseends = self.atomends.replace('.', '') self.field = field self.commentlist = []
'Skip white space and extract comments.'
def gotonext(self):
wslist = [] while (self.pos < len(self.field)): if (self.field[self.pos] in (self.LWS + '\n\r')): if (self.field[self.pos] not in '\n\r'): wslist.append(self.field[self.pos]) self.pos += 1 elif (self.field[self.pos] == '('): self.commentlist.ap...
'Parse all addresses. Returns a list containing all of the addresses.'
def getaddrlist(self):
result = [] while (self.pos < len(self.field)): ad = self.getaddress() if ad: result += ad else: result.append(('', '')) return result
'Parse the next address.'
def getaddress(self):
self.commentlist = [] self.gotonext() oldpos = self.pos oldcl = self.commentlist plist = self.getphraselist() self.gotonext() returnlist = [] if (self.pos >= len(self.field)): if plist: returnlist = [(SPACE.join(self.commentlist), plist[0])] elif (self.field[self....
'Parse a route address (Return-path value). This method just skips all the route stuff and returns the addrspec.'
def getrouteaddr(self):
if (self.field[self.pos] != '<'): return expectroute = False self.pos += 1 self.gotonext() adlist = '' while (self.pos < len(self.field)): if expectroute: self.getdomain() expectroute = False elif (self.field[self.pos] == '>'): self.pos...
'Parse an RFC 2822 addr-spec.'
def getaddrspec(self):
aslist = [] self.gotonext() while (self.pos < len(self.field)): preserve_ws = True if (self.field[self.pos] == '.'): if (aslist and (not aslist[(-1)].strip())): aslist.pop() aslist.append('.') self.pos += 1 preserve_ws = False ...
'Get the complete domain name from an address.'
def getdomain(self):
sdlist = [] while (self.pos < len(self.field)): if (self.field[self.pos] in self.LWS): self.pos += 1 elif (self.field[self.pos] == '('): self.commentlist.append(self.getcomment()) elif (self.field[self.pos] == '['): sdlist.append(self.getdomainliteral(...
'Parse a header fragment delimited by special characters. `beginchar\' is the start character for the fragment. If self is not looking at an instance of `beginchar\' then getdelimited returns the empty string. `endchars\' is a sequence of allowable end-delimiting characters. Parsing stops when one of these is encounter...
def getdelimited(self, beginchar, endchars, allowcomments=True):
if (self.field[self.pos] != beginchar): return '' slist = [''] quote = False self.pos += 1 while (self.pos < len(self.field)): if quote: slist.append(self.field[self.pos]) quote = False elif (self.field[self.pos] in endchars): self.pos += 1...
'Get a quote-delimited fragment from self\'s field.'
def getquote(self):
return self.getdelimited('"', '"\r', False)
'Get a parenthesis-delimited fragment from self\'s field.'
def getcomment(self):
return self.getdelimited('(', ')\r', True)
'Parse an RFC 2822 domain-literal.'
def getdomainliteral(self):
return ('[%s]' % self.getdelimited('[', ']\r', False))
'Parse an RFC 2822 atom. Optional atomends specifies a different set of end token delimiters (the default is to use self.atomends). This is used e.g. in getphraselist() since phrase endings must not include the `.\' (which is legal in phrases).'
def getatom(self, atomends=None):
atomlist = [''] if (atomends is None): atomends = self.atomends while (self.pos < len(self.field)): if (self.field[self.pos] in atomends): break else: atomlist.append(self.field[self.pos]) self.pos += 1 return EMPTYSTRING.join(atomlist)
'Parse a sequence of RFC 2822 phrases. A phrase is a sequence of words, which are in turn either RFC 2822 atoms or quoted-strings. Phrases are canonicalized by squeezing all runs of continuous whitespace into one space.'
def getphraselist(self):
plist = [] while (self.pos < len(self.field)): if (self.field[self.pos] in self.FWS): self.pos += 1 elif (self.field[self.pos] == '"'): plist.append(self.getquote()) elif (self.field[self.pos] == '('): self.commentlist.append(self.getcomment()) ...
'Return the content-transfer-encoding used for body encoding. This is either the string `quoted-printable\' or `base64\' depending on the encoding used, or it is a function in which case you should call the function with a single argument, the Message object being encoded. The function should then set the Content-Tran...
def get_body_encoding(self):
assert (self.body_encoding != SHORTEST) if (self.body_encoding == QP): return 'quoted-printable' elif (self.body_encoding == BASE64): return 'base64' else: return encode_7or8bit
'Return the output character set. This is self.output_charset if that is not None, otherwise it is self.input_charset.'
def get_output_charset(self):
return (self.output_charset or self.input_charset)
'Header-encode a string by converting it first to bytes. The type of encoding (base64 or quoted-printable) will be based on this charset\'s `header_encoding`. :param string: A unicode string for the header. It must be possible to encode this string to bytes using the character set\'s output codec. :return: The encoded...
def header_encode(self, string):
codec = (self.output_codec or 'us-ascii') header_bytes = _encode(string, codec) encoder_module = self._get_encoder(header_bytes) if (encoder_module is None): return string return encoder_module.header_encode(header_bytes, codec)
'Header-encode a string by converting it first to bytes. This is similar to `header_encode()` except that the string is fit into maximum line lengths as given by the argument. :param string: A unicode string for the header. It must be possible to encode this string to bytes using the character set\'s output codec. :pa...
def header_encode_lines(self, string, maxlengths):
codec = (self.output_codec or 'us-ascii') header_bytes = _encode(string, codec) encoder_module = self._get_encoder(header_bytes) encoder = partial(encoder_module.header_encode, charset=codec) charset = self.get_output_charset() extra = (len(charset) + RFC2047_CHROME_LEN) lines = [] curre...
'Body-encode a string by converting it first to bytes. The type of encoding (base64 or quoted-printable) will be based on self.body_encoding. If body_encoding is None, we assume the output charset is a 7bit encoding, so re-encoding the decoded string using the ascii codec produces the correct string version of the con...
def body_encode(self, string):
if (not string): return string if (self.body_encoding is BASE64): if isinstance(string, str): string = string.encode(self.output_charset) return email.base64mime.body_encode(string) elif (self.body_encoding is QP): if isinstance(string, str): string = ...
'Create a MIME-compliant header that can contain many character sets. Optional s is the initial header value. If None, the initial header value is not set. You can later append to the header with .append() method calls. s may be a byte string or a Unicode string, but see the .append() documentation for semantics. Op...
def __init__(self, s=None, charset=None, maxlinelen=None, header_name=None, continuation_ws=' ', errors='strict'):
if (charset is None): charset = USASCII elif (not isinstance(charset, Charset)): charset = Charset(charset) self._charset = charset self._continuation_ws = continuation_ws self._chunks = [] if (s is not None): self.append(s, charset, errors) if (maxlinelen is None): ...
'Return the string value of the header.'
def __str__(self):
self._normalize() uchunks = [] lastcs = None lastspace = None for (string, charset) in self._chunks: nextcs = charset if (nextcs == _charset.UNKNOWN8BIT): original_bytes = string.encode('ascii', 'surrogateescape') string = original_bytes.decode('ascii', 'repla...
'Append a string to the MIME header. Optional charset, if given, should be a Charset instance or the name of a character set (which will be converted to a Charset instance). A value of None (the default) means that the charset given in the constructor is used. s may be a byte string or a Unicode string. If it is a by...
def append(self, s, charset=None, errors='strict'):
if (charset is None): charset = self._charset elif (not isinstance(charset, Charset)): charset = Charset(charset) if (not isinstance(s, str)): input_charset = (charset.input_codec or 'us-ascii') if (input_charset == _charset.UNKNOWN8BIT): s = s.decode('us-ascii', ...
'True if string s is not a ctext character of RFC822.'
def _nonctext(self, s):
return (s.isspace() or (s in ('(', ')', '\\')))
'Encode a message header into an RFC-compliant format. There are many issues involved in converting a given string for use in an email header. Only certain character sets are readable in most email clients, and as header strings can only contain a subset of 7-bit ASCII, care must be taken to properly convert and encod...
def encode(self, splitchars=';, DCTB ', maxlinelen=None, linesep='\n'):
self._normalize() if (maxlinelen is None): maxlinelen = self._maxlinelen if (maxlinelen == 0): maxlinelen = 1000000 formatter = _ValueFormatter(self._headerlen, maxlinelen, self._continuation_ws, splitchars) lastcs = None hasspace = lastspace = None for (string, charset) in s...
'This constructor adds a Content-Type: and a MIME-Version: header. The Content-Type: header is taken from the _maintype and _subtype arguments. Additional parameters for this header are taken from the keyword arguments.'
def __init__(self, _maintype, _subtype, **_params):
message.Message.__init__(self) ctype = ('%s/%s' % (_maintype, _subtype)) self.add_header('Content-Type', ctype, **_params) self['MIME-Version'] = '1.0'
'Create a text/* type MIME document. _text is the string for this message object. _subtype is the MIME sub content type, defaulting to "plain". _charset is the character set parameter added to the Content-Type header. This defaults to "us-ascii". Note that as a side-effect, the Content-Transfer-Encoding header will a...
def __init__(self, _text, _subtype='plain', _charset=None):
if (_charset is None): try: _text.encode('us-ascii') _charset = 'us-ascii' except UnicodeEncodeError: _charset = 'utf-8' MIMENonMultipart.__init__(self, 'text', _subtype, **{'charset': _charset}) self.set_payload(_text, _charset)
'Create an application/* type MIME document. _data is a string containing the raw application data. _subtype is the MIME content type subtype, defaulting to \'octet-stream\'. _encoder is a function which will perform the actual encoding for transport of the application data, defaulting to base64 encoding. Any additiona...
def __init__(self, _data, _subtype='octet-stream', _encoder=encoders.encode_base64, **_params):
if (_subtype is None): raise TypeError('Invalid application MIME subtype') MIMENonMultipart.__init__(self, 'application', _subtype, **_params) self.set_payload(_data) _encoder(self)
'Create a message/* type MIME document. _msg is a message object and must be an instance of Message, or a derived class of Message, otherwise a TypeError is raised. Optional _subtype defines the subtype of the contained message. The default is "rfc822" (this is defined by the MIME standard, even though the term "rfc82...
def __init__(self, _msg, _subtype='rfc822'):
MIMENonMultipart.__init__(self, 'message', _subtype) if (not isinstance(_msg, message.Message)): raise TypeError('Argument is not an instance of Message') message.Message.attach(self, _msg) self.set_default_type('message/rfc822')
'Create an image/* type MIME document. _imagedata is a string containing the raw image data. If this data can be decoded by the standard Python `imghdr\' module, then the subtype will be automatically included in the Content-Type header. Otherwise, you can specify the specific image subtype via the _subtype parameter....
def __init__(self, _imagedata, _subtype=None, _encoder=encoders.encode_base64, **_params):
if (_subtype is None): _subtype = imghdr.what(None, _imagedata) if (_subtype is None): raise TypeError('Could not guess image MIME subtype') MIMENonMultipart.__init__(self, 'image', _subtype, **_params) self.set_payload(_imagedata) _encoder(self)
'Creates a multipart/* type message. By default, creates a multipart/mixed message, with proper Content-Type and MIME-Version headers. _subtype is the subtype of the multipart content type, defaulting to `mixed\'. boundary is the multipart boundary string. By default it is calculated as needed. _subparts is a sequence...
def __init__(self, _subtype='mixed', boundary=None, _subparts=None, **_params):
MIMEBase.__init__(self, 'multipart', _subtype, **_params) self._payload = [] if _subparts: for p in _subparts: self.attach(p) if boundary: self.set_boundary(boundary)
'Create an audio/* type MIME document. _audiodata is a string containing the raw audio data. If this data can be decoded by the standard Python `sndhdr\' module, then the subtype will be automatically included in the Content-Type header. Otherwise, you can specify the specific audio subtype via the _subtype parameter...
def __init__(self, _audiodata, _subtype=None, _encoder=encoders.encode_base64, **_params):
if (_subtype is None): _subtype = _whatsnd(_audiodata) if (_subtype is None): raise TypeError('Could not find audio MIME subtype') MIMENonMultipart.__init__(self, 'audio', _subtype, **_params) self.set_payload(_audiodata) _encoder(self)
'Registers an instance to respond to XML-RPC requests. Only one instance can be installed at a time. If the registered instance has a _dispatch method then that method will be called with the name of the XML-RPC method and its parameters as a tuple e.g. instance._dispatch(\'add\',(2,3)) If the registered instance does ...
def register_instance(self, instance, allow_dotted_names=False):
self.instance = instance self.allow_dotted_names = allow_dotted_names
'Registers a function to respond to XML-RPC requests. The optional name argument can be used to set a Unicode name for the function.'
def register_function(self, function, name=None):
if (name is None): name = function.__name__ self.funcs[name] = function
'Registers the XML-RPC introspection methods in the system namespace. see http://xmlrpc.usefulinc.com/doc/reserved.html'
def register_introspection_functions(self):
self.funcs.update({'system.listMethods': self.system_listMethods, 'system.methodSignature': self.system_methodSignature, 'system.methodHelp': self.system_methodHelp})
'Registers the XML-RPC multicall method in the system namespace. see http://www.xmlrpc.com/discuss/msgReader$1208'
def register_multicall_functions(self):
self.funcs.update({'system.multicall': self.system_multicall})
'Dispatches an XML-RPC method from marshalled (XML) data. XML-RPC methods are dispatched from the marshalled (XML) data using the _dispatch method and the result is returned as marshalled data. For backwards compatibility, a dispatch function can be provided as an argument (see comment in SimpleXMLRPCRequestHandler.do_...
def _marshaled_dispatch(self, data, dispatch_method=None, path=None):
try: (params, method) = loads(data, use_builtin_types=self.use_builtin_types) if (dispatch_method is not None): response = dispatch_method(method, params) else: response = self._dispatch(method, params) response = (response,) response = dumps(response,...
'system.listMethods() => [\'add\', \'subtract\', \'multiple\'] Returns a list of the methods supported by the server.'
def system_listMethods(self):
methods = set(self.funcs.keys()) if (self.instance is not None): if hasattr(self.instance, '_listMethods'): methods |= set(self.instance._listMethods()) elif (not hasattr(self.instance, '_dispatch')): methods |= set(list_public_methods(self.instance)) return sorted(me...
'system.methodSignature(\'add\') => [double, int, int] Returns a list describing the signature of the method. In the above example, the add method takes two integers as arguments and returns a double result. This server does NOT support system.methodSignature.'
def system_methodSignature(self, method_name):
return 'signatures not supported'
'system.methodHelp(\'add\') => "Adds two integers together" Returns a string containing documentation for the specified method.'
def system_methodHelp(self, method_name):
method = None if (method_name in self.funcs): method = self.funcs[method_name] elif (self.instance is not None): if hasattr(self.instance, '_methodHelp'): return self.instance._methodHelp(method_name) elif (not hasattr(self.instance, '_dispatch')): try: ...
'system.multicall([{\'methodName\': \'add\', \'params\': [2, 2]}, ...]) => [[4], ...] Allows the caller to package multiple XML-RPC calls into a single request. See http://www.xmlrpc.com/discuss/msgReader$1208'
def system_multicall(self, call_list):
results = [] for call in call_list: method_name = call['methodName'] params = call['params'] try: results.append([self._dispatch(method_name, params)]) except Fault as fault: results.append({'faultCode': fault.faultCode, 'faultString': fault.faultString}) ...
'Dispatches the XML-RPC method. XML-RPC calls are forwarded to a registered function that matches the called XML-RPC method name. If no such function exists then the call is forwarded to the registered instance, if available. If the registered instance has a _dispatch method then that method will be called with the nam...
def _dispatch(self, method, params):
func = None try: func = self.funcs[method] except KeyError: if (self.instance is not None): if hasattr(self.instance, '_dispatch'): return self.instance._dispatch(method, params) else: try: func = resolve_dotted_attr...
'Handles the HTTP POST request. Attempts to interpret all HTTP POST requests as XML-RPC calls, which are forwarded to the server\'s _dispatch method for handling.'
def do_POST(self):
if (not self.is_rpc_path_valid()): self.report_404() return try: max_chunk_size = ((10 * 1024) * 1024) size_remaining = int(self.headers['content-length']) L = [] while size_remaining: chunk_size = min(size_remaining, max_chunk_size) chunk ...
'Selectively log an accepted request.'
def log_request(self, code='-', size='-'):
if self.server.logRequests: BaseHTTPRequestHandler.log_request(self, code, size)
'Handle a single XML-RPC request'
def handle_xmlrpc(self, request_text):
response = self._marshaled_dispatch(request_text) print 'Content-Type: text/xml' print ('Content-Length: %d' % len(response)) print () sys.stdout.flush() sys.stdout.buffer.write(response) sys.stdout.buffer.flush()
'Handle a single HTTP GET request. Default implementation indicates an error because XML-RPC uses the POST method.'
def handle_get(self):
code = 400 (message, explain) = BaseHTTPRequestHandler.responses[code] response = (http.server.DEFAULT_ERROR_MESSAGE % {'code': code, 'message': message, 'explain': explain}) response = response.encode('utf-8') print ('Status: %d %s' % (code, message)) print ('Content-Type: %s' % http.s...
'Handle a single XML-RPC request passed through a CGI post method. If no XML data is given then it is read from stdin. The resulting XML-RPC response is printed to stdout along with the correct HTTP headers.'
def handle_request(self, request_text=None):
if ((request_text is None) and (os.environ.get('REQUEST_METHOD', None) == 'GET')): self.handle_get() else: try: length = int(os.environ.get('CONTENT_LENGTH', None)) except (ValueError, TypeError): length = (-1) if (request_text is None): reques...
'Mark up some plain text, given a context of symbols to look for. Each context dictionary maps object names to anchor names.'
def markup(self, text, escape=None, funcs={}, classes={}, methods={}):
escape = (escape or self.escape) results = [] here = 0 pattern = re.compile('\\b((http|ftp)://\\S+[\\w/]|RFC[- ]?(\\d+)|PEP[- ]?(\\d+)|(self\\.)?((?:\\w|\\.)+))\\b') while 1: match = pattern.search(text, here) if (not match): break (start, end) = match.span(...
'Produce HTML documentation for a function or method object.'
def docroutine(self, object, name, mod=None, funcs={}, classes={}, methods={}, cl=None):
anchor = ((((cl and cl.__name__) or '') + '-') + name) note = '' title = ('<a name="%s"><strong>%s</strong></a>' % (self.escape(anchor), self.escape(name))) if inspect.ismethod(object): args = inspect.getfullargspec(object) argspec = inspect.formatargspec(args.args[1:], args.varargs, ...
'Produce HTML documentation for an XML-RPC server.'
def docserver(self, server_name, package_documentation, methods):
fdict = {} for (key, value) in methods.items(): fdict[key] = ('#-' + key) fdict[value] = fdict[key] server_name = self.escape(server_name) head = ('<big><big><strong>%s</strong></big></big>' % server_name) result = self.heading(head, '#ffffff', '#7799ee') doc = self.markup(packag...
'Set the HTML title of the generated server documentation'
def set_server_title(self, server_title):
self.server_title = server_title
'Set the name of the generated HTML server documentation'
def set_server_name(self, server_name):
self.server_name = server_name
'Set the documentation string for the entire server.'
def set_server_documentation(self, server_documentation):
self.server_documentation = server_documentation
'generate_html_documentation() => html documentation for the server Generates HTML documentation for the server using introspection for installed functions and instances that do not implement the _dispatch method. Alternatively, instances can choose to implement the _get_method_argstring(method_name) method to provide ...
def generate_html_documentation(self):
methods = {} for method_name in self.system_listMethods(): if (method_name in self.funcs): method = self.funcs[method_name] elif (self.instance is not None): method_info = [None, None] if hasattr(self.instance, '_get_method_argstring'): method_...
'Handles the HTTP GET request. Interpret all HTTP GET requests as requests for server documentation.'
def do_GET(self):
if (not self.is_rpc_path_valid()): self.report_404() return response = self.server.generate_html_documentation().encode('utf-8') self.send_response(200) self.send_header('Content-type', 'text/html') self.send_header('Content-length', str(len(response))) self.end_headers() sel...
'Handles the HTTP GET request. Interpret all HTTP GET requests as requests for server documentation.'
def handle_get(self):
response = self.generate_html_documentation().encode('utf-8') print 'Content-Type: text/html' print ('Content-Length: %d' % len(response)) print () sys.stdout.flush() sys.stdout.buffer.write(response) sys.stdout.buffer.flush()
'A workaround to get special attributes on the ServerProxy without interfering with the magic __getattr__'
def __call__(self, attr):
if (attr == 'close'): return self.__close elif (attr == 'transport'): return self.__transport raise AttributeError(('Attribute %r not found' % (attr,)))