• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python xmlstream.ET类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中sleekxmpp.xmlstream.ET的典型用法代码示例。如果您正苦于以下问题:Python ET类的具体用法?Python ET怎么用?Python ET使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了ET类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: open_selected_item

    def open_selected_item(self):
        """
        displays the currently selected item in the item view window
        """
        selected_item = self.get_item_by_id(self.get_selected_item_id())
        if not selected_item:
            return
        log.debug('Content: %s'%ET.tostring(selected_item.content))
        entry = atom_parser.parse_atom_entry(selected_item.content)
        if not entry:
            self.item_viewer._text = str(ET.tostring(selected_item.content))
        else:
            self.item_viewer._text = \
"""\x193Title:\x19o %(title)s
\x193Author:\x19o %(author_name)s (%(author_uri)s)
%(dates)s\x193Link:\x19o %(link)s

\x193Summary:\x19o
%(summary)s
""" % {'title': entry.get('title') or '',
       'author_name': entry['author'].get('name') or '',
       'author_uri': entry['author'].get('uri') or '',
       'link': entry.get('link_href') or '',
       'summary': entry.get('summary') or '',
       'dates': '\x193Published:\x19o %(published)s\n%(updated)s' % {'published':entry.get('published') or '',
                                                                'updated': '' if (entry.get('updated') is None) or (entry.get('published') == entry.get('updated')) else '\x193Published:\x19o %s\n' % entry.get('updated')}
       }
        self.item_viewer.rebuild_text()
        return True
开发者ID:adamkijak,项目名称:poezio,代码行数:29,代码来源:pubsub.py


示例2: testGetItems

 def testGetItems(self):
     """Test retrieving items from a roster stanza."""
     xml_string = """
       <iq>
         <query xmlns="jabber:iq:roster">
           <item jid="[email protected]" name="User" subscription="both">
             <group>Friends</group>
             <group>Coworkers</group>
           </item>
           <item jid="[email protected]" name="Other User"
                 subscription="both" />
         </query>
       </iq>
     """
     iq = self.Iq(ET.fromstring(xml_string))
     expected = {
         "[email protected]": {
             "name": "User",
             "subscription": "both",
             "ask": "",
             "approved": "",
             "groups": ["Friends", "Coworkers"],
         },
         "[email protected]": {
             "name": "Other User",
             "subscription": "both",
             "ask": "",
             "approved": "",
             "groups": [],
         },
     }
     debug = "Roster items don't match after retrieval."
     debug += "\nReturned: %s" % str(iq["roster"]["items"])
     debug += "\nExpected: %s" % str(expected)
     self.failUnless(iq["roster"]["items"] == expected, debug)
开发者ID:NickBMetaswitch,项目名称:SleekXMPP,代码行数:35,代码来源:test_stanza_roster.py


示例3: broadcast

    def broadcast(self, payload):
        """ Broadcasts via XMPP the payload. The payload can be a list
        of Item or a single item.
        """

        # Transforms all Item objects to a single XML string
        xmls = ""
        if isinstance(payload, dict):
            xmls = payload.to_xml()
        elif isinstance(payload, list):
            for elem in payload:
                xmls += elem.to_xml()

        # Transforms the XML string to a valid sleekxmpp XML element
        xml_element = ET.fromstring(xmls)

        try:
            result = self.pubsub.publish(self.config.server_host,
                                         self.config.node_name,
                                         payload=xml_element)
            id = result['pubsub']['publish']['item']['id']
            self.logger.debug('Published at item id: %s' % id)
        except:
            self.logger.error('Could not publish to: %s' %
                              self.config.node_name)
开发者ID:raphdg,项目名称:baboon,代码行数:25,代码来源:transport.py


示例4: publish

 def publish(self, node, data):
     payload = ET.fromstring("<test xmlns='test'>{}</test>".format(data))
     try:
         self['xep_0060'].publish(self.pubsub_server, node, payload=payload)
     except Exception as e:
         log.error('pubsub: could not publish to: {}'.format(node))
         log.error('Exception "{}" of type {}'.format(e, type(e)))
开发者ID:Murodese,项目名称:pynab,代码行数:7,代码来源:xmpp.py


示例5: publish

 def publish(self):
     payload = ET.fromstring("<test xmlns='test'>%s</test>" % self.data)
     try:
         result = self["xep_0060"].publish(self.pubsub_server, self.node, payload=payload)
         id = result["pubsub"]["publish"]["item"]["id"]
         print("Published at item id: %s" % id)
     except:
         logging.error("Could not publish to: %s" % self.node)
开发者ID:hoangduit,项目名称:emesene,代码行数:8,代码来源:pubsub_client.py


示例6: publish

    def publish(self, event, radius):
        from events.api.resources.jabber import EventResource

        resource = EventResource()
        event_dict = resource.full_dehydrate(resource.build_bundle(obj=event))
        event_dict.data['radius'] = radius
        str_payload = resource.serialize(None, event_dict, 'application/xml')
        payload = ET.fromstring(str_payload)

        if logger.level is logging.DEBUG:
            lxml_payload = etree.fromstring(ET.tostring(payload))
            str_payload = etree.tostring(lxml_payload, pretty_print=True)
            logger.debug('sending publish message with payload:\n%s', str_payload)

        self._pubsub.publish(self.config.pubsub_server,
                             self.config.node_name,
                             payload=payload)
开发者ID:42cc,项目名称:p2psafety,代码行数:17,代码来源:clients.py


示例7: testMailBox

    def testMailBox(self):
        """Testing reading from Gmail mailbox result"""

        # Use the example from Google's documentation at
        # http://code.google.com/apis/talk/jep_extensions/gmail.html#notifications
        xml = ET.fromstring("""
          <iq type="result">
            <mailbox xmlns="google:mail:notify"
                     result-time='1118012394209'
                     url='http://mail.google.com/mail'
                     total-matched='95'
                     total-estimate='0'>
              <mail-thread-info tid='1172320964060972012'
                                participation='1'
                                messages='28'
                                date='1118012394209'
                                url='http://mail.google.com/mail?view=cv'>
                <senders>
                  <sender name='Me' address='[email protected]' originator='1' />
                  <sender name='Benvolio' address='[email protected]' />
                  <sender name='Mercutio' address='[email protected]' unread='1'/>
                </senders>
                <labels>act1scene3</labels>
                <subject>Put thy rapier up.</subject>
                <snippet>Ay, ay, a scratch, a scratch; marry, 'tis enough.</snippet>
              </mail-thread-info>
            </mailbox>
          </iq>
        """)

        iq = self.Iq(xml=xml)
        mailbox = iq['mailbox']
        self.failUnless(mailbox['result-time'] == '1118012394209', "result-time doesn't match")
        self.failUnless(mailbox['url'] == 'http://mail.google.com/mail', "url doesn't match")
        self.failUnless(mailbox['matched'] == '95', "total-matched incorrect")
        self.failUnless(mailbox['estimate'] == False, "total-estimate incorrect")
        self.failUnless(len(mailbox['threads']) == 1, "could not extract message threads")

        thread = mailbox['threads'][0]
        self.failUnless(thread['tid'] == '1172320964060972012', "thread tid doesn't match")
        self.failUnless(thread['participation'] == '1', "thread participation incorrect")
        self.failUnless(thread['messages'] == '28', "thread message count incorrect")
        self.failUnless(thread['date'] == '1118012394209', "thread date doesn't match")
        self.failUnless(thread['url'] == 'http://mail.google.com/mail?view=cv', "thread url doesn't match")
        self.failUnless(thread['labels'] == 'act1scene3', "thread labels incorrect")
        self.failUnless(thread['subject'] == 'Put thy rapier up.', "thread subject doesn't match")
        self.failUnless(thread['snippet'] == "Ay, ay, a scratch, a scratch; marry, 'tis enough.", "snippet doesn't match")
        self.failUnless(len(thread['senders']) == 3, "could not extract senders")

        sender1 = thread['senders'][0]
        self.failUnless(sender1['name'] == 'Me', "sender name doesn't match")
        self.failUnless(sender1['address'] == '[email protected]', "sender address doesn't match")
        self.failUnless(sender1['originator'] == True, "sender originator incorrect")
        self.failUnless(sender1['unread'] == False, "sender unread incorrectly True")

        sender2 = thread['senders'][2]
        self.failUnless(sender2['unread'] == True, "sender unread incorrectly False")
开发者ID:2M1R,项目名称:SleekXMPP,代码行数:57,代码来源:test_stanza_gmail.py


示例8: testGetFirstIndex

 def testGetFirstIndex(self):
     xml_string = """
       <set xmlns="http://jabber.org/protocol/rsm">
         <first index="10">id</first>
       </set>
     """
     s = Set(ET.fromstring(xml_string))
     expected = '10'
     self.failUnless(s['first_index'] == expected)
开发者ID:2M1R,项目名称:SleekXMPP,代码行数:9,代码来源:test_stanza_xep_0059.py


示例9: set_body

 def set_body(self, content, lang=None):
     if lang is None:
         lang = self.get_lang()
     self.del_body(lang)
     if lang == '*':
         for sublang, subcontent in content.items():
             self.set_body(subcontent, sublang)
     else:
         if isinstance(content, type(ET.Element('test'))):
             content = ET.tostring(content)
         else:
             content = str(content)
         header = '<body xmlns="%s"' % XHTML_NS
         if lang:
             header = '%s xml:lang="%s"' % (header, lang)
         content = '%s>%s</body>' % (header, content)
         xhtml = ET.fromstring(content)
         self.xml.append(xhtml)
开发者ID:guluc3m,项目名称:gul-zoe-dependencies,代码行数:18,代码来源:stanza.py


示例10: testGetBeforeVal

 def testGetBeforeVal(self):
     xml_string = """
       <set xmlns="http://jabber.org/protocol/rsm">
         <before>id</before>
       </set>
     """
     s = Set(ET.fromstring(xml_string))
     expected = 'id'
     self.failUnless(s['before'] == expected)
开发者ID:2M1R,项目名称:SleekXMPP,代码行数:9,代码来源:test_stanza_xep_0059.py


示例11: set_nick

   def set_nick(self, nick):
      # set bla baaasa
      vcard = ET.fromstring("""
<vCard xmlns="vcard-temp">
   <FN>Dr. Mundo</FN>
   <NICKNAME>Pussy Boy</NICKNAME>
</vCard>
      """)
      self['xep_0054'].publish_vcard(vcard)
开发者ID:ksergey,项目名称:playground,代码行数:9,代码来源:pussy_bot0.py


示例12: load_ballot

    def load_ballot(self, name, quorum):
        self.quorum = quorum
        self.current_ballot = name

        with open('%s/ballot_%s.xml' % (self.data_dir, name)) as ballot_file:
            self._ballot_data = Ballot(xml=ET.fromstring(ballot_file.read()))
        try:
            os.makedirs('%s/results/%s' % (self.data_dir, name))
        except:
            pass
开发者ID:joachimlindborg,项目名称:memberbot,代码行数:10,代码来源:voting.py


示例13: get_xhtml

	def get_xhtml(self, element=True):
		xhtml = ET.XML(markdown_to_xhtml(self.text))
		if self.font:
			span = ET.Element('span')
			span.set('style', 'font-family: ' + self.font + ';')
			span.append(xhtml)
			xhtml = span
		if element:
			return xhtml
		return ET.tostring(xhtml)
开发者ID:jamcut,项目名称:cassie-bot,代码行数:10,代码来源:imcontent.py


示例14: load_config

def load_config(filename):
    """
    Create a configuration stanza object from
    the given file's contents.

    Arguments:
        filename -- Name of the config file.
    """
    with open(filename, 'r+') as conf_file:
        data = "\n".join([line for line in conf_file])
        config = Config(xml=ET.fromstring(data))
        return config
开发者ID:legastero,项目名称:Weld,代码行数:12,代码来源:config.py


示例15: testDelFirstIndex

 def testDelFirstIndex(self):
     xml_string = """
       <set xmlns="http://jabber.org/protocol/rsm">
         <first index="10">id</first>
       </set>
     """
     s = Set(ET.fromstring(xml_string))
     del s['first_index']
     self.check(s, """
       <set xmlns="http://jabber.org/protocol/rsm">
         <first>id</first>
       </set>
     """)
开发者ID:2M1R,项目名称:SleekXMPP,代码行数:13,代码来源:test_stanza_xep_0059.py


示例16: set_task

    def set_task(self, task_id, tags, task):
        """ Publish task to teammates """
        payload = ET.fromstring(task)

        for node, project_tag in self._nodes.items():
            if project_tag in tags:
                self['xep_0060'].publish(self._pubsub, node, id=task_id,
                        payload=payload)
            else:
                # Has this node still this task?
                item_req = self['xep_0060'].get_item(self._pubsub, node,
                            task_id)
                items = item_req['pubsub']['items']['substanzas']
                if len(items) > 0:
                    self['xep_0060'].retract(self._pubsub, node, task_id)
开发者ID:lefred,项目名称:backend_gtgonline,代码行数:15,代码来源:backend_pubsub.py


示例17: alert

    def alert(self, msg):
        """ Broadcast the msg on the pubsub node (written in the
        config file).
        """

        xml_element = ET.fromstring('<status>%s</status>' % msg)

        try:
            result = self.pubsub.publish(self.config.pubsub,
                                         self.config.node,
                                         payload=xml_element)
            id = result['pubsub']['publish']['item']['id']
            print('Published at item id: %s' % id)
        except:
            print('Could not publish to: %s' %
                  'Baboon')
开发者ID:PiWhy,项目名称:baboon,代码行数:16,代码来源:alert.py


示例18: parse_xml

    def parse_xml(self, xml_string):
        try:
            xml = ET.fromstring(xml_string)
            return xml
        except SyntaxError as e:
            if 'unbound' in e.msg:
                known_prefixes = {
                        'stream': 'http://etherx.jabber.org/streams'}

                prefix = xml_string.split('<')[1].split(':')[0]
                if prefix in known_prefixes:
                    xml_string = '<fixns xmlns:%s="%s">%s</fixns>' % (
                            prefix,
                            known_prefixes[prefix],
                            xml_string)
                xml = self.parse_xml(xml_string)
                xml = xml.getchildren()[0]
                return xml
开发者ID:EnerNOC,项目名称:smallfoot-sleekxmpp,代码行数:18,代码来源:sleektest.py


示例19: assertXMLEqual

def assertXMLEqual(a, b):
    """
    Asserts that both xmls should be syntactically valid and equal.
    Prints human-readable xml on `AssertionError`.
    """
    args = [a, b]
    parser = etree.XMLParser(remove_blank_text=True)
    for i, _ in enumerate(args):
        if isinstance(args[i], basestring):
            args[i] = etree.XML(args[i], parser=parser)
        elif isinstance(args[i], etree._Element):
            pass
        else:
            args[i] = etree.fromstring(ET.tostring(args[i]))

        args[i] = etree.tostring(args[i], pretty_print=True)

    assert_message = ('XMLs are not equal:\n'
                      '{2}\n{0}{2}\n{1}'
                      .format(args[0], args[1],  '-' * 70))
    assert (args[0] == args[1]), assert_message
开发者ID:42cc,项目名称:p2psafety,代码行数:21,代码来源:helpers.py


示例20: testInvalidBase64Alphabet

    def testInvalidBase64Alphabet(self):
        """
        Test detecting invalid base64 data with characters
        outside of the base64 alphabet.
        """
        iq = Iq(xml=ET.fromstring("""
          <iq type="set" id="0" to="[email protected]">
            <data xmlns="http://jabber.org/protocol/ibb" seq="0">
              ABCD?EFGH
            </data>
          </iq>
        """))

        errored = False

        try:
            data = iq['ibb_data']['data']
        except XMPPError:
            errored = True

        self.assertTrue(errored, "ABCD?EFGH did not raise base64 error")
开发者ID:2M1R,项目名称:SleekXMPP,代码行数:21,代码来源:test_stanza_xep_0047.py



注:本文中的sleekxmpp.xmlstream.ET类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python xmlstream.ElementBase类代码示例发布时间:2022-05-27
下一篇:
Python xmlstream.register_stanza_plugin函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap