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

Python compat.unicode函数代码示例

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

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



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

示例1: fromXml

    def fromXml(self, element):
        """
        Get a Tune instance from an XML representation.

        This class method parses the given XML document into a L{Tune}
        instances.

        @param element: The XML tune document.
        @type element: object providing
                       L{IElement<twisted.words.xish.domish.IElement>}
        @return: A L{Tune} instance or C{None} if C{element} was not a tune
                 document.
        """
        if element.uri != NS_TUNE or element.name != 'tune':
            return None

        tune = Tune()

        for child in element.elements():
            if child.uri != NS_TUNE:
                continue

            if child.name in ('artist', 'source', 'title', 'track', 'uri'):
                setattr(tune, child.name, unicode(child))
            elif child.name == 'length':
                try:
                    tune.length = int(unicode(child))
                except ValueError:
                    pass

        return tune
开发者ID:ralphm,项目名称:wokkel,代码行数:31,代码来源:formats.py


示例2: test_availableLanguages

    def test_availableLanguages(self):
        """
        It should be possible to pass a sender address.
        """
        self.protocol.available(JID('[email protected]'),
                                show=u'chat',
                                statuses={None: u'Talk to me!',
                                          'nl': u'Praat met me!'},
                                priority=50)
        element = self.output[-1]
        self.assertEquals("[email protected]", element.getAttribute('to'))
        self.assertIdentical(None, element.getAttribute('type'))
        self.assertEquals(u'chat', unicode(element.show))

        statuses = {}
        for status in element.elements():
            if status.name == 'status':
                lang = status.getAttribute((NS_XML, 'lang'))
                statuses[lang] = unicode(status)

        self.assertIn(None, statuses)
        self.assertEquals(u'Talk to me!', statuses[None])
        self.assertIn('nl', statuses)
        self.assertEquals(u'Praat met me!', statuses['nl'])
        self.assertEquals(u'50', unicode(element.priority))
开发者ID:ralphm,项目名称:wokkel,代码行数:25,代码来源:test_xmppim.py


示例3: authenticate

    def authenticate(self, database_name, username, password, mechanism):
        database_name = str(database_name)
        username = unicode(username)
        password = unicode(password)

        yield self.__auth_lock.acquire()

        try:
            if mechanism == "MONGODB-CR":
                auth_func = self.authenticate_mongo_cr
            elif mechanism == "SCRAM-SHA-1":
                auth_func = self.authenticate_scram_sha1
            elif mechanism == "DEFAULT":
                if self.max_wire_version >= 3:
                    auth_func = self.authenticate_scram_sha1
                else:
                    auth_func = self.authenticate_mongo_cr
            else:
                raise MongoAuthenticationError(
                    "Unknown authentication mechanism: {0}".format(mechanism))

            result = yield auth_func(database_name, username, password)
            defer.returnValue(result)
        finally:
            self.__auth_lock.release()
开发者ID:deconevidya,项目名称:txmongo,代码行数:25,代码来源:protocol.py


示例4: test_observeWrites

 def test_observeWrites(self):
     """
     L{FileLogObserver} writes to the given file when it observes events.
     """
     with StringIO() as fileHandle:
         observer = FileLogObserver(fileHandle, lambda e: unicode(e))
         event = dict(x=1)
         observer(event)
         self.assertEqual(fileHandle.getvalue(), unicode(event))
开发者ID:dansgithubuser,项目名称:constructicon,代码行数:9,代码来源:test_file.py


示例5: onAuthSet

        def onAuthSet(iq):
            """
            Called when the initializer sent the authentication request.

            The server checks the credentials and responds with an empty result
            signalling success.
            """
            self.assertEqual("user", unicode(iq.query.username))
            self.assertEqual(sha1(b"12345secret").hexdigest(), unicode(iq.query.digest))
            self.assertEqual("resource", unicode(iq.query.resource))

            # Send server response
            response = xmlstream.toResponse(iq, "result")
            self.pipe.source.send(response)
开发者ID:alfonsjose,项目名称:international-orders-app,代码行数:14,代码来源:test_jabberclient.py


示例6: test_available

 def test_available(self):
     """
     It should be possible to pass a sender address.
     """
     self.protocol.available(JID('[email protected]'),
                             show=u'chat',
                             status=u'Talk to me!',
                             priority=50)
     element = self.output[-1]
     self.assertEquals("[email protected]", element.getAttribute('to'))
     self.assertIdentical(None, element.getAttribute('type'))
     self.assertEquals(u'chat', unicode(element.show))
     self.assertEquals(u'Talk to me!', unicode(element.status))
     self.assertEquals(u'50', unicode(element.priority))
开发者ID:ralphm,项目名称:wokkel,代码行数:14,代码来源:test_xmppim.py


示例7: _onPresenceAvailable

    def _onPresenceAvailable(self, presence):
        entity = JID(presence["from"])

        show = unicode(presence.show or '')
        if show not in ['away', 'xa', 'chat', 'dnd']:
            show = None

        statuses = self._getStatuses(presence)

        try:
            priority = int(unicode(presence.priority or '')) or 0
        except ValueError:
            priority = 0

        self.availableReceived(entity, show, statuses, priority)
开发者ID:ralphm,项目名称:wokkel,代码行数:15,代码来源:xmppim.py


示例8: _childParser_mucUser

    def _childParser_mucUser(self, element):
        """
        Parse the MUC user extension element.
        """
        for child in element.elements():
            if child.uri != NS_MUC_USER:
                continue

            elif child.name == 'status':
                try:
                    value = int(child.getAttribute('code'))
                    statusCode = STATUS_CODE.lookupByValue(value)
                except (TypeError, ValueError):
                    continue

                self.mucStatuses.add(statusCode)

            elif child.name == 'item':
                if child.hasAttribute('jid'):
                    self.entity = jid.JID(child['jid'])

                self.nick = child.getAttribute('nick')
                self.affiliation = child.getAttribute('affiliation')
                self.role = child.getAttribute('role')

                for reason in child.elements(NS_MUC_ADMIN, 'reason'):
                    self.reason = unicode(reason)
开发者ID:ralphm,项目名称:wokkel,代码行数:27,代码来源:muc.py


示例9: onResult

    def onResult(self, result):
        def reply(validity):
            reply = domish.Element((NS_DIALBACK, 'result'))
            reply['from'] = result['to']
            reply['to'] = result['from']
            reply['type'] = validity
            self.xmlstream.send(reply)

        def valid(xs):
            reply('valid')
            if not self.xmlstream.thisEntity:
                self.xmlstream.thisEntity = jid.internJID(receivingServer)
            self.xmlstream.otherEntity = jid.internJID(originatingServer)
            self.xmlstream.dispatch(self.xmlstream,
                                    xmlstream.STREAM_AUTHD_EVENT)

        def invalid(failure):
            log.err(failure)
            reply('invalid')

        receivingServer = result['to']
        originatingServer = result['from']
        key = unicode(result)

        d = self.service.validateConnection(receivingServer, originatingServer,
                                            self.xmlstream.sid, key)
        d.addCallbacks(valid, invalid)
        return d
开发者ID:ralphm,项目名称:wokkel,代码行数:28,代码来源:server.py


示例10: onVerify

    def onVerify(self, verify):
        try:
            receivingServer = jid.JID(verify['from']).host
            originatingServer = jid.JID(verify['to']).host
        except (KeyError, jid.InvalidFormat):
            raise error.StreamError('improper-addressing')

        if originatingServer not in self.service.domains:
            raise error.StreamError('host-unknown')

        if (self.xmlstream.otherEntity and
            receivingServer != self.xmlstream.otherEntity.host):
            raise error.StreamError('invalid-from')

        streamID = verify.getAttribute('id', '')
        key = unicode(verify)

        calculatedKey = generateKey(self.service.secret, receivingServer,
                                    originatingServer, streamID)
        validity = (key == calculatedKey) and 'valid' or 'invalid'

        reply = domish.Element((NS_DIALBACK, 'verify'))
        reply['from'] = originatingServer
        reply['to'] = receivingServer
        reply['id'] = streamID
        reply['type'] = validity
        self.xmlstream.send(reply)
开发者ID:ralphm,项目名称:wokkel,代码行数:27,代码来源:server.py


示例11: _parseError

def _parseError(error, errorNamespace):
    """
    Parses an error element.

    @param error: The error element to be parsed
    @type error: L{domish.Element}
    @param errorNamespace: The namespace of the elements that hold the error
                           condition and text.
    @type errorNamespace: C{str}
    @return: Dictionary with extracted error information. If present, keys
             C{condition}, C{text}, C{textLang} have a string value,
             and C{appCondition} has an L{domish.Element} value.
    @rtype: C{dict}
    """
    condition = None
    text = None
    textLang = None
    appCondition = None

    for element in error.elements():
        if element.uri == errorNamespace:
            if element.name == 'text':
                text = unicode(element)
                textLang = element.getAttribute((NS_XML, 'lang'))
            else:
                condition = element.name
        else:
            appCondition = element

    return {
        'condition': condition,
        'text': text,
        'textLang': textLang,
        'appCondition': appCondition,
    }
开发者ID:JohnDoes95,项目名称:project_parser,代码行数:35,代码来源:error.py


示例12: fromElement

    def fromElement(element):
        valueElements = list(domish.generateElementsQNamed(element.children, "value", NS_X_DATA))
        if not valueElements:
            raise Error("Option has no value")

        label = element.getAttribute("label")
        return Option(unicode(valueElements[0]), label)
开发者ID:ralphm,项目名称:wokkel,代码行数:7,代码来源:data_form.py


示例13: formatWithCall

def formatWithCall(formatString, mapping):
    """
    Format a string like L{unicode.format}, but:

        - taking only a name mapping; no positional arguments

        - with the additional syntax that an empty set of parentheses
          correspond to a formatting item that should be called, and its result
          C{str}'d, rather than calling C{str} on the element directly as
          normal.

    For example::

        >>> formatWithCall("{string}, {function()}.",
        ...                dict(string="just a string",
        ...                     function=lambda: "a function"))
        'just a string, a function.'

    @param formatString: A PEP-3101 format string.
    @type formatString: L{unicode}

    @param mapping: A L{dict}-like object to format.

    @return: The string with formatted values interpolated.
    @rtype: L{unicode}
    """
    return unicode(
        aFormatter.vformat(formatString, (), CallMapping(mapping))
    )
开发者ID:JohnDoes95,项目名称:project_parser,代码行数:29,代码来源:_format.py


示例14: formatTime

def formatTime(when, timeFormat=timeFormatRFC3339, default=u"-"):
    """
    Format a timestamp as text.

    Example::

        >>> from time import time
        >>> from twisted.logger import formatTime
        >>>
        >>> t = time()
        >>> formatTime(t)
        u'2013-10-22T14:19:11-0700'
        >>> formatTime(t, timeFormat="%Y/%W")  # Year and week number
        u'2013/42'
        >>>

    @param when: A timestamp.
    @type then: L{float}

    @param timeFormat: A time format.
    @type timeFormat: L{unicode} or L{None}

    @param default: Text to return if C{when} or C{timeFormat} is L{None}.
    @type default: L{unicode}

    @return: A formatted time.
    @rtype: L{unicode}
    """
    if (timeFormat is None or when is None):
        return default
    else:
        tz = FixedOffsetTimeZone.fromLocalTimeStamp(when)
        datetime = DateTime.fromtimestamp(when, tz)
        return unicode(datetime.strftime(timeFormat))
开发者ID:JohnDoes95,项目名称:project_parser,代码行数:34,代码来源:_format.py


示例15: test_addElementContent

 def test_addElementContent(self):
     """
     Content passed to addElement becomes character data on the new child.
     """
     element = domish.Element((u"testns", u"foo"))
     child = element.addElement("bar", content=u"abc")
     self.assertEqual(u"abc", unicode(child))
开发者ID:alfonsjose,项目名称:international-orders-app,代码行数:7,代码来源:test_domish.py


示例16: test_addContentNativeStringASCII

 def test_addContentNativeStringASCII(self):
     """
     ASCII native strings passed to C{addContent} become the character data.
     """
     element = domish.Element((u"testns", u"foo"))
     element.addContent("native")
     self.assertEqual(u"native", unicode(element))
开发者ID:alfonsjose,项目名称:international-orders-app,代码行数:7,代码来源:test_domish.py


示例17: test_addContent

 def test_addContent(self):
     """
     Unicode strings passed to C{addContent} become the character data.
     """
     element = domish.Element((u"testns", u"foo"))
     element.addContent(u"unicode")
     self.assertEqual(u"unicode", unicode(element))
开发者ID:alfonsjose,项目名称:international-orders-app,代码行数:7,代码来源:test_domish.py


示例18: test_toElementBooleanTextSingle

 def test_toElementBooleanTextSingle(self):
     """
     A boolean value should render to text if the field type is text-single.
     """
     field = data_form.Field(var='test', value=True)
     element = field.toElement()
     self.assertEqual(u'true', unicode(element.value))
开发者ID:ralphm,项目名称:wokkel,代码行数:7,代码来源:test_data_form.py


示例19: test_observeFailureThatRaisesInGetTraceback

    def test_observeFailureThatRaisesInGetTraceback(self):
        """
        If the C{"log_failure"} key exists in an event, and contains an object
        that raises when you call it's C{getTraceback()}, then the observer
        appends a message noting the problem, instead of raising.
        """
        with StringIO() as fileHandle:
            observer = FileLogObserver(fileHandle, lambda e: unicode(e))

            event = dict(log_failure=object())  # object has no getTraceback()
            observer(event)
            output = fileHandle.getvalue()
            expected = (
                "{0}\n(UNABLE TO OBTAIN TRACEBACK FROM EVENT)\n"
                .format(unicode(event))
            )
            self.assertEqual(output, expected)
开发者ID:12019,项目名称:OpenWrt_Luci_Lua,代码行数:17,代码来源:test_file.py


示例20: test_toElementBoolean

 def test_toElementBoolean(self):
     """
     A boolean value should render to text.
     """
     field = data_form.Field(fieldType='boolean', var='test',
                             value=True)
     element = field.toElement()
     self.assertEqual(u'true', unicode(element.value))
开发者ID:ralphm,项目名称:wokkel,代码行数:8,代码来源:test_data_form.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python compat.NativeStringIO类代码示例发布时间:2022-05-27
下一篇:
Python compat.set函数代码示例发布时间: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