desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Returns the first item that matches the given criteria and appears after this Tag in the document.'
def findNext(self, name=None, attrs={}, text=None, **kwargs):
return self._findOne(self.findAllNext, name, attrs, text, **kwargs)
'Returns all items that match the given criteria and appear after this Tag in the document.'
def findAllNext(self, name=None, attrs={}, text=None, limit=None, **kwargs):
return self._findAll(name, attrs, text, limit, self.nextGenerator, **kwargs)
'Returns the closest sibling to this Tag that matches the given criteria and appears after this Tag in the document.'
def findNextSibling(self, name=None, attrs={}, text=None, **kwargs):
return self._findOne(self.findNextSiblings, name, attrs, text, **kwargs)
'Returns the siblings of this Tag that match the given criteria and appear after this Tag in the document.'
def findNextSiblings(self, name=None, attrs={}, text=None, limit=None, **kwargs):
return self._findAll(name, attrs, text, limit, self.nextSiblingGenerator, **kwargs)
'Returns the first item that matches the given criteria and appears before this Tag in the document.'
def findPrevious(self, name=None, attrs={}, text=None, **kwargs):
return self._findOne(self.findAllPrevious, name, attrs, text, **kwargs)
'Returns all items that match the given criteria and appear before this Tag in the document.'
def findAllPrevious(self, name=None, attrs={}, text=None, limit=None, **kwargs):
return self._findAll(name, attrs, text, limit, self.previousGenerator, **kwargs)
'Returns the closest sibling to this Tag that matches the given criteria and appears before this Tag in the document.'
def findPreviousSibling(self, name=None, attrs={}, text=None, **kwargs):
return self._findOne(self.findPreviousSiblings, name, attrs, text, **kwargs)
'Returns the siblings of this Tag that match the given criteria and appear before this Tag in the document.'
def findPreviousSiblings(self, name=None, attrs={}, text=None, limit=None, **kwargs):
return self._findAll(name, attrs, text, limit, self.previousSiblingGenerator, **kwargs)
'Returns the closest parent of this Tag that matches the given criteria.'
def findParent(self, name=None, attrs={}, **kwargs):
r = None l = self.findParents(name, attrs, 1) if l: r = l[0] return r
'Returns the parents of this Tag that match the given criteria.'
def findParents(self, name=None, attrs={}, limit=None, **kwargs):
return self._findAll(name, attrs, None, limit, self.parentGenerator, **kwargs)
'Iterates over a generator looking for things that match.'
def _findAll(self, name, attrs, text, limit, generator, **kwargs):
if isinstance(name, SoupStrainer): strainer = name elif ((text is None) and (not limit) and (not attrs) and (not kwargs)): if (name is True): return [element for element in generator() if isinstance(element, Tag)] elif isinstance(name, basestring): return [element...
'Encodes an object to a string in some encoding, or to Unicode.'
def toEncoding(self, s, encoding=None):
if isinstance(s, unicode): if encoding: s = s.encode(encoding) elif isinstance(s, str): if encoding: s = s.encode(encoding) else: s = unicode(s) elif encoding: s = self.toEncoding(str(s), encoding) else: s = unicode(s) retur...
'Used with a regular expression to substitute the appropriate XML entity for an XML special character.'
def _sub_entity(self, x):
return (('&' + self.XML_SPECIAL_CHARS_TO_ENTITIES[x.group(0)[0]]) + ';')
'Create a new NavigableString. When unpickling a NavigableString, this method is called with the string in DEFAULT_OUTPUT_ENCODING. That encoding needs to be passed in to the superclass\'s __new__ or the superclass won\'t know how to handle non-ASCII characters.'
def __new__(cls, value):
if isinstance(value, unicode): return unicode.__new__(cls, value) return unicode.__new__(cls, value, DEFAULT_OUTPUT_ENCODING)
'text.string gives you text. This is for backwards compatibility for Navigable*String, but for CData* it lets you get the string without the CData wrapper.'
def __getattr__(self, attr):
if (attr == 'string'): return self else: raise AttributeError, ("'%s' object has no attribute '%s'" % (self.__class__.__name__, attr))
'Used in a call to re.sub to replace HTML, XML, and numeric entities with the appropriate Unicode characters. If HTML entities are being converted, any unrecognized entities are escaped.'
def _convertEntities(self, match):
x = match.group(1) if (self.convertHTMLEntities and (x in name2codepoint)): return unichr(name2codepoint[x]) elif (x in self.XML_ENTITIES_TO_SPECIAL_CHARS): if self.convertXMLEntities: return self.XML_ENTITIES_TO_SPECIAL_CHARS[x] else: return (u'&%s;' % x) ...
'Basic constructor.'
def __init__(self, parser, name, attrs=None, parent=None, previous=None):
self.parserClass = parser.__class__ self.isSelfClosing = parser.isSelfClosingTag(name) self.name = name if (attrs is None): attrs = [] elif isinstance(attrs, dict): attrs = attrs.items() self.attrs = attrs self.contents = [] self.setup(parent, previous) self.hidden = ...
'Replace the contents of the tag with a string'
def setString(self, string):
self.clear() self.append(string)
'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') ...
'True if this class is actually needed. If false, then the output stream will not be affected, nor will win32 calls be issued, so wrapping stdout is not actually required. This will generally be False on non-Windows platforms, unless optional functionality like autoreset has been requested using kwargs to init()'
def should_wrap(self):
return (self.convert or self.strip or self.autoreset)
'Write the given text to our wrapped stream, stripping any ANSI sequences from the text, and optionally converting them into win32 calls.'
def write_and_convert(self, text):
cursor = 0 text = self.convert_osc(text) for match in self.ANSI_CSI_RE.finditer(text): (start, end) = match.span() self.write_plain_text(text, cursor, start) self.convert_ansi(*match.groups()) cursor = end self.write_plain_text(text, cursor, len(text))
'Create an instance of the CallbackManager'
def __init__(self):
self._stack = dict()
'Add a callback to the stack for the specified key. If the call is specified as one_shot, it will be removed after being fired The prefix is usually the channel number but the class is generic and prefix and key may be any value. If you pass in only_caller CallbackManager will restrict processing of the callback to onl...
@sanitize_prefix def add(self, prefix, key, callback, one_shot=True, only_caller=None, arguments=None):
if (prefix not in self._stack): self._stack[prefix] = dict() if (key not in self._stack[prefix]): self._stack[prefix][key] = list() for callback_dict in self._stack[prefix][key]: if ((callback_dict[self.CALLBACK] == callback) and (callback_dict[self.ARGUMENTS] == arguments) and (call...
'Clear all the callbacks if there are any defined.'
def clear(self):
self._stack = dict() LOGGER.debug('Callbacks cleared')
'Remove all callbacks from the stack by a prefix. Returns True if keys were there to be removed :param str or int prefix: The prefix for keeping track of callbacks with :rtype: bool'
@sanitize_prefix def cleanup(self, prefix):
LOGGER.debug('Clearing out %r from the stack', prefix) if ((prefix not in self._stack) or (not self._stack[prefix])): return False del self._stack[prefix] return True
'Return count of callbacks for a given prefix or key or None :param prefix: Categorize the callback :type prefix: str or int :param key: The key for the callback :type key: object or str or dict :rtype: None or int'
@sanitize_prefix def pending(self, prefix, key):
if ((not (prefix in self._stack)) or (not (key in self._stack[prefix]))): return None return len(self._stack[prefix][key])
'Run through and process all the callbacks for the specified keys. Caller should be specified at all times so that callbacks which require a specific function to call CallbackManager.process will not be processed. :param prefix: Categorize the callback :type prefix: str or int :param key: The key for the callback :type...
@sanitize_prefix @check_for_prefix_and_key def process(self, prefix, key, caller, *args, **keywords):
LOGGER.debug('Processing %s:%s', prefix, key) if ((prefix not in self._stack) or (key not in self._stack[prefix])): return False callbacks = list() for callback_dict in list(self._stack[prefix][key]): if self._should_process_callback(callback_dict, caller, list(args)): cal...
'Remove a callback from the stack by prefix, key and optionally the callback itself. If you only pass in prefix and key, all callbacks for that prefix and key will be removed. :param str or int prefix: The prefix for keeping track of callbacks with :param str key: The callback key :param method callback_value: The meth...
@sanitize_prefix @check_for_prefix_and_key def remove(self, prefix, key, callback_value=None, arguments=None):
if callback_value: offsets_to_remove = list() for offset in xrange(len(self._stack[prefix][key]), 0, (-1)): callback_dict = self._stack[prefix][key][(offset - 1)] if ((callback_dict[self.CALLBACK] == callback_value) and self._arguments_match(callback_dict, [arguments])): ...
'Remove all callbacks for the specified prefix and key. :param str prefix: The prefix for keeping track of callbacks with :param str key: The callback key'
@sanitize_prefix @check_for_prefix_and_key def remove_all(self, prefix, key):
del self._stack[prefix][key] self._cleanup_callback_dict(prefix, key)
'Validate if the arguments passed in match the expected arguments in the callback_dict. We expect this to be a frame passed in to *args for process or passed in as a list from remove. :param dict callback_dict: The callback dictionary to evaluate against :param list args: The arguments passed in as a list'
def _arguments_match(self, callback_dict, args):
if (callback_dict[self.ARGUMENTS] is None): return True if (not args): return False if isinstance(args[0], dict): return self._dict_arguments_match(args[0], callback_dict[self.ARGUMENTS]) return self._obj_arguments_match((args[0].method if hasattr(args[0], 'method') else args[0])...
'Return the callback dictionary. :param method callback: The callback to call :param bool one_shot: Remove this callback after it is called :param object only_caller: Only allow one_caller value to call the event that fires the callback. :rtype: dict'
def _callback_dict(self, callback, one_shot, only_caller, arguments):
value = {self.CALLBACK: callback, self.ONE_SHOT: one_shot, self.ONLY_CALLER: only_caller, self.ARGUMENTS: arguments} if one_shot: value[self.CALLS] = 1 return value
'Remove empty dict nodes in the callback stack. :param str or int prefix: The prefix for keeping track of callbacks with :param str key: The callback key'
def _cleanup_callback_dict(self, prefix, key=None):
if (key and (key in self._stack[prefix]) and (not self._stack[prefix][key])): del self._stack[prefix][key] if ((prefix in self._stack) and (not self._stack[prefix])): del self._stack[prefix]
'Checks an dict to see if it has attributes that meet the expectation. :param dict value: The dict to evaluate :param dict expectation: The values to check against :rtype: bool'
@staticmethod def _dict_arguments_match(value, expectation):
LOGGER.debug('Comparing %r to %r', value, expectation) for key in expectation: if (value.get(key) != expectation[key]): LOGGER.debug('Values in dict do not match for %s', key) return False return True
'Checks an object to see if it has attributes that meet the expectation. :param object value: The object to evaluate :param dict expectation: The values to check against :rtype: bool'
@staticmethod def _obj_arguments_match(value, expectation):
for key in expectation: if (not hasattr(value, key)): LOGGER.debug('%r does not have required attribute: %s', type(value), key) return False if (getattr(value, key) != expectation[key]): LOGGER.debug('Values in %s do not match f...
'Returns True if the callback should be processed. :param dict callback_dict: The callback configuration :param object caller: Who is firing the event :param list args: Any optional arguments :rtype: bool'
def _should_process_callback(self, callback_dict, caller, args):
if (not self._arguments_match(callback_dict, args)): LOGGER.debug('Arguments do not match for %r, %r', callback_dict, args) return False return ((callback_dict[self.ONLY_CALLER] is None) or (callback_dict[self.ONLY_CALLER] and (callback_dict[self.ONLY_CALLER] == caller)))
'Process the one-shot callback, decrementing the use counter and removing it from the stack if it\'s now been fully used. :param str or int prefix: The prefix for keeping track of callbacks with :param str key: The callback key :param dict callback_dict: The callback dict to process'
def _use_one_shot_callback(self, prefix, key, callback_dict):
LOGGER.debug('Processing use of oneshot callback') callback_dict[self.CALLS] -= 1 LOGGER.debug('%i registered uses left', callback_dict[self.CALLS]) if (callback_dict[self.CALLS] <= 0): self.remove(prefix, key, callback_dict[self.CALLBACK], callback_dict[self.ARGUMENTS])
'Create a new instance of a frame :param int frame_type: The frame type :param int channel_number: The channel number for the frame'
def __init__(self, frame_type, channel_number):
self.frame_type = frame_type self.channel_number = channel_number
'Create the full AMQP wire protocol frame data representation :rtype: bytes'
def _marshal(self, pieces):
payload = ''.join(pieces) return ((struct.pack('>BHI', self.frame_type, self.channel_number, len(payload)) + payload) + byte(spec.FRAME_END))
'To be ended by child classes :raises NotImplementedError'
def marshal(self):
raise NotImplementedError
'Create a new instance of a frame :param int channel_number: The frame type :param pika.Spec.Class.Method method: The AMQP Class.Method'
def __init__(self, channel_number, method):
Frame.__init__(self, spec.FRAME_METHOD, channel_number) self.method = method
'Return the AMQP binary encoded value of the frame :rtype: str'
def marshal(self):
pieces = self.method.encode() pieces.insert(0, struct.pack('>I', self.method.INDEX)) return self._marshal(pieces)
'Create a new instance of a AMQP ContentHeader object :param int channel_number: The channel number for the frame :param int body_size: The number of bytes for the body :param pika.spec.BasicProperties props: Basic.Properties object'
def __init__(self, channel_number, body_size, props):
Frame.__init__(self, spec.FRAME_HEADER, channel_number) self.body_size = body_size self.properties = props
'Return the AMQP binary encoded value of the frame :rtype: str'
def marshal(self):
pieces = self.properties.encode() pieces.insert(0, struct.pack('>HxxQ', self.properties.INDEX, self.body_size)) return self._marshal(pieces)
'Parameters: - channel_number: int - fragment: unicode or str'
def __init__(self, channel_number, fragment):
Frame.__init__(self, spec.FRAME_BODY, channel_number) self.fragment = fragment
'Return the AMQP binary encoded value of the frame :rtype: str'
def marshal(self):
return self._marshal([self.fragment])
'Create a new instance of the Heartbeat frame'
def __init__(self):
Frame.__init__(self, spec.FRAME_HEARTBEAT, 0)
'Return the AMQP binary encoded value of the frame :rtype: str'
def marshal(self):
return self._marshal(list())
'Construct a Protocol Header frame object for the specified AMQP version :param int major: Major version number :param int minor: Minor version number :param int revision: Revision'
def __init__(self, major=None, minor=None, revision=None):
self.frame_type = (-1) self.major = (major or spec.PROTOCOL_VERSION[0]) self.minor = (minor or spec.PROTOCOL_VERSION[1]) self.revision = (revision or spec.PROTOCOL_VERSION[2])
'Return the full AMQP wire protocol frame data representation of the ProtocolHeader frame :rtype: str'
def marshal(self):
return ('AMQP' + struct.pack('BBBB', 0, self.major, self.minor, self.revision))
'If the method is a content frame, set the properties and body to be carried as attributes of the class. :param pika.frame.Properties properties: AMQP Basic Properties :param body: The message body :type body: str or unicode'
def _set_content(self, properties, body):
self._properties = properties self._body = body
'Return the properties if they are set. :rtype: pika.frame.Properties'
def get_properties(self):
return self._properties
'Return the message body if it is set. :rtype: str|unicode'
def get_body(self):
return self._body
':param messages: sequence of returned unroutable messages :type messages: sequence of `blocking_connection.ReturnedMessage` objects'
def __init__(self, messages):
super(UnroutableError, self).__init__(('%s unroutable message(s) returned' % len(messages))) self.messages = messages
':param messages: sequence of returned unroutable messages :type messages: sequence of `blocking_connection.ReturnedMessage` objects'
def __init__(self, messages):
super(NackError, self).__init__(('%s message(s) NACKed' % len(messages))) self.messages = messages
'Create a new instance of the Channel :param pika.connection.Connection connection: The connection :param int channel_number: The channel number for this instance :param callable on_open_callback: The callback to call on channel open'
def __init__(self, connection, channel_number, on_open_callback):
if (not isinstance(channel_number, int)): raise exceptions.InvalidChannelNumber self.channel_number = channel_number self.callbacks = connection.callbacks self.connection = connection self.flow_active = True self._content_assembler = ContentFrameAssembler() self._blocked = collection...
'Return the channel object as its channel number :rtype: int'
def __int__(self):
return self.channel_number
'Pass in a callback handler and a list replies from the RabbitMQ broker which you\'d like the callback notified of. Callbacks should allow for the frame parameter to be passed in. :param callable callback: The callback to call :param list replies: The replies to get a callback for :param bool one_shot: Only handle the ...
def add_callback(self, callback, replies, one_shot=True):
for reply in replies: self.callbacks.add(self.channel_number, reply, callback, one_shot)
'Pass a callback function that will be called when the basic_cancel is sent by the server. The callback function should receive a frame parameter. :param callable callback: The callback to call on Basic.Cancel from broker'
def add_on_cancel_callback(self, callback):
self.callbacks.add(self.channel_number, spec.Basic.Cancel, callback, False)
'Pass a callback function that will be called when the channel is closed. The callback function will receive the channel, the reply_code (int) and the reply_text (int) describing why the channel was closed. If the channel is closed by broker via Channel.Close, the callback will receive the reply_code/reply_text provide...
def add_on_close_callback(self, callback):
self.callbacks.add(self.channel_number, '_on_channel_close', callback, False, self)
'Pass a callback function that will be called when Channel.Flow is called by the remote server. Note that newer versions of RabbitMQ will not issue this but instead use TCP backpressure :param callable callback: The callback function'
def add_on_flow_callback(self, callback):
self._has_on_flow_callback = True self.callbacks.add(self.channel_number, spec.Channel.Flow, callback, False)
'Pass a callback function that will be called when basic_publish as sent a message that has been rejected and returned by the server. :param callable callback: The function to call, having the signature callback(channel, method, properties, body) where channel: pika.Channel method: pika.spec.Basic.Return properties: pi...
def add_on_return_callback(self, callback):
self.callbacks.add(self.channel_number, '_on_return', callback, False)
'Acknowledge one or more messages. When sent by the client, this method acknowledges one or more messages delivered via the Deliver or Get-Ok methods. When sent by server, this method acknowledges one or more messages published with the Publish method on a channel in confirm mode. The acknowledgement can be for a singl...
def basic_ack(self, delivery_tag=0, multiple=False):
if (not self.is_open): raise exceptions.ChannelClosed() return self._send_method(spec.Basic.Ack(delivery_tag, multiple))
'This method cancels a consumer. This does not affect already delivered messages, but it does mean the server will not send any more messages for that consumer. The client may receive an arbitrary number of messages in between sending the cancel method and receiving the cancel-ok reply. It may also be sent from the ser...
def basic_cancel(self, callback=None, consumer_tag='', nowait=False):
self._validate_channel_and_callback(callback) if nowait: if (callback is not None): raise ValueError('Completion callback must be None when nowait=True') elif (callback is None): raise ValueError('Must have completion callback with nowait=False') ...
'Sends the AMQP 0-9-1 command Basic.Consume to the broker and binds messages for the consumer_tag to the consumer callback. If you do not pass in a consumer_tag, one will be automatically generated for you. Returns the consumer tag. For more information on basic_consume, see: Tutorial 2 at http://www.rabbitmq.com/getst...
def basic_consume(self, consumer_callback, queue='', no_ack=False, exclusive=False, consumer_tag=None, arguments=None):
self._validate_channel_and_callback(consumer_callback) if (not consumer_tag): consumer_tag = self._generate_consumer_tag() if ((consumer_tag in self._consumers) or (consumer_tag in self._cancelled)): raise exceptions.DuplicateConsumerTag(consumer_tag) if no_ack: self._consumers_w...
'Generate a consumer tag NOTE: this protected method may be called by derived classes :returns: consumer tag :rtype: str'
def _generate_consumer_tag(self):
return ('ctag%i.%s' % (self.channel_number, uuid.uuid4().hex))
'Get a single message from the AMQP broker. If you want to be notified of Basic.GetEmpty, use the Channel.add_callback method adding your Basic.GetEmpty callback which should expect only one parameter, frame. Due to implementation details, this cannot be called a second time until the callback is executed. For more in...
def basic_get(self, callback=None, queue='', no_ack=False):
self._validate_channel_and_callback(callback) if (self._on_getok_callback is not None): raise exceptions.DuplicateGetOkCallback() self._on_getok_callback = callback self._send_method(spec.Basic.Get(queue=queue, no_ack=no_ack))