本文整理汇总了Python中twisted.python.compat.unicode函数的典型用法代码示例。如果您正苦于以下问题:Python unicode函数的具体用法?Python unicode怎么用?Python unicode使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了unicode函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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
示例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))
示例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()
示例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))
示例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)
示例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))
示例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)
示例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)
示例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
示例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)
示例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,
}
示例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)
示例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))
)
示例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))
示例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))