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

Python compat.nativeString函数代码示例

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

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



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

示例1: gotHasKey

        def gotHasKey(result):
            if result:
                if not self.hasHostKey(ip, key):
                    ui.warn("Warning: Permanently added the %s host key for "
                            "IP address '%s' to the list of known hosts." %
                            (key.type(), nativeString(ip)))
                    self.addHostKey(ip, key)
                    self.save()
                return result
            else:
                def promptResponse(response):
                    if response:
                        self.addHostKey(hostname, key)
                        self.addHostKey(ip, key)
                        self.save()
                        return response
                    else:
                        raise UserRejectedKey()

                keytype = key.type()

                if keytype is "EC":
                    keytype = "ECDSA"

                prompt = (
                    "The authenticity of host '%s (%s)' "
                    "can't be established.\n"
                    "%s key fingerprint is SHA256:%s.\n"
                    "Are you sure you want to continue connecting (yes/no)? " %
                    (nativeString(hostname), nativeString(ip), keytype,
                     key.fingerprint(format=FingerprintFormats.SHA256_BASE64)))
                proceed = ui.prompt(prompt.encode(sys.getdefaultencoding()))
                return proceed.addCallback(promptResponse)
开发者ID:JohnDoes95,项目名称:project_parser,代码行数:33,代码来源:knownhosts.py


示例2: class_IN

    def class_IN(self, ttl, type, domain, rdata):
        """
        Simulate a class IN and recurse into the actual class.

        @param ttl: time to live for the record
        @type ttl: L{int}

        @param type: record type
        @type type: str

        @param domain: the domain
        @type domain: bytes

        @param rdata:
        @type rdate: bytes
        """
        record = getattr(dns, 'Record_%s' % (nativeString(type),), None)
        if record:
            r = record(*rdata)
            r.ttl = ttl
            self.records.setdefault(domain.lower(), []).append(r)

            if type == 'SOA':
                self.soa = (domain, r)
        else:
            raise NotImplementedError(
                "Record type %r not supported" % (nativeString(type),)
            )
开发者ID:JohnDoes95,项目名称:project_parser,代码行数:28,代码来源:authority.py


示例3: lineReceived

    def lineReceived(self, rawSentence):
        """
        Parses the data from the sentence and validates the checksum.

        @param rawSentence: The NMEA positioning sentence.
        @type rawSentence: C{bytes}
        """
        sentence = rawSentence.strip()

        _validateChecksum(sentence)
        splitSentence = _split(sentence)

        sentenceType = nativeString(splitSentence[0])
        contents = [nativeString(x) for x in splitSentence[1:]]

        try:
            keys = self._SENTENCE_CONTENTS[sentenceType]
        except KeyError:
            raise ValueError("unknown sentence type %s" % sentenceType)

        sentenceData = {"type": sentenceType}
        for key, value in izip(keys, contents):
            if key is not None and value != "":
                sentenceData[key] = value

        sentence = NMEASentence(sentenceData)

        if self._sentenceCallback is not None:
            self._sentenceCallback(sentence)

        self._receiver.sentenceReceived(sentence)
开发者ID:JohnDoes95,项目名称:project_parser,代码行数:31,代码来源:nmea.py


示例4: lineReceived

 def lineReceived(self, line):
     """
     Receive line commands from the server.
     """
     self.resetTimeout()
     token = line.split(b" ", 1)[0]
     # First manage standard commands without space
     cmd = getattr(self, "cmd_" + nativeString(token), None)
     if cmd is not None:
         args = line.split(b" ", 1)[1:]
         if args:
             cmd(args[0])
         else:
             cmd()
     else:
         # Then manage commands with space in it
         line = line.replace(b" ", b"_")
         cmd = getattr(self, "cmd_" + nativeString(line), None)
         if cmd is not None:
             cmd()
         else:
             # Increment/Decrement response
             cmd = self._current.popleft()
             val = int(line)
             cmd.success(val)
     if not self._current:
         # No pending request, remove timeout
         self.setTimeout(None)
开发者ID:JohnDoes95,项目名称:project_parser,代码行数:28,代码来源:memcache.py


示例5: uri

    def uri(self):
        # type: () -> URL
        request = self._request

        # This code borrows from t.w.server.Request._prePathURL.

        if request.isSecure():
            scheme = u"https"
        else:
            scheme = u"http"

        netloc = nativeString(request.getRequestHostname())

        port = request.getHost().port
        if request.isSecure():
            default = 443
        else:
            default = 80
        if port != default:
            netloc += u":{}".format(port)

        path = nativeString(request.uri)
        if path and path[0] == u"/":
            path = path[1:]

        return URL.fromText(u"{}://{}/{}".format(scheme, netloc, path))
开发者ID:notoriousno,项目名称:klein,代码行数:26,代码来源:_request_compat.py


示例6: filenameToModuleName

def filenameToModuleName(fn):
    """
    Convert a name in the filesystem to the name of the Python module it is.

    This is aggressive about getting a module name back from a file; it will
    always return a string.  Aggressive means 'sometimes wrong'; it won't look
    at the Python path or try to do any error checking: don't use this method
    unless you already know that the filename you're talking about is a Python
    module.

    @param fn: A filesystem path to a module or package; C{bytes} on Python 2,
        C{bytes} or C{unicode} on Python 3.

    @return: A hopefully importable module name.
    @rtype: C{str}
    """
    if isinstance(fn, bytes):
        initPy = b"__init__.py"
    else:
        initPy = "__init__.py"
    fullName = os.path.abspath(fn)
    base = os.path.basename(fn)
    if not base:
        # this happens when fn ends with a path separator, just skit it
        base = os.path.basename(fn[:-1])
    modName = nativeString(os.path.splitext(base)[0])
    while 1:
        fullName = os.path.dirname(fullName)
        if os.path.exists(os.path.join(fullName, initPy)):
            modName = "%s.%s" % (
                nativeString(os.path.basename(fullName)),
                nativeString(modName))
        else:
            break
    return modName
开发者ID:geodrinx,项目名称:gearthview,代码行数:35,代码来源:_reflectpy3.py


示例7: test_authInfoInURL

 def test_authInfoInURL(self):
     url = "http://%s:%[email protected]:%d/" % (
         nativeString(self.user), nativeString(self.password), self.port)
     p = xmlrpc.Proxy(networkString(url))
     d = p.callRemote("authinfo")
     d.addCallback(self.assertEqual, [self.user, self.password])
     return d
开发者ID:Architektor,项目名称:PySnip,代码行数:7,代码来源:test_xmlrpc.py


示例8: callRemote

    def callRemote(self, method, *args):
        """
        Call remote XML-RPC C{method} with given arguments.

        @return: a L{defer.Deferred} that will fire with the method response,
            or a failure if the method failed. Generally, the failure type will
            be L{Fault}, but you can also have an C{IndexError} on some buggy
            servers giving empty responses.

            If the deferred is cancelled before the request completes, the
            connection is closed and the deferred will fire with a
            L{defer.CancelledError}.
        """
        def cancel(d):
            factory.deferred = None
            connector.disconnect()
        factory = self.queryFactory(
            self.path, self.host, method, self.user,
            self.password, self.allowNone, args, cancel, self.useDateTime)

        if self.secure:
            from twisted.internet import ssl
            connector = self._reactor.connectSSL(
                nativeString(self.host), self.port or 443,
                factory, ssl.ClientContextFactory(),
                timeout=self.connectTimeout)
        else:
            connector = self._reactor.connectTCP(
                nativeString(self.host), self.port or 80, factory,
                timeout=self.connectTimeout)
        return factory.deferred
开发者ID:JohnDoes95,项目名称:project_parser,代码行数:31,代码来源:xmlrpc.py


示例9: assertNativeString

 def assertNativeString(self, original, expected):
     """
     Raise an exception indicating a failed test if the output of
     C{nativeString(original)} is unequal to the expected string, or is not
     a native string.
     """
     self.assertEqual(nativeString(original), expected)
     self.assertIsInstance(nativeString(original), str)
开发者ID:esabelhaus,项目名称:secret-octo-dubstep,代码行数:8,代码来源:test_compat.py


示例10: _unjelly_function

 def _unjelly_function(self, rest):
     fname = nativeString(rest[0])
     modSplit = fname.split(nativeString('.'))
     modName = nativeString('.').join(modSplit[:-1])
     if not self.taster.isModuleAllowed(modName):
         raise InsecureJelly("Module not allowed: %s" % modName)
     # XXX do I need an isFunctionAllowed?
     function = namedAny(fname)
     return function
开发者ID:JohnDoes95,项目名称:project_parser,代码行数:9,代码来源:jelly.py


示例11: posixGetLinkLocalIPv6Addresses

def posixGetLinkLocalIPv6Addresses():
    """
    Return a list of strings in colon-hex format representing all the link local
    IPv6 addresses available on the system, as reported by I{getifaddrs(3)}.
    """
    retList = []
    for (interface, family, address) in _interfaces():
        interface = nativeString(interface)
        address = nativeString(address)
        if family == socket.AF_INET6 and address.startswith('fe80:'):
            retList.append('%s%%%s' % (address, interface))
    return retList
开发者ID:AlexanderHerlan,项目名称:syncpy,代码行数:12,代码来源:_posixifaces.py


示例12: _ip

def _ip(src, dst, payload):
    """
    Construct an IP datagram with the given source, destination, and
    application payload.

    @param src: The source IPv4 address as a dotted-quad string.
    @type src: L{bytes}

    @param dst: The destination IPv4 address as a dotted-quad string.
    @type dst: L{bytes}

    @param payload: The content of the IP datagram (such as a UDP datagram).
    @type payload: L{bytes}

    @return: An IP datagram header and payload.
    @rtype: L{bytes}
    """
    ipHeader = (
        # Version and header length, 4 bits each
        b'\x45'
        # Differentiated services field
        b'\x00'
        # Total length
        + _H(20 + len(payload))
        + b'\x00\x01\x00\x00\x40\x11'
        # Checksum
        + _H(0)
        # Source address
        + socket.inet_pton(socket.AF_INET, nativeString(src))
        # Destination address
        + socket.inet_pton(socket.AF_INET, nativeString(dst)))

    # Total all of the 16-bit integers in the header
    checksumStep1 = sum(struct.unpack('!10H', ipHeader))
    # Pull off the carry
    carry = checksumStep1 >> 16
    # And add it to what was left over
    checksumStep2 = (checksumStep1 & 0xFFFF) + carry
    # Compute the one's complement sum
    checksumStep3 = checksumStep2 ^ 0xFFFF

    # Reconstruct the IP header including the correct checksum so the platform
    # IP stack, if there is one involved in this test, doesn't drop it on the
    # floor as garbage.
    ipHeader = (
        ipHeader[:10] +
        struct.pack('!H', checksumStep3) +
        ipHeader[12:])

    return ipHeader + payload
开发者ID:JohnDoes95,项目名称:project_parser,代码行数:50,代码来源:testing.py


示例13: gotHasKey

 def gotHasKey(result):
     if result:
         if not self.knownHosts.hasHostKey(ip, key):
             log.msg("Added new %s host key for IP address '%s'." %
                     (key.type(), nativeString(ip)))
             self.knownHosts.addHostKey(ip, key)
             self.knownHosts.save()
         return result
     else:
         log.msg("Added %s host key for IP address '%s'." %
                 (key.type(), nativeString(ip)))
         self.knownHosts.addHostKey(hostname, key)
         self.knownHosts.addHostKey(ip, key)
         self.knownHosts.save()
         return True
开发者ID:calston,项目名称:tensor,代码行数:15,代码来源:ssh.py


示例14: getPassword

 def getPassword(self, prompt = None):
     if prompt:
         prompt = nativeString(prompt)
     else:
         prompt = ("%[email protected]%s's password: " %
             (nativeString(self.user), self.transport.transport.getPeer().host))
     try:
         # We don't know the encoding the other side is using,
         # signaling that is not part of the SSH protocol. But
         # using our defaultencoding is better than just going for
         # ASCII.
         p = self._getPassword(prompt).encode(sys.getdefaultencoding())
         return defer.succeed(p)
     except ConchError:
         return defer.fail()
开发者ID:dansgithubuser,项目名称:constructicon,代码行数:15,代码来源:default.py


示例15: _unjelly_class

 def _unjelly_class(self, rest):
     cname = nativeString(rest[0])
     clist = cname.split(nativeString('.'))
     modName = nativeString('.').join(clist[:-1])
     if not self.taster.isModuleAllowed(modName):
         raise InsecureJelly("module %s not allowed" % modName)
     klaus = namedObject(cname)
     objType = type(klaus)
     if objType not in (_OldStyleClass, type):
         raise InsecureJelly(
             "class %r unjellied to something that isn't a class: %r" % (
                 cname, klaus))
     if not self.taster.isClassAllowed(klaus):
         raise InsecureJelly("class not allowed: %s" % qual(klaus))
     return klaus
开发者ID:JohnDoes95,项目名称:project_parser,代码行数:15,代码来源:jelly.py


示例16: render

    def render(self, request):
        """
        Render a given resource. See L{IResource}'s render method.

        I delegate to methods of self with the form 'render_METHOD'
        where METHOD is the HTTP that was used to make the
        request. Examples: render_GET, render_HEAD, render_POST, and
        so on. Generally you should implement those methods instead of
        overriding this one.

        render_METHOD methods are expected to return a byte string which will be
        the rendered page, unless the return value is C{server.NOT_DONE_YET}, in
        which case it is this class's responsibility to write the results using
        C{request.write(data)} and then call C{request.finish()}.

        Old code that overrides render() directly is likewise expected
        to return a byte string or NOT_DONE_YET.

        @see: L{IResource.render}
        """
        m = getattr(self, 'render_' + nativeString(request.method), None)
        if not m:
            try:
                allowedMethods = self.allowedMethods
            except AttributeError:
                allowedMethods = _computeAllowedMethods(self)
            raise UnsupportedMethod(allowedMethods)
        return m(request)
开发者ID:Lovelykira,项目名称:frameworks_try,代码行数:28,代码来源:resource.py


示例17: _parseAttributes

 def _parseAttributes(self, data):
     flags ,= struct.unpack('!L', data[:4])
     attrs = {}
     data = data[4:]
     if flags & FILEXFER_ATTR_SIZE == FILEXFER_ATTR_SIZE:
         size ,= struct.unpack('!Q', data[:8])
         attrs['size'] = size
         data = data[8:]
     if flags & FILEXFER_ATTR_OWNERGROUP == FILEXFER_ATTR_OWNERGROUP:
         uid, gid = struct.unpack('!2L', data[:8])
         attrs['uid'] = uid
         attrs['gid'] = gid
         data = data[8:]
     if flags & FILEXFER_ATTR_PERMISSIONS == FILEXFER_ATTR_PERMISSIONS:
         perms ,= struct.unpack('!L', data[:4])
         attrs['permissions'] = perms
         data = data[4:]
     if flags & FILEXFER_ATTR_ACMODTIME == FILEXFER_ATTR_ACMODTIME:
         atime, mtime = struct.unpack('!2L', data[:8])
         attrs['atime'] = atime
         attrs['mtime'] = mtime
         data = data[8:]
     if flags & FILEXFER_ATTR_EXTENDED == FILEXFER_ATTR_EXTENDED:
         extended_count ,= struct.unpack('!L', data[:4])
         data = data[4:]
         for i in xrange(extended_count):
             extended_type, data = getNS(data)
             extended_data, data = getNS(data)
             attrs['ext_%s' % nativeString(extended_type)] = extended_data
     return attrs, data
开发者ID:alfonsjose,项目名称:international-orders-app,代码行数:30,代码来源:filetransfer.py


示例18: gotGlobalRequest

 def gotGlobalRequest(self, requestType, data):
     # XXX should this use method dispatch?
     requestType = nativeString(requestType.replace(b'-', b'_'))
     f = getattr(self, "global_%s" % requestType, None)
     if not f:
         return 0
     return f(data)
开发者ID:JohnDoes95,项目名称:project_parser,代码行数:7,代码来源:avatar.py


示例19: __repr__

 def __repr__(self):
     """
     Return a pretty representation of this object.
     """
     lines = [
         '<%s %s (%s bits)' % (
             nativeString(self.type()),
             self.isPublic() and 'Public Key' or 'Private Key',
             self._keyObject.key_size)]
     for k, v in sorted(self.data().items()):
         if _PY3 and isinstance(k, bytes):
             k = k.decode('ascii')
         lines.append('attr %s:' % (k,))
         by = common.MP(v)[4:]
         while by:
             m = by[:15]
             by = by[15:]
             o = ''
             for c in iterbytes(m):
                 o = o + '%02x:' % (ord(c),)
             if len(m) < 15:
                 o = o[:-1]
             lines.append('\t' + o)
     lines[-1] = lines[-1] + '>'
     return '\n'.join(lines)
开发者ID:daweasel27,项目名称:PhobiaEnemy,代码行数:25,代码来源:keys.py


示例20: test_formatRootShortUnicodeString

 def test_formatRootShortUnicodeString(self):
     """
     The C{_formatRoot} method formats a short unicode string using the
     built-in repr.
     """
     e = self.makeFlattenerError()
     self.assertEqual(e._formatRoot(nativeString('abcd')), repr('abcd'))
开发者ID:marcelpetersen,项目名称:localnews,代码行数:7,代码来源:test_error.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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