desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Returns the value of the \'key\' attribute for the tag, or the value given for \'default\' if it doesn\'t have that attribute.'
def get(self, key, default=None):
return self._getAttrMap().get(key, default)
'Extract all children.'
def clear(self):
for child in self.contents[:]: child.extract()
'tag[key] returns the value of the \'key\' attribute for the tag, and throws an exception if it\'s not there.'
def __getitem__(self, key):
return self._getAttrMap()[key]
'Iterating over a tag iterates over its contents.'
def __iter__(self):
return iter(self.contents)
'The length of a tag is the length of its list of contents.'
def __len__(self):
return len(self.contents)
'A tag is non-None even if it has no contents.'
def __nonzero__(self):
return True
'Setting tag[key] sets the value of the \'key\' attribute for the tag.'
def __setitem__(self, key, value):
self._getAttrMap() self.attrMap[key] = value found = False for i in xrange(0, len(self.attrs)): if (self.attrs[i][0] == key): self.attrs[i] = (key, value) found = True if (not found): self.attrs.append((key, value)) self._getAttrMap()[key] = value
'Deleting tag[key] deletes all \'key\' attributes for the tag.'
def __delitem__(self, key):
for item in self.attrs: if (item[0] == key): self.attrs.remove(item) self._getAttrMap() if self.attrMap.has_key(key): del self.attrMap[key]
'Calling a tag like a function is the same as calling its findAll() method. Eg. tag(\'a\') returns a list of all the A tags found within this tag.'
def __call__(self, *args, **kwargs):
return apply(self.findAll, args, kwargs)
'Returns true iff this tag has the same name, the same attributes, and the same contents (recursively) as the given tag. NOTE: right now this will return false if two tags have the same attributes in a different order. Should this be fixed?'
def __eq__(self, other):
if (other is self): return True if ((not hasattr(other, 'name')) or (not hasattr(other, 'attrs')) or (not hasattr(other, 'contents')) or (self.name != other.name) or (self.attrs != other.attrs) or (len(self) != len(other))): return False for i in xrange(0, len(self.contents)): if (se...
'Returns true iff this tag is not identical to the other tag, as defined in __eq__.'
def __ne__(self, other):
return (not (self == other))
'Renders this tag as a string.'
def __repr__(self, encoding=DEFAULT_OUTPUT_ENCODING):
return self.__str__(encoding)
'Returns a string or Unicode representation of this tag and its contents. To get Unicode, pass None for encoding. NOTE: since Python\'s HTML parser consumes whitespace, this method is not certain to reproduce the whitespace present in the original string.'
def __str__(self, encoding=DEFAULT_OUTPUT_ENCODING, prettyPrint=False, indentLevel=0):
encodedName = self.toEncoding(self.name, encoding) attrs = [] if self.attrs: for (key, val) in self.attrs: fmt = '%s="%s"' if isinstance(val, basestring): if (self.containsSubstitutions and ('%SOUP-ENCODING%' in val)): val = self.substitute...
'Recursively destroys the contents of this tree.'
def decompose(self):
self.extract() if (len(self.contents) == 0): return current = self.contents[0] while (current is not None): next = current.next if isinstance(current, Tag): del current.contents[:] current.parent = None current.previous = None current.previousS...
'Renders the contents of this tag as a string in the given encoding. If encoding is None, returns a Unicode string..'
def renderContents(self, encoding=DEFAULT_OUTPUT_ENCODING, prettyPrint=False, indentLevel=0):
s = [] for c in self: text = None if isinstance(c, NavigableString): text = c.__str__(encoding) elif isinstance(c, Tag): s.append(c.__str__(encoding, prettyPrint, indentLevel)) if (text and prettyPrint): text = text.strip() if text: ...
'Return only the first child of this Tag matching the given criteria.'
def find(self, name=None, attrs={}, recursive=True, text=None, **kwargs):
r = None l = self.findAll(name, attrs, recursive, text, 1, **kwargs) if l: r = l[0] return r
'Extracts a list of Tag objects that match the given criteria. You can specify the name of the Tag and any attributes you want the Tag to have. The value of a key-value pair in the \'attrs\' map can be a string, a list of strings, a regular expression object, or a callable that takes a string and returns whether or no...
def findAll(self, name=None, attrs={}, recursive=True, text=None, limit=None, **kwargs):
generator = self.recursiveChildGenerator if (not recursive): generator = self.childGenerator return self._findAll(name, attrs, text, limit, generator, **kwargs)
'Initializes a map representation of this tag\'s attributes, if not already initialized.'
def _getAttrMap(self):
if (not getattr(self, 'attrMap')): self.attrMap = {} for (key, value) in self.attrs: self.attrMap[key] = value return self.attrMap
'The Soup object is initialized as the \'root tag\', and the provided markup (which can be a string or a file-like object) is fed into the underlying parser. sgmllib will process most bad HTML, and the BeautifulSoup class has some tricks for dealing with some HTML that kills sgmllib, but Beautiful Soup can nonetheless ...
def __init__(self, markup='', parseOnlyThese=None, fromEncoding=None, markupMassage=True, smartQuotesTo=XML_ENTITIES, convertEntities=None, selfClosingTags=None, isHTML=False):
self.parseOnlyThese = parseOnlyThese self.fromEncoding = fromEncoding self.smartQuotesTo = smartQuotesTo self.convertEntities = convertEntities if self.convertEntities: self.smartQuotesTo = None if (convertEntities == self.HTML_ENTITIES): self.convertXMLEntities = False ...
'This method fixes a bug in Python\'s SGMLParser.'
def convert_charref(self, name):
try: n = int(name) except ValueError: return if (not (0 <= n <= 127)): return return self.convert_codepoint(n)
'This method routes method call requests to either the SGMLParser superclass or the Tag superclass, depending on the method name.'
def __getattr__(self, methodName):
if (methodName.startswith('start_') or methodName.startswith('end_') or methodName.startswith('do_')): return SGMLParser.__getattr__(self, methodName) elif (not methodName.startswith('__')): return Tag.__getattr__(self, methodName) else: raise AttributeError
'Returns true iff the given string is the name of a self-closing tag according to this parser.'
def isSelfClosingTag(self, name):
return (self.SELF_CLOSING_TAGS.has_key(name) or self.instanceSelfClosingTags.has_key(name))
'Pops the tag stack up to and including the most recent instance of the given tag. If inclusivePop is false, pops the tag stack up to but *not* including the most recent instqance of the given tag.'
def _popToTag(self, name, inclusivePop=True):
if (name == self.ROOT_TAG_NAME): return numPops = 0 mostRecentTag = None for i in xrange((len(self.tagStack) - 1), 0, (-1)): if (name == self.tagStack[i].name): numPops = (len(self.tagStack) - i) break if (not inclusivePop): numPops = (numPops - 1) ...
'We need to pop up to the previous tag of this type, unless one of this tag\'s nesting reset triggers comes between this tag and the previous tag of this type, OR unless this tag is a generic nesting trigger and another generic nesting trigger comes between this tag and the previous tag of this type. Examples: <p>Foo<b...
def _smartPop(self, name):
nestingResetTriggers = self.NESTABLE_TAGS.get(name) isNestable = (nestingResetTriggers != None) isResetNesting = self.RESET_NESTING_TAGS.has_key(name) popTo = None inclusive = True for i in xrange((len(self.tagStack) - 1), 0, (-1)): p = self.tagStack[i] if (((not p) or (p.name ==...
'Adds a certain piece of text to the tree as a NavigableString subclass.'
def _toStringSubclass(self, text, subclass):
self.endData() self.handle_data(text) self.endData(subclass)
'Handle a processing instruction as a ProcessingInstruction object, possibly one with a %SOUP-ENCODING% slot into which an encoding will be plugged later.'
def handle_pi(self, text):
if (text[:3] == 'xml'): text = u"xml version='1.0' encoding='%SOUP-ENCODING%'" self._toStringSubclass(text, ProcessingInstruction)
'Handle comments as Comment objects.'
def handle_comment(self, text):
self._toStringSubclass(text, Comment)
'Handle character references as data.'
def handle_charref(self, ref):
if self.convertEntities: data = unichr(int(ref)) else: data = ('&#%s;' % ref) self.handle_data(data)
'Handle entity references as data, possibly converting known HTML and/or XML entity references to the corresponding Unicode characters.'
def handle_entityref(self, ref):
data = None if self.convertHTMLEntities: try: data = unichr(name2codepoint[ref]) except KeyError: pass if ((not data) and self.convertXMLEntities): data = self.XML_ENTITIES_TO_SPECIAL_CHARS.get(ref) if ((not data) and self.convertHTMLEntities and (not self...
'Handle DOCTYPEs and the like as Declaration objects.'
def handle_decl(self, data):
self._toStringSubclass(data, Declaration)
'Treat a bogus SGML declaration as raw data. Treat a CDATA declaration as a CData object.'
def parse_declaration(self, i):
j = None if (self.rawdata[i:(i + 9)] == '<![CDATA['): k = self.rawdata.find(']]>', i) if (k == (-1)): k = len(self.rawdata) data = self.rawdata[(i + 9):k] j = (k + 3) self._toStringSubclass(data, CData) else: try: j = SGMLParser.parse_d...
'Beautiful Soup can detect a charset included in a META tag, try to convert the document to that charset, and re-parse the document from the beginning.'
def start_meta(self, attrs):
httpEquiv = None contentType = None contentTypeIndex = None tagNeedsEncodingSubstitution = False for i in xrange(0, len(attrs)): (key, value) = attrs[i] key = key.lower() if (key == 'http-equiv'): httpEquiv = value elif (key == 'content'): cont...
'Changes a MS smart quote character to an XML or HTML entity.'
def _subMSChar(self, orig):
sub = self.MS_CHARS.get(orig) if isinstance(sub, tuple): if (self.smartQuotesTo == 'xml'): sub = ('&#x%s;' % sub[1]) else: sub = ('&%s;' % sub[0]) return sub
'Given a string and its encoding, decodes the string into Unicode. %encoding is a string recognized by encodings.aliases'
def _toUnicode(self, data, encoding):
if ((len(data) >= 4) and (data[:2] == '\xfe\xff') and (data[2:4] != '\x00\x00')): encoding = 'utf-16be' data = data[2:] elif ((len(data) >= 4) and (data[:2] == '\xff\xfe') and (data[2:4] != '\x00\x00')): encoding = 'utf-16le' data = data[2:] elif (data[:3] == '\xef\xbb\xbf'):...
'Given a document, tries to detect its XML encoding.'
def _detectEncoding(self, xml_data, isHTML=False):
xml_encoding = sniffed_xml_encoding = None try: if (xml_data[:4] == 'Lo\xa7\x94'): xml_data = self._ebcdic_to_ascii(xml_data) elif (xml_data[:4] == '\x00<\x00?'): sniffed_xml_encoding = 'utf-16be' xml_data = unicode(xml_data, 'utf-16be').encode('utf-8') ...
'Create a copy of this pen.'
def copy(self):
pen = Pen() pen.__dict__ = self.__dict__.copy() return pen
'Draw this shape with the given cairo context'
def draw(self, cr, highlight=False):
raise NotImplementedError
'Override this method in subclass to process click events. Note that element can be None (click on empty space).'
def on_click(self, element, event):
return False
'getKey() -> bytes'
def getKey(self):
return self.__key
'Will set the crypting key for this object.'
def setKey(self, key):
key = self._guardAgainstUnicode(key) self.__key = key
'getMode() -> pyDes.ECB or pyDes.CBC'
def getMode(self):
return self._mode
'Sets the type of crypting mode, pyDes.ECB or pyDes.CBC'
def setMode(self, mode):
self._mode = mode
'getPadding() -> bytes of length 1. Padding character.'
def getPadding(self):
return self._padding
'setPadding() -> bytes of length 1. Padding character.'
def setPadding(self, pad):
if (pad is not None): pad = self._guardAgainstUnicode(pad) self._padding = pad
'getPadMode() -> pyDes.PAD_NORMAL or pyDes.PAD_PKCS5'
def getPadMode(self):
return self._padmode
'Sets the type of padding mode, pyDes.PAD_NORMAL or pyDes.PAD_PKCS5'
def setPadMode(self, mode):
self._padmode = mode
'getIV() -> bytes'
def getIV(self):
return self._iv
'Will set the Initial Value, used in conjunction with CBC mode'
def setIV(self, IV):
if ((not IV) or (len(IV) != self.block_size)): raise ValueError((('Invalid Initial Value (IV), must be a multiple of ' + str(self.block_size)) + ' bytes')) IV = self._guardAgainstUnicode(IV) self._iv = IV
'Will set the crypting key for this object. Must be 8 bytes.'
def setKey(self, key):
_baseDes.setKey(self, key) self.__create_sub_keys()
'Turn the string data, into a list of bits (1, 0)\'s'
def __String_to_BitList(self, data):
if (_pythonMajorVersion < 3): data = [ord(c) for c in data] l = (len(data) * 8) result = ([0] * l) pos = 0 for ch in data: i = 7 while (i >= 0): if ((ch & (1 << i)) != 0): result[pos] = 1 else: result[pos] = 0 ...
'Turn the list of bits -> data, into a string'
def __BitList_to_String(self, data):
result = [] pos = 0 c = 0 while (pos < len(data)): c += (data[pos] << (7 - (pos % 8))) if ((pos % 8) == 7): result.append(c) c = 0 pos += 1 if (_pythonMajorVersion < 3): return ''.join([chr(c) for c in result]) else: return bytes(re...
'Permutate this block with the specified table'
def __permutate(self, table, block):
return list(map((lambda x: block[x]), table))
'Create the 16 subkeys K[1] to K[16] from the given key'
def __create_sub_keys(self):
key = self.__permutate(des.__pc1, self.__String_to_BitList(self.getKey())) i = 0 self.L = key[:28] self.R = key[28:] while (i < 16): j = 0 while (j < des.__left_rotations[i]): self.L.append(self.L[0]) del self.L[0] self.R.append(self.R[0]) ...
'Crypt the block of data through DES bit-manipulation'
def __des_crypt(self, block, crypt_type):
block = self.__permutate(des.__ip, block) self.L = block[:32] self.R = block[32:] if (crypt_type == des.ENCRYPT): iteration = 0 iteration_adjustment = 1 else: iteration = 15 iteration_adjustment = (-1) i = 0 while (i < 16): tempR = self.R[:] se...
'Crypt the data in blocks, running it through des_crypt()'
def crypt(self, data, crypt_type):
if (not data): return '' if ((len(data) % self.block_size) != 0): if (crypt_type == des.DECRYPT): raise ValueError((('Invalid data length, data must be a multiple of ' + str(self.block_size)) + ' bytes\n.')) if (not self.getPadding()): ...
'encrypt(data, [pad], [padmode]) -> bytes data : Bytes to be encrypted pad : Optional argument for encryption padding. Must only be one byte padmode : Optional argument for overriding the padding mode. The data must be a multiple of 8 bytes and will be encrypted with the already specified key. Data does not have to be...
def encrypt(self, data, pad=None, padmode=None):
data = self._guardAgainstUnicode(data) if (pad is not None): pad = self._guardAgainstUnicode(pad) data = self._padData(data, pad, padmode) return self.crypt(data, des.ENCRYPT)
'decrypt(data, [pad], [padmode]) -> bytes data : Bytes to be encrypted pad : Optional argument for decryption padding. Must only be one byte padmode : Optional argument for overriding the padding mode. The data must be a multiple of 8 bytes and will be decrypted with the already specified key. In PAD_NORMAL mode, if t...
def decrypt(self, data, pad=None, padmode=None):
data = self._guardAgainstUnicode(data) if (pad is not None): pad = self._guardAgainstUnicode(pad) data = self.crypt(data, des.DECRYPT) return self._unpadData(data, pad, padmode)
'Will set the crypting key for this object. Either 16 or 24 bytes long.'
def setKey(self, key):
self.key_size = 24 if (len(key) != self.key_size): if (len(key) == 16): self.key_size = 16 else: raise ValueError('Invalid triple DES key size. Key must be either 16 or 24 bytes long') if (self.getMode() == CBC): if (not ...
'Sets the type of crypting mode, pyDes.ECB or pyDes.CBC'
def setMode(self, mode):
_baseDes.setMode(self, mode) for key in (self.__key1, self.__key2, self.__key3): key.setMode(mode)
'setPadding() -> bytes of length 1. Padding character.'
def setPadding(self, pad):
_baseDes.setPadding(self, pad) for key in (self.__key1, self.__key2, self.__key3): key.setPadding(pad)
'Sets the type of padding mode, pyDes.PAD_NORMAL or pyDes.PAD_PKCS5'
def setPadMode(self, mode):
_baseDes.setPadMode(self, mode) for key in (self.__key1, self.__key2, self.__key3): key.setPadMode(mode)
'Will set the Initial Value, used in conjunction with CBC mode'
def setIV(self, IV):
_baseDes.setIV(self, IV) for key in (self.__key1, self.__key2, self.__key3): key.setIV(IV)
'encrypt(data, [pad], [padmode]) -> bytes data : bytes to be encrypted pad : Optional argument for encryption padding. Must only be one byte padmode : Optional argument for overriding the padding mode. The data must be a multiple of 8 bytes and will be encrypted with the already specified key. Data does not have to be...
def encrypt(self, data, pad=None, padmode=None):
ENCRYPT = des.ENCRYPT DECRYPT = des.DECRYPT data = self._guardAgainstUnicode(data) if (pad is not None): pad = self._guardAgainstUnicode(pad) data = self._padData(data, pad, padmode) if (self.getMode() == CBC): self.__key1.setIV(self.getIV()) self.__key2.setIV(self.getIV(...
'decrypt(data, [pad], [padmode]) -> bytes data : bytes to be encrypted pad : Optional argument for decryption padding. Must only be one byte padmode : Optional argument for overriding the padding mode. The data must be a multiple of 8 bytes and will be decrypted with the already specified key. In PAD_NORMAL mode, if t...
def decrypt(self, data, pad=None, padmode=None):
ENCRYPT = des.ENCRYPT DECRYPT = des.DECRYPT data = self._guardAgainstUnicode(data) if (pad is not None): pad = self._guardAgainstUnicode(pad) if (self.getMode() == CBC): self.__key1.setIV(self.getIV()) self.__key2.setIV(self.getIV()) self.__key3.setIV(self.getIV()) ...
'Receive EXACTLY the number of bytes requested from the file object. Blocks until the required number of bytes have been received.'
def _readall(self, file, count):
data = '' while (len(data) < count): d = file.read((count - len(data))) if (not d): raise GeneralProxyError('Connection closed unexpectedly') data += d return data
'set_proxy(proxy_type, addr[, port[, rdns[, username[, password]]]]) Sets the proxy to be used. proxy_type - The type of the proxy to be used. Three types are supported: PROXY_TYPE_SOCKS4 (including socks4a), PROXY_TYPE_SOCKS5 and PROXY_TYPE_HTTP addr - The address of the server (IP or DNS). port - The...
def set_proxy(self, proxy_type=None, addr=None, port=None, rdns=True, username=None, password=None):
self.proxy = (proxy_type, addr, port, rdns, (username.encode() if username else None), (password.encode() if password else None))
'Implements proxy connection for UDP sockets, which happens during the bind() phase.'
def bind(self, *pos, **kw):
(proxy_type, proxy_addr, proxy_port, rdns, username, password) = self.proxy if ((not proxy_type) or (self.type != socket.SOCK_DGRAM)): return _orig_socket.bind(self, *pos, **kw) if self._proxyconn: raise socket.error(EINVAL, 'Socket already bound to an address') if (proxy_...
'Returns the bound IP address and port number at the proxy.'
def get_proxy_sockname(self):
return self.proxy_sockname
'Returns the IP and port number of the proxy.'
def get_proxy_peername(self):
return _BaseSocket.getpeername(self)
'Returns the IP address and port number of the destination machine (note: get_proxy_peername returns the proxy)'
def get_peername(self):
return self.proxy_peername
'Negotiates a stream connection through a SOCKS5 server.'
def _negotiate_SOCKS5(self, *dest_addr):
CONNECT = '\x01' (self.proxy_peername, self.proxy_sockname) = self._SOCKS5_request(self, CONNECT, dest_addr)
'Send SOCKS5 request with given command (CMD field) and address (DST field). Returns resolved DST address that was used.'
def _SOCKS5_request(self, conn, cmd, dst):
(proxy_type, addr, port, rdns, username, password) = self.proxy writer = conn.makefile('wb') reader = conn.makefile('rb', 0) try: if (username and password): writer.write('\x05\x02\x00\x02') else: writer.write('\x05\x01\x00') writer.flush() chosen_...
'Return the host and port packed for the SOCKS5 protocol, and the resolved address as a tuple object.'
def _write_SOCKS5_address(self, addr, file):
(host, port) = addr (proxy_type, _, _, rdns, username, password) = self.proxy family_to_byte = {socket.AF_INET: '\x01', socket.AF_INET6: '\x04'} for family in (socket.AF_INET, socket.AF_INET6): try: addr_bytes = socket.inet_pton(family, host) file.write((family_to_byte[fa...
'Negotiates a connection through a SOCKS4 server.'
def _negotiate_SOCKS4(self, dest_addr, dest_port):
(proxy_type, addr, port, rdns, username, password) = self.proxy writer = self.makefile('wb') reader = self.makefile('rb', 0) try: remote_resolve = False try: addr_bytes = socket.inet_aton(dest_addr) except socket.error: if rdns: addr_bytes ...
'Negotiates a connection through an HTTP server. NOTE: This currently only supports HTTP CONNECT-style proxies.'
def _negotiate_HTTP(self, dest_addr, dest_port):
(proxy_type, addr, port, rdns, username, password) = self.proxy addr = (dest_addr if rdns else socket.gethostbyname(dest_addr)) http_headers = [(((('CONNECT ' + addr.encode('idna')) + ':') + str(dest_port).encode()) + ' HTTP/1.1'), ('Host: ' + dest_addr.encode('idna'))] if (username and passwor...
'Connects to the specified destination through a proxy. Uses the same API as socket\'s connect(). To select the proxy server, use set_proxy(). dest_pair - 2-tuple of (IP/hostname, port).'
def connect(self, dest_pair):
if ((len(dest_pair) != 2) or dest_pair[0].startswith('[')): raise socket.error("PySocks doesn't support IPv6") (dest_addr, dest_port) = dest_pair if (self.type == socket.SOCK_DGRAM): if (not self._proxyconn): self.bind(('', 0)) dest_addr = socket.gethostbyname(de...
'Return proxy address to connect to as tuple object'
def _proxy_addr(self):
(proxy_type, proxy_addr, proxy_port, rdns, username, password) = self.proxy proxy_port = (proxy_port or DEFAULT_PORTS.get(proxy_type)) if (not proxy_port): raise GeneralProxyError('Invalid proxy type') return (proxy_addr, proxy_port)
'prefix is ignored if add_to_http_hdrs is true.'
def addheader(self, key, value, prefix=0, add_to_http_hdrs=0):
lines = value.split('\r\n') while (lines and (not lines[(-1)])): del lines[(-1)] while (lines and (not lines[0])): del lines[0] if add_to_http_hdrs: value = ''.join(lines) self._http_hdrs.append((key.capitalize(), value)) else: for i in xrange(1, len(lines)): ...
'prefix is ignored if add_to_http_hdrs is true.'
def startbody(self, ctype=None, plist=[], prefix=1, add_to_http_hdrs=0, content_type=1):
if (content_type and ctype): for (name, value) in plist: ctype = (ctype + (';\r\n %s=%s' % (name, value))) self.addheader('Content-Type', ctype, prefix=prefix, add_to_http_hdrs=add_to_http_hdrs) self.flushheaders() if (not add_to_http_hdrs): self._fp.write('\r\n') ...
'type: string describing type of control (see the keys of the HTMLForm.type2class dictionary for the allowable values) name: control name attrs: HTML attributes of control\'s HTML element'
def __init__(self, type, name, attrs, index=None):
raise NotImplementedError()
'Return list of (key, value) pairs suitable for passing to urlencode.'
def pairs(self):
return [(k, v) for (i, k, v) in self._totally_ordered_pairs()]
'Return list of (key, value, index) tuples. Like pairs, but allows preserving correct ordering even where several controls are involved.'
def _totally_ordered_pairs(self):
raise NotImplementedError()
'Write data for a subitem of this control to a MimeWriter.'
def _write_mime_data(self, mw, name, value):
mw2 = mw.nextpart() mw2.addheader('Content-Disposition', ('form-data; name="%s"' % name), 1) f = mw2.startbody(prefix=0) f.write(value)
'Return all labels (Label instances) for this control. If the control was surrounded by a <label> tag, that will be the first label; all other labels, connected by \'for\' and \'id\', are in the order that appear in the HTML.'
def get_labels(self):
res = [] if self._label: res.append(self._label) if self.id: res.extend(self._form._id_to_labels.get(self.id, ())) return res
'Return all labels (Label instances) for this item. For items that represent radio buttons or checkboxes, if the item was surrounded by a <label> tag, that will be the first label; all other labels, connected by \'for\' and \'id\', are in the order that appear in the HTML. For items that represent select options, if th...
def get_labels(self):
res = [] res.extend(self._labels) if self.id: res.extend(self._control._form._id_to_labels.get(self.id, ())) return res
'select_default: for RADIO and multiple-selection SELECT controls, pick the first item as the default if no \'selected\' HTML attribute is present'
def __init__(self, type, name, attrs={}, select_default=False, called_as_base_class=False, index=None):
if (not called_as_base_class): raise NotImplementedError() self.__dict__['type'] = type.lower() self.__dict__['name'] = name self._value = attrs.get('value') self.disabled = False self.readonly = False self.id = attrs.get('id') self._closed = False self.items = [] self._f...
'Return matching items by name or label. For argument docs, see the docstring for .get()'
def get_items(self, name=None, label=None, id=None, exclude_disabled=False):
if ((name is not None) and (not isstringlike(name))): raise TypeError('item name must be string-like') if ((label is not None) and (not isstringlike(label))): raise TypeError('item label must be string-like') if ((id is not None) and (not isstringlike(id))): r...
'Return item by name or label, disambiguating if necessary with nr. All arguments must be passed by name, with the exception of \'name\', which may be used as a positional argument. If name is specified, then the item must have the indicated name. If label is specified, then the item must have a label whose whitespace-...
def get(self, name=None, label=None, id=None, nr=None, exclude_disabled=False):
if ((nr is None) and self._form.backwards_compat): nr = 0 items = self.get_items(name, label, id, exclude_disabled) return disambiguate(items, nr, name=name, label=label, id=id)
'Deprecated: given a name or label and optional disambiguating index nr, toggle the matching item\'s selection. Selecting items follows the behavior described in the docstring of the \'get\' method. if the item is disabled, or this control is disabled or readonly, raise AttributeError.'
def toggle(self, name, by_label=False, nr=None):
deprecation('item = control.get(...); item.selected = not item.selected') o = self._get(name, by_label, nr) self._set_selected_state(o, (not o.selected))
'Deprecated: given a name or label and optional disambiguating index nr, set the matching item\'s selection to the bool value of selected. Selecting items follows the behavior described in the docstring of the \'get\' method. if the item is disabled, or this control is disabled or readonly, raise AttributeError.'
def set(self, selected, name, by_label=False, nr=None):
deprecation('control.get(...).selected = <boolean>') self._set_selected_state(self._get(name, by_label, nr), selected)
'Deprecated: toggle the selection of the single item in this control. Raises ItemCountError if the control does not contain only one item. by_label argument is ignored, and included only for backwards compatibility.'
def toggle_single(self, by_label=None):
deprecation('control.items[0].selected = not control.items[0].selected') if (len(self.items) != 1): raise ItemCountError(("'%s' is not a single-item control" % self.name)) item = self.items[0] self._set_selected_state(item, (not item.selected))
'Deprecated: set the selection of the single item in this control. Raises ItemCountError if the control does not contain only one item. by_label argument is ignored, and included only for backwards compatibility.'
def set_single(self, selected, by_label=None):
deprecation('control.items[0].selected = <boolean>') if (len(self.items) != 1): raise ItemCountError(("'%s' is not a single-item control" % self.name)) self._set_selected_state(self.items[0], selected)
'Get disabled state of named list item in a ListControl.'
def get_item_disabled(self, name, by_label=False, nr=None):
deprecation('control.get(...).disabled') return self._get(name, by_label, nr).disabled
'Set disabled state of named list item in a ListControl. disabled: boolean disabled state'
def set_item_disabled(self, disabled, name, by_label=False, nr=None):
deprecation('control.get(...).disabled = <boolean>') self._get(name, by_label, nr).disabled = disabled
'Set disabled state of all list items in a ListControl. disabled: boolean disabled state'
def set_all_items_disabled(self, disabled):
for o in self.items: o.disabled = disabled
'Return dictionary of HTML attributes for a single ListControl item. The HTML element types that describe list items are: OPTION for SELECT controls, INPUT for the rest. These elements have HTML attributes that you may occasionally want to know about -- for example, the "alt" HTML attribute gives a text string describ...
def get_item_attrs(self, name, by_label=False, nr=None):
deprecation('control.get(...).attrs') return self._get(name, by_label, nr).attrs
'ListControls are built up from component list items (which are also ListControls) during parsing. This method should be called after all items have been added. See ListControl.__doc__ for the reason this is required.'
def fixup(self):
for o in self.items: o.__dict__['_control'] = self
'Set the value of control by item labels. value is expected to be an iterable of strings that are substrings of the item labels that should be selected. Before substring matching is performed, the original label text is whitespace-compressed (consecutive whitespace characters are converted to a single space character)...
def set_value_by_label(self, value):
if isstringlike(value): raise TypeError(value) if ((not self.multiple) and (len(value) > 1)): raise ItemCountError('single selection list, must set sequence of length 0 or 1') items = [] for nn in value: found = self.get_items(label=nn) if (l...
'Return the value of the control as given by normalized labels.'
def get_value_by_label(self):
res = [] compat = self._form.backwards_compat for o in self.items: if (((not o.disabled) or compat) and o.selected): for l in o.get_labels(): if l.text: res.append(l.text) break else: res.append(None) ...
'Deprecated: return the names or labels of all possible items. Includes disabled items, which may be misleading for some use cases.'
def possible_items(self, by_label=False):
deprecation('[item.name for item in self.items]') if by_label: res = [] for o in self.items: for l in o.get_labels(): if l.text: res.append(l.text) break else: res.append(None) ret...