code
stringlengths
52
7.75k
docs
stringlengths
1
5.85k
def mkdir(jottapath, JFS): jf = JFS.post('%s?mkDir=true' % jottapath) return instanceof(jf, JFSFolder)
Make a new directory (a.k.a. folder) on JottaCloud. Returns boolean
def iter_tree(jottapath, JFS): filedirlist = JFS.getObject('%s?mode=list' % jottapath) log.debug("got tree: %s", filedirlist) if not isinstance(filedirlist, JFSFileDirList): yield ( '', tuple(), tuple() ) for path in filedirlist.tree: yield path
Get a tree of of files and folders. use as an iterator, you get something like os.walk
def _query(self, filename): # - Query metadata of one file # - Return a dict with a 'size' key, and a file size value (-1 for not found) # - Retried if an exception is thrown log.Info('Querying size of %s' % filename) from jottalib.JFS import JFSNotFoundError, JFSInco...
Get size of filename
def parse_drawing(document, container, elem): _blip = elem.xpath('.//a:blip', namespaces=NAMESPACES) if len(_blip) > 0: blip = _blip[0] _rid = blip.attrib[_name('{{{r}}}embed')] img = doc.Image(_rid) container.elements.append(img)
Parse drawing element. We don't do much with drawing element. We can find embeded image but we don't do more than that.
def parse_footnote(document, container, elem): "Parse the footnote element." _rid = elem.attrib[_name('{{{w}}}id')] foot = doc.Footnote(_rid) container.elements.append(footf parse_footnote(document, container, elem): "Parse the footnote element." _rid = elem.attrib[_name('{{{w}}}id')] foot...
Parse the footnote element.
def parse_endnote(document, container, elem): "Parse the endnote element." _rid = elem.attrib[_name('{{{w}}}id')] note = doc.Endnote(_rid) container.elements.append(notef parse_endnote(document, container, elem): "Parse the endnote element." _rid = elem.attrib[_name('{{{w}}}id')] note = do...
Parse the endnote element.
def parse_smarttag(document, container, tag_elem): "Parse the endnote element." tag = doc.SmartTag() tag.element = tag_elem.attrib[_name('{{{w}}}element')] for elem in tag_elem: if elem.tag == _name('{{{w}}}r'): parse_text(document, tag, elem) if elem.tag == _name('{{{w}}...
Parse the endnote element.
def parse_paragraph(document, par): paragraph = doc.Paragraph() paragraph.document = document for elem in par: if elem.tag == _name('{{{w}}}pPr'): parse_paragraph_properties(document, paragraph, elem) if elem.tag == _name('{{{w}}}r'): parse_text(document, para...
Parse paragraph element. Some other elements could be found inside of paragraph element (math, links).
def parse_table_properties(doc, table, prop): "Parse table properties." if not table: return style = prop.find(_name('{{{w}}}tblStyle')) if style is not None: table.style_id = style.attrib[_name('{{{w}}}val')] doc.add_style_as_used(table.style_idf parse_table_properties(doc, t...
Parse table properties.
def parse_table_column_properties(doc, cell, prop): "Parse table column properties." if not cell: return grid = prop.find(_name('{{{w}}}gridSpan')) if grid is not None: cell.grid_span = int(grid.attrib[_name('{{{w}}}val')]) vmerge = prop.find(_name('{{{w}}}vMerge')) if vmerg...
Parse table column properties.
def parse_document(xmlcontent): document = etree.fromstring(xmlcontent) body = document.xpath('.//w:body', namespaces=NAMESPACES)[0] document = doc.Document() for elem in body: if elem.tag == _name('{{{w}}}p'): document.elements.append(parse_paragraph(document, elem)) ...
Parse document with content. Content is placed in file 'document.xml'.
def parse_relationship(document, xmlcontent, rel_type): doc = etree.fromstring(xmlcontent) for elem in doc: if elem.tag == _name('{{{pr}}}Relationship'): rel = {'target': elem.attrib['Target'], 'type': elem.attrib['Type'], 'target_mode': elem.attr...
Parse relationship document. Relationships hold information like external or internal references for links. Relationships are placed in file '_rels/document.xml.rels'.
def parse_style(document, xmlcontent): styles = etree.fromstring(xmlcontent) _r = styles.xpath('.//w:rPrDefault', namespaces=NAMESPACES) if len(_r) > 0: rpr = _r[0].find(_name('{{{w}}}rPr')) if rpr is not None: st = doc.Style() parse_previous_properties(docum...
Parse styles document. Styles are defined in file 'styles.xml'.
def parse_comments(document, xmlcontent): comments = etree.fromstring(xmlcontent) document.comments = {} for comment in comments.xpath('.//w:comment', namespaces=NAMESPACES): # w:author # w:id # w: date comment_id = comment.attrib[_name('{{{w}}}id')] comm = do...
Parse comments document. Comments are defined in file 'comments.xml'
def parse_footnotes(document, xmlcontent): footnotes = etree.fromstring(xmlcontent) document.footnotes = {} for footnote in footnotes.xpath('.//w:footnote', namespaces=NAMESPACES): _type = footnote.attrib.get(_name('{{{w}}}type'), None) # don't know what to do with these now ...
Parse footnotes document. Footnotes are defined in file 'footnotes.xml'
def parse_endnotes(document, xmlcontent): endnotes = etree.fromstring(xmlcontent) document.endnotes = {} for note in endnotes.xpath('.//w:endnote', namespaces=NAMESPACES): paragraphs = [parse_paragraph(document, para) for para in note.xpath('.//w:p', namespaces=NAMESPACES)] document....
Parse endnotes document. Endnotes are defined in file 'endnotes.xml'
def parse_numbering(document, xmlcontent): numbering = etree.fromstring(xmlcontent) document.abstruct_numbering = {} document.numbering = {} for abstruct_num in numbering.xpath('.//w:abstractNum', namespaces=NAMESPACES): numb = {} for lvl in abstruct_num.xpath('./w:lvl', namespac...
Parse numbering document. Numbering is defined in file 'numbering.xml'.
def get_by_name(self, name, style_type = None): for st in self.styles.values(): if st: if st.name == name: return st if style_type and not st: st = self.styles.get(self.default_styles[style_type], None) return st
Find style by it's descriptive name. :Returns: Returns found style of type :class:`ooxml.doc.Style`.
def get_by_id(self, style_id, style_type = None): for st in self.styles.values(): if st: if st.style_id == style_id: return st if style_type: return self.styles.get(self.default_styles[style_type], None) return None
Find style by it's unique identifier :Returns: Returns found style of type :class:`ooxml.doc.Style`.
def process_affinity(affinity=None): if affinity is not None: affinity = CPUSet(affinity) if not affinity.issubset(system_affinity()): raise ValueError("unknown cpus: %s" % affinity) return system_affinity()
Get or set the CPU affinity set for the current process. This will affect all future threads spawned by this process. It is implementation-defined whether it will also affect previously-spawned threads.
def acquire(self,blocking=True,timeout=None): if timeout is None: return self.__lock.acquire(blocking) else: # Simulated timeout using progressively longer sleeps. # This is the same timeout scheme used in the stdlib Condition # class. If ther...
Attempt to acquire this lock. If the optional argument "blocking" is True and "timeout" is None, this methods blocks until is successfully acquires the lock. If "blocking" is False, it returns immediately if the lock could not be acquired. Otherwise, it blocks for at most "timeout" se...
def from_thread(cls,thread): new_classes = [] for new_cls in cls.__mro__: if new_cls not in thread.__class__.__mro__: new_classes.append(new_cls) if isinstance(thread,cls): pass elif issubclass(cls,thread.__class__): thread.__c...
Convert a vanilla thread object into an instance of this class. This method "upgrades" a vanilla thread object to an instance of this extended class. You might need to call this if you obtain a reference to a thread by some means other than (a) creating it, or (b) from the methods of ...
def acquire(self,blocking=True,timeout=None,shared=False): with self._lock: if shared: self._acquire_shared(blocking,timeout) else: self._acquire_exclusive(blocking,timeout) assert not (self.is_shared and self.is_exclusive)
Acquire the lock in shared or exclusive mode.
def release(self): # This decrements the appropriate lock counters, and if the lock # becomes free, it looks for a queued thread to hand it off to. # By doing the handoff here we ensure fairness. me = currentThread() with self._lock: if self.is_exclusive: ...
Release the lock.
def read_from_file(file_name): from .docxfile import DOCXFile dfile = DOCXFile(file_name) dfile.parse() return dfile
Parser OOXML file and returns parsed document. :Args: - file_name (str): Path to OOXML file :Returns: Returns object of type :class:`ooxml.docx.DOCXFile`.
def _get_font_size(document, style): font_size = style.get_font_size() if font_size == -1: if style.based_on: based_on = document.styles.get_by_id(style.based_on) if based_on: return _get_font_size(document, based_on) return font_size
Get font size defined for this style. It will try to get font size from it's parent style if it is not defined by original style. :Args: - document (:class:`ooxml.doc.Document`): Document object - style (:class:`ooxml.doc.Style`): Style object :Returns: Returns font size as a number. -...
def _get_numbering(document, numid, ilvl): try: abs_num = document.numbering[numid] return document.abstruct_numbering[abs_num][ilvl]['numFmt'] except: return 'bullet'
Returns type for the list. :Returns: Returns type for the list. Returns "bullet" by default or in case of an error.
def _get_parent(root): elem = root while True: elem = elem.getparent() if elem.tag in ['ul', 'ol']: return elem
Returns root element for a list. :Args: root (Element): lxml element of current location :Returns: lxml element representing list
def close_list(ctx, root): try: n = len(ctx.in_list) if n <= 0: return root elem = root while n > 0: while True: if elem.tag in ['ul', 'ol', 'td']: elem = elem.getparent() brea...
Close already opened list if needed. This will try to see if it is needed to close already opened list. :Args: - ctx (:class:`Context`): Context object - root (Element): lxml element representing current position. :Returns: lxml element where future content should be placed.
def serialize_break(ctx, document, elem, root): "Serialize break element." if elem.break_type == u'textWrapping': _div = etree.SubElement(root, 'br') else: _div = etree.SubElement(root, 'span') if ctx.options['embed_styles']: _div.set('style', 'page-break-after: always;'...
Serialize break element.
def serialize_math(ctx, document, elem, root): _div = etree.SubElement(root, 'span') if ctx.options['embed_styles']: _div.set('style', 'border: 1px solid red') _div.text = 'We do not support Math blocks at the moment.' fire_hooks(ctx, document, elem, _div, ctx.get_hook('math')) retur...
Serialize math element. Math objects are not supported at the moment. This is wht we only show error message.
def serialize_link(ctx, document, elem, root): _a = etree.SubElement(root, 'a') for el in elem.elements: _ser = ctx.get_serializer(el) if _ser: _td = _ser(ctx, document, el, _a) else: if isinstance(el, doc.Text): children = list(_a) ...
Serilaze link element. This works only for external links at the moment.
def serialize_image(ctx, document, elem, root): _img = etree.SubElement(root, 'img') # make path configurable if elem.rid in document.relationships[ctx.options['relationship']]: img_src = document.relationships[ctx.options['relationship']][elem.rid].get('target', '') img_name, img_ext...
Serialize image element. This is not abstract enough.
def fire_hooks(ctx, document, elem, element, hooks): if not hooks: return for hook in hooks: hook(ctx, document, elem, element)
Fire hooks on newly created element. For each newly created element we will try to find defined hooks and execute them. :Args: - ctx (:class:`Context`): Context object - document (:class:`ooxml.doc.Document`): Document object - elem (:class:`ooxml.doc.Element`): Element which we serialized ...
def has_style(node): elements = ['b', 'i', 'u', 'strike', 'color', 'jc', 'sz', 'ind', 'superscript', 'subscript', 'small_caps'] return any([True for elem in elements if elem in node.rpr])
Tells us if node element has defined styling. :Args: - node (:class:`ooxml.doc.Element`): Element :Returns: True or False
def get_all_styles(document, style): classes = [] while True: classes.insert(0, get_style_name(style)) if style.based_on: style = document.styles.get_by_id(style.based_on) else: break return classes
Returns list of styles on which specified style is based on. :Args: - document (:class:`ooxml.doc.Document`): Document object - style (:class:`ooxml.doc.Style`): Style object :Returns: List of style objects.
def get_css_classes(document, style): lst = [st.lower() for st in get_all_styles(document, style)[-1:]] + \ ['{}-fontsize'.format(st.lower()) for st in get_all_styles(document, style)[-1:]] return ' '.join(lst)
Returns CSS classes for this style. This function will check all the styles specified style is based on and return their CSS classes. :Args: - document (:class:`ooxml.doc.Document`): Document object - style (:class:`ooxml.doc.Style`): Style object :Returns: String representing all the C...
def serialize_symbol(ctx, document, el, root): "Serialize special symbols." span = etree.SubElement(root, 'span') span.text = el.value() fire_hooks(ctx, document, el, span, ctx.get_hook('symbol')) return roof serialize_symbol(ctx, document, el, root): "Serialize special symbols." span = ...
Serialize special symbols.
def serialize_footnote(ctx, document, el, root): "Serializes footnotes." footnote_num = el.rid if el.rid not in ctx.footnote_list: ctx.footnote_id += 1 ctx.footnote_list[el.rid] = ctx.footnote_id footnote_num = ctx.footnote_list[el.rid] note = etree.SubElement(root, 'sup') li...
Serializes footnotes.
def serialize_comment(ctx, document, el, root): "Serializes comment." # Check if option is turned on if el.comment_type == 'end': ctx.opened_comments.remove(el.cid) else: if el.comment_type != 'reference': ctx.opened_comments.append(el.cid) if ctx.options['comment_...
Serializes comment.
def serialize_endnote(ctx, document, el, root): "Serializes endnotes." footnote_num = el.rid if el.rid not in ctx.endnote_list: ctx.endnote_id += 1 ctx.endnote_list[el.rid] = ctx.endnote_id footnote_num = ctx.endnote_list[el.rid] note = etree.SubElement(root, 'sup') link = et...
Serializes endnotes.
def serialize_smarttag(ctx, document, el, root): "Serializes smarttag." if ctx.options['smarttag_span']: _span = etree.SubElement(root, 'span', {'class': 'smarttag', 'data-smarttag-element': el.element}) else: _span = root for elem in el.elements: _ser = ctx.get_serializer(elem...
Serializes smarttag.
def serialize_table(ctx, document, table, root): # What we should check really is why do we pass None as root element # There is a good chance some content is missing after the import if root is None: return root if ctx.ilvl != None: root = close_list(ctx, root) ctx.ilvl,...
Serializes table element.
def serialize_textbox(ctx, document, txtbox, root): _div = etree.SubElement(root, 'div') _div.set('class', 'textbox') for elem in txtbox.elements: _ser = ctx.get_serializer(elem) if _ser: _ser(ctx, document, elem, _div) fire_hooks(ctx, document, txtbox, _div, ctx.get...
Serialize textbox element.
def serialize_elements(document, elements, options=None): ctx = Context(document, options) tree_root = root = etree.Element('div') for elem in elements: _ser = ctx.get_serializer(elem) if _ser: root = _ser(ctx, document, elem, root) # TODO: # - create footnot...
Serialize list of elements into HTML string. :Args: - document (:class:`ooxml.doc.Document`): Document object - elements (list): List of elements - options (dict): Optional dictionary with :class:`Context` options :Returns: Returns HTML representation of the document.
def is_header(self, elem, font_size, node, style=None): # This logic has been disabled for now. Mark this as header if it has # been marked during the parsing or mark. # if hasattr(elem, 'possible_header'): # if elem.possible_header: # ...
Used for checking if specific element is a header or not. :Returns: True or False
def get_header(self, elem, style, node): font_size = style if hasattr(elem, 'possible_header'): if elem.possible_header: return 'h1' if not style: return 'h6' if hasattr(style, 'style_id'): font_size = _get_font_size(self.doc...
Returns HTML tag representing specific header for this element. :Returns: String representation of HTML tag.
def get_serializer(self, node): return self.options['serializers'].get(type(node), None) if type(node) in self.options['serializers']: return self.options['serializers'][type(node)] return None
Returns serializer for specific element. :Args: - node (:class:`ooxml.doc.Element`): Element object :Returns: Returns reference to a function which will be used for serialization.
def priority(self,priority): with self.__lock: old_priorities = {} try: for thread in self.__threads: old_priorities[thread] = thread.priority thread.priority = priority except Exception: for (th...
Set the priority for all threads in this group. If setting priority fails on any thread, the priority of all threads is restored to its previous value.
def affinity(self,affinity): with self.__lock: old_affinities = {} try: for thread in self.__threads: old_affinities[thread] = thread.affinity thread.affinity = affinity except Exception: for (th...
Set the affinity for all threads in this group. If setting affinity fails on any thread, the affinity of all threads is restored to its previous value.
def join(self,timeout=None): if timeout is None: for thread in self.__threads: thread.join() else: deadline = _time() + timeout for thread in self.__threads: delay = deadline - _time() if delay <= 0: ...
Join all threads in this group. If the optional "timeout" argument is given, give up after that many seconds. This method returns True is the threads were successfully joined, False if a timeout occurred.
def text_length(elem): if not elem: return 0 value = elem.value() try: value = len(value) except: value = 0 try: for a in elem.elements: value += len(a.value()) except: pass return value
Returns length of the content in this element. Return value is not correct but it is **good enough***.
def reset(self): "Resets the values." self.zf = zipfile.ZipFile(self.file_name, 'r') self._doc = Nonf reset(self): "Resets the values." self.zf = zipfile.ZipFile(self.file_name, 'r') self._doc = None
Resets the values.
def _priority_range(policy=None): if policy is None: policy = libc.sched_getscheduler(0) if policy < 0: raise OSError(get_errno(),"sched_getscheduler") max = libc.sched_get_priority_max(policy) if max < 0: raise OSError(get_errno(),"sched_get_priority_max") min =...
Determine the priority range (min,max) for the given scheduler policy. If no policy is specified, the current default policy is used.
def _get_dynamic_attr(self, attname, obj, default=None): try: attr = getattr(self, attname) except AttributeError: return default if callable(attr): # Check co_argcount rather than try/excepting the function and # catching the TypeError, b...
Copied from django.contrib.syndication.views.Feed (v1.7.1)
def build_rrule(count=None, interval=None, bysecond=None, byminute=None, byhour=None, byweekno=None, bymonthday=None, byyearday=None, bymonth=None, until=None, bysetpos=None, wkst=None, byday=None, freq=None): result = {} if count is not None: result...
Build rrule dictionary for vRecur class. :param count: int :param interval: int :param bysecond: int :param byminute: int :param byhour: int :param byweekno: int :param bymonthday: int :param byyearday: int :param bymonth: int :param until: datetime :param bysetpos: int ...
def build_rrule_from_recurrences_rrule(rule): from recurrence import serialize line = serialize(rule) if line.startswith('RRULE:'): line = line[6:] return build_rrule_from_text(line)
Build rrule dictionary for vRecur class from a django_recurrences rrule. django_recurrences is a popular implementation for recurrences in django. https://pypi.org/project/django-recurrence/ this is a shortcut to interface between recurrences and icalendar.
def build_rrule_from_dateutil_rrule(rule): lines = str(rule).splitlines() for line in lines: if line.startswith('DTSTART:'): continue if line.startswith('RRULE:'): line = line[6:] return build_rrule_from_text(line)
Build rrule dictionary for vRecur class from a dateutil rrule. Dateutils rrule is a popular implementation of rrule in python. https://pypi.org/project/python-dateutil/ this is a shortcut to interface between dateutil and icalendar.
def write(self, outfile, encoding): u cal = Calendar() cal.add('version', '2.0') cal.add('calscale', 'GREGORIAN') for ifield, efield in FEED_FIELD_MAP: val = self.feed.get(ifield) if val is not None: cal.add(efield, val) self.writ...
u""" Writes the feed to the specified file in the specified encoding.
def write_items(self, calendar): for item in self.items: event = Event() for ifield, efield in ITEM_EVENT_FIELD_MAP: val = item.get(ifield) if val is not None: event.add(efield, val) calendar.add_component(event)
Write all events to the calendar
def _textlist(self, _addtail=False): '''Returns a list of text strings contained within an element and its sub-elements. Helpful for extracting text from prose-oriented XML (such as XHTML or DocBook). ''' result = [] if (not _addtail) and (self.text is not None): result.append(self.text) ...
Returns a list of text strings contained within an element and its sub-elements. Helpful for extracting text from prose-oriented XML (such as XHTML or DocBook).
def _reindent(s, indent, reformat=True): s = textwrap.dedent(s) s = s.split('\n') s = [x.rstrip() for x in s] while s and (not s[0]): s = s[1:] while s and (not s[-1]): s = s[:-1] if reformat: s = '\n'.join(s) s = textwrap.wrap(s, initial_indent=indent, subse...
Remove the existing indentation from each line of a chunk of text, s, and then prefix each line with a new indent string. Also removes trailing whitespace from each line, and leading and trailing blank lines.
def generate_docstr(element, indent='', wrap=None): result = [] txt = element.text and element.text.rstrip() if txt: result.append(_reindent(txt, indent)) result.append(indent) for d in element.findall('doc') + element.findall('rule'): docval = ''.join(d.textlist()).rstrip...
Generate a Python docstr for a given element in the AMQP XML spec file. The element could be a class or method The 'wrap' parameter is an optional chunk of text that's added to the beginning and end of the resulting docstring.
def _next_method(self): while self.queue.empty(): try: frame_type, channel, payload = self.source.read_frame() except Exception, e: # # Connection was closed? Framing Error? # self.queue.put(e) ...
Read the next method from the source, once one complete method has been assembled it is placed in the internal queue.
def _process_method_frame(self, channel, payload): method_sig = unpack('>HH', payload[:4]) args = AMQPReader(payload[4:]) if method_sig in _CONTENT_METHODS: # # Save what we've got so far and wait for the content-header # self.partial_mes...
Process Method frames
def _process_content_header(self, channel, payload): partial = self.partial_messages[channel] partial.add_header(payload) if partial.complete: # # a bodyless message, we're done # self.queue.put((channel, partial.method_sig, partial.args,...
Process Content Header frames
def _process_content_body(self, channel, payload): partial = self.partial_messages[channel] partial.add_payload(payload) if partial.complete: # # Stick the message in the queue and go back to # waiting for method frames # self....
Process Content Body frames
def read_method(self): self._next_method() m = self.queue.get() if isinstance(m, Exception): raise m return m
Read a method from the peer.
def _do_close(self): AMQP_LOGGER.debug('Closed channel #%d' % self.channel_id) self.is_open = False del self.connection.channels[self.channel_id] self.channel_id = self.connection = None self.callbacks = {}
Tear down this object, after we've agreed to close with the server.
def _alert(self, args): reply_code = args.read_short() reply_text = args.read_shortstr() details = args.read_table() self.alerts.put((reply_code, reply_text, details))
This method allows the server to send a non-fatal warning to the client. This is used for methods that are normally asynchronous and thus do not have confirmations, and for which the server may detect errors that need to be reported. Fatal errors are handled as channel or connection ex...
def close(self, reply_code=0, reply_text='', method_sig=(0, 0)): if not self.is_open: # already closed return args = AMQPWriter() args.write_short(reply_code) args.write_shortstr(reply_text) args.write_short(method_sig[0]) # class_id args...
request a channel close This method indicates that the sender wants to close the channel. This may be due to internal conditions (e.g. a forced shut-down) or due to an error handling a specific method, i.e. an exception. When a close is due to an exception, the sender provides ...
def _close(self, args): reply_code = args.read_short() reply_text = args.read_shortstr() class_id = args.read_short() method_id = args.read_short() # self.close_ok() # def close_ok(self): # """ # confirm a channel close # # This method confirms ...
request a channel close This method indicates that the sender wants to close the channel. This may be due to internal conditions (e.g. a forced shut-down) or due to an error handling a specific method, i.e. an exception. When a close is due to an exception, the sender provides ...
def exchange_delete(self, exchange, if_unused=False, nowait=False, ticket=None): args = AMQPWriter() if ticket is not None: args.write_short(ticket) else: args.write_short(self.default_ticket) args.write_shortstr(exchange) args.write_bit(i...
delete an exchange This method deletes an exchange. When an exchange is deleted all queue bindings on the exchange are cancelled. PARAMETERS: exchange: shortstr RULE: The exchange MUST exist. Attempting to delete a non-exis...
def _queue_declare_ok(self, args): queue = args.read_shortstr() message_count = args.read_long() consumer_count = args.read_long() return queue, message_count, consumer_count
confirms a queue definition This method confirms a Declare method and confirms the name of the queue, essential for automatically-named queues. PARAMETERS: queue: shortstr Reports the name of the queue. If the server generated a queue name, this fie...
def basic_get(self, queue='', no_ack=False, ticket=None): args = AMQPWriter() if ticket is not None: args.write_short(ticket) else: args.write_short(self.default_ticket) args.write_shortstr(queue) args.write_bit(no_ack) self._send_method((...
direct access to a queue This method provides a direct access to the messages in a queue using a synchronous dialogue that is designed for specific types of application where synchronous functionality is more important than performance. PARAMETERS: queue: shortstr ...
def _basic_return(self, args, msg): reply_code = args.read_short() reply_text = args.read_shortstr() exchange = args.read_shortstr() routing_key = args.read_shortstr() self.returned_messages.put( (reply_code, reply_text, exchange, routing_key, msg) ...
return a failed message This method returns an undeliverable message that was published with the "immediate" flag set, or an unroutable message published with the "mandatory" flag set. The reply code and text provide information about the reason that the message was undeliverabl...
def _wait_method(self, channel_id, allowed_methods): # # Check the channel's deferred methods # method_queue = self.channels[channel_id].method_queue for queued_method in method_queue: method_sig = queued_method[0] if (allowed_methods is None) \ ...
Wait for a method from the server destined for a particular channel.
def channel(self, channel_id=None): if channel_id in self.channels: return self.channels[channel_id] return Channel(self, channel_id)
Fetch a Channel object identified by the numeric channel_id, or create that object if it doesn't already exist.
def _close(self, args): reply_code = args.read_short() reply_text = args.read_shortstr() class_id = args.read_short() method_id = args.read_short() self._x_close_ok() raise AMQPConnectionException(reply_code, reply_text, (class_id, method_id))
request a connection close This method indicates that the sender wants to close the connection. This may be due to internal conditions (e.g. a forced shut-down) or due to an error handling a specific method, i.e. an exception. When a close is due to an exception, the sender pro...
def _x_open(self, virtual_host, capabilities='', insist=False): args = AMQPWriter() args.write_shortstr(virtual_host) args.write_shortstr(capabilities) args.write_bit(insist) self._send_method((10, 40), args) return self.wait(allowed_methods=[ ...
open connection to virtual host This method opens a connection to a virtual host, which is a collection of resources, and acts to separate multiple application domains within a server. RULE: The client MUST open the context before doing any work on the connecti...
def _open_ok(self, args): self.known_hosts = args.read_shortstr() AMQP_LOGGER.debug('Open OK! known_hosts [%s]' % self.known_hosts) return None
signal that the connection is ready This method signals to the client that the connection is ready for use. PARAMETERS: known_hosts: shortstr
def _redirect(self, args): host = args.read_shortstr() self.known_hosts = args.read_shortstr() AMQP_LOGGER.debug('Redirected to [%s], known_hosts [%s]' % (host, self.known_hosts)) return host
asks the client to use a different server This method redirects the client to another server, based on the requested virtual host and/or capabilities. RULE: When getting the Connection.Redirect method, the client SHOULD reconnect to the host specified, and if that host...
def _start(self, args): self.version_major = args.read_octet() self.version_minor = args.read_octet() self.server_properties = args.read_table() self.mechanisms = args.read_longstr().split(' ') self.locales = args.read_longstr().split(' ') AMQP_LOGGER.debug('Sta...
start connection negotiation This method starts the connection negotiation process by telling the client the protocol version that the server proposes, along with a list of security mechanisms which the client can use for authentication. RULE: If the client cannot ...
def _x_start_ok(self, client_properties, mechanism, response, locale): args = AMQPWriter() args.write_table(client_properties) args.write_shortstr(mechanism) args.write_longstr(response) args.write_shortstr(locale) self._send_method((10, 11), args)
select security mechanism and locale This method selects a SASL security mechanism. ASL uses SASL (RFC2222) to negotiate authentication and encryption. PARAMETERS: client_properties: table client properties mechanism: shortstr selected...
def _tune(self, args): self.channel_max = args.read_short() or self.channel_max self.frame_max = args.read_long() or self.frame_max self.method_writer.frame_max = self.frame_max self.heartbeat = args.read_short() self._x_tune_ok(self.channel_max, self.frame_max, 0)
propose connection tuning parameters This method proposes a set of connection configuration values to the client. The client can accept and/or adjust these. PARAMETERS: channel_max: short proposed maximum channels The maximum total number of chann...
def _send_method(self, method_sig, args=bytes(), content=None): if isinstance(args, AMQPWriter): args = args.getvalue() self.connection.method_writer.write_method(self.channel_id, method_sig, args, content)
Send a method for our channel.
def read_frame(self): frame_type, channel, size = unpack('>BHI', self._read(7)) payload = self._read(size) ch = ord(self._read(1)) if ch == 206: # '\xce' return frame_type, channel, payload else: raise Exception('Framing Error, received 0x%02x whi...
Read an AMQP frame.
def write_frame(self, frame_type, channel, payload): size = len(payload) self._write(pack('>BHI%dsB' % size, frame_type, channel, size, payload, 0xce))
Write out an AMQP frame.
def _setup_transport(self): if HAVE_PY26_SSL: if hasattr(self, 'sslopts'): self.sslobj = ssl.wrap_socket(self.sock, **self.sslopts) else: self.sslobj = ssl.wrap_socket(self.sock) self.sslobj.do_handshake() else: sel...
Wrap the socket in an SSL object, either the new Python 2.6 version, or the older Python 2.5 and lower version.
def _shutdown_transport(self): if HAVE_PY26_SSL and (self.sslobj is not None): self.sock = self.sslobj.unwrap() self.sslobj = None
Unwrap a Python 2.6 SSL socket, so we can call shutdown()
def _read(self, n): result = self.sslobj.read(n) while len(result) < n: s = self.sslobj.read(n - len(result)) if not s: raise IOError('Socket closed') result += s return result
It seems that SSL Objects read() method may not supply as much as you're asking for, at least with extremely large messages. somewhere > 16K - found this in the test_channel.py test_large unittest.
def _write(self, s): while s: n = self.sslobj.write(s) if not n: raise IOError('Socket closed') s = s[n:]
Write a string out to the SSL socket fully.
def _setup_transport(self): self._write = self.sock.sendall self._read_buffer = bytes()
Setup to _write() directly to the socket, and do our own buffered reads.
def _read(self, n): while len(self._read_buffer) < n: s = self.sock.recv(65536) if not s: raise IOError('Socket closed') self._read_buffer += s result = self._read_buffer[:n] self._read_buffer = self._read_buffer[n:] return r...
Read exactly n bytes from the socket
def read_table(self): self.bitcount = self.bits = 0 tlen = unpack('>I', self.input.read(4))[0] table_data = AMQPReader(self.input.read(tlen)) result = {} while table_data.input.tell() < tlen: name = table_data.read_shortstr() ftype = ord(table_dat...
Read an AMQP table, and return as a Python dictionary.
def write_bit(self, b): if b: b = 1 else: b = 0 shift = self.bitcount % 8 if shift == 0: self.bits.append(0) self.bits[-1] |= (b << shift) self.bitcount += 1
Write a boolean value.
def write_octet(self, n): if (n < 0) or (n > 255): raise ValueError('Octet out of range 0..255') self._flushbits() self.out.write(pack('B', n))
Write an integer as an unsigned 8-bit value.
def write_short(self, n): if (n < 0) or (n > 65535): raise ValueError('Octet out of range 0..65535') self._flushbits() self.out.write(pack('>H', n))
Write an integer as an unsigned 16-bit value.
def write_long(self, n): if (n < 0) or (n >= (2**32)): raise ValueError('Octet out of range 0..2**31-1') self._flushbits() self.out.write(pack('>I', n))
Write an integer as an unsigned2 32-bit value.
def write_longlong(self, n): if (n < 0) or (n >= (2**64)): raise ValueError('Octet out of range 0..2**64-1') self._flushbits() self.out.write(pack('>Q', n))
Write an integer as an unsigned 64-bit value.