當前位置: 首頁>>代碼示例>>Python>>正文


Python compat.networkString方法代碼示例

本文整理匯總了Python中twisted.python.compat.networkString方法的典型用法代碼示例。如果您正苦於以下問題:Python compat.networkString方法的具體用法?Python compat.networkString怎麽用?Python compat.networkString使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在twisted.python.compat的用法示例。


在下文中一共展示了compat.networkString方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: _prePathURL

# 需要導入模塊: from twisted.python import compat [as 別名]
# 或者: from twisted.python.compat import networkString [as 別名]
def _prePathURL(self, prepath):
        port = self.getHost().port
        if self.isSecure():
            default = 443
        else:
            default = 80
        if port == default:
            hostport = ''
        else:
            hostport = ':%d' % port
        prefix = networkString('http%s://%s%s/' % (
            self.isSecure() and 's' or '',
            nativeString(self.getRequestHostname()),
            hostport))
        path = b'/'.join([quote(segment, safe=b'') for segment in prepath])
        return prefix + path 
開發者ID:proxysh,項目名稱:Safejumper-for-Desktop,代碼行數:18,代碼來源:server.py

示例2: render

# 需要導入模塊: from twisted.python import compat [as 別名]
# 或者: from twisted.python.compat import networkString [as 別名]
def render(self, request):
        """
        Send www-authenticate headers to the client
        """
        def generateWWWAuthenticate(scheme, challenge):
            l = []
            for k,v in challenge.items():
                l.append(networkString("%s=%s" % (k, quoteString(v))))
            return b" ".join([scheme, b", ".join(l)])

        def quoteString(s):
            return '"%s"' % (s.replace('\\', '\\\\').replace('"', '\\"'),)

        request.setResponseCode(401)
        for fact in self._credentialFactories:
            challenge = fact.getChallenge(request)
            request.responseHeaders.addRawHeader(
                b'www-authenticate',
                generateWWWAuthenticate(fact.scheme, challenge))
        if request.method == b'HEAD':
            return b''
        return b'Unauthorized' 
開發者ID:proxysh,項目名稱:Safejumper-for-Desktop,代碼行數:24,代碼來源:wrapper.py

示例3: _setContentHeaders

# 需要導入模塊: from twisted.python import compat [as 別名]
# 或者: from twisted.python.compat import networkString [as 別名]
def _setContentHeaders(self, request, size=None):
        """
        Set the Content-length and Content-type headers for this request.

        This method is not appropriate for requests for multiple byte ranges;
        L{_doMultipleRangeRequest} will set these headers in that case.

        @param request: The L{twisted.web.http.Request} object.
        @param size: The size of the response.  If not specified, default to
            C{self.getFileSize()}.
        """
        if size is None:
            size = self.getFileSize()
        request.setHeader(b'content-length', intToBytes(size))
        if self.type:
            request.setHeader(b'content-type', networkString(self.type))
        if self.encoding:
            request.setHeader(b'content-encoding', networkString(self.encoding)) 
開發者ID:proxysh,項目名稱:Safejumper-for-Desktop,代碼行數:20,代碼來源:static.py

示例4: test_frameElementFilename

# 需要導入模塊: from twisted.python import compat [as 別名]
# 或者: from twisted.python.compat import networkString [as 別名]
def test_frameElementFilename(self):
        """
        The I{filename} renderer of L{_FrameElement} renders the filename
        associated with the frame object used to initialize the
        L{_FrameElement}.
        """
        element = _FrameElement(
            TagLoader(tags.span(render="filename")),
            self.frame)
        d = flattenString(None, element)
        d.addCallback(
            # __file__ differs depending on whether an up-to-date .pyc file
            # already existed.
            self.assertEqual,
            b"<span>" + networkString(__file__.rstrip('c')) + b"</span>")
        return d 
開發者ID:proxysh,項目名稱:Safejumper-for-Desktop,代碼行數:18,代碼來源:test_util.py

示例5: test_noRangeHeaderSetsContentHeaders

# 需要導入模塊: from twisted.python import compat [as 別名]
# 或者: from twisted.python.compat import networkString [as 別名]
def test_noRangeHeaderSetsContentHeaders(self):
        """
        makeProducer when no Range header is set sets the Content-* headers
        for the response.
        """
        length = 123
        contentType = "text/plain"
        contentEncoding = 'gzip'
        resource = self.makeResourceWithContent(
            b'a'*length, type=contentType, encoding=contentEncoding)
        request = DummyRequest([])
        with resource.openForReading() as file:
            resource.makeProducer(request, file)
            self.assertEqual(
                {b'content-type': networkString(contentType), b'content-length': intToBytes(length),
                 b'content-encoding': networkString(contentEncoding)},
                self.contentHeaders(request)) 
開發者ID:proxysh,項目名稱:Safejumper-for-Desktop,代碼行數:19,代碼來源:test_static.py

示例6: test_singleRangeSetsContentHeaders

# 需要導入模塊: from twisted.python import compat [as 別名]
# 或者: from twisted.python.compat import networkString [as 別名]
def test_singleRangeSetsContentHeaders(self):
        """
        makeProducer when the Range header requests a single, satisfiable byte
        range sets the Content-* headers appropriately.
        """
        request = DummyRequest([])
        request.requestHeaders.addRawHeader(b'range', b'bytes=1-3')
        contentType = "text/plain"
        contentEncoding = 'gzip'
        resource = self.makeResourceWithContent(b'abcdef', type=contentType, encoding=contentEncoding)
        with resource.openForReading() as file:
            resource.makeProducer(request, file)
            self.assertEqual(
                {b'content-type': networkString(contentType),
                 b'content-encoding': networkString(contentEncoding),
                 b'content-range': b'bytes 1-3/6', b'content-length': b'3'},
                self.contentHeaders(request)) 
開發者ID:proxysh,項目名稱:Safejumper-for-Desktop,代碼行數:19,代碼來源:test_static.py

示例7: test_multipleRangeRequestWithRangeOverlappingEnd

# 需要導入模塊: from twisted.python import compat [as 別名]
# 或者: from twisted.python.compat import networkString [as 別名]
def test_multipleRangeRequestWithRangeOverlappingEnd(self):
        """
        The response to a request for multiple bytes ranges is a MIME-ish
        multipart response, even when one of the ranged falls off the end of
        the resource.
        """
        startEnds = [(0, 2), (40, len(self.payload) + 10)]
        rangeHeaderValue = b','.join([networkString("%s-%s" % (s,e)) for (s, e) in startEnds])
        self.request.requestHeaders.addRawHeader(b'range',
                                                 b'bytes=' + rangeHeaderValue)
        self.resource.render(self.request)
        self.assertEqual(self.request.responseCode, http.PARTIAL_CONTENT)
        boundary = re.match(
            b'^multipart/byteranges; boundary="(.*)"$',
            self.request.responseHeaders.getRawHeaders(b'content-type')[0]).group(1)
        parts = self.parseMultipartBody(b''.join(self.request.written), boundary)
        self.assertEqual(len(startEnds), len(parts))
        for part, (s, e) in zip(parts, startEnds):
            self.assertEqual(networkString(self.resource.type),
                             part[b'contentType'])
            start, end, size = part[b'contentRange']
            self.assertEqual(int(start), s)
            self.assertEqual(int(end), min(e, self.resource.getFileSize()-1))
            self.assertEqual(int(size), self.resource.getFileSize())
            self.assertEqual(self.payload[s:e+1], part[b'body']) 
開發者ID:proxysh,項目名稱:Safejumper-for-Desktop,代碼行數:27,代碼來源:test_static.py

示例8: test_invalidStartBytePos

# 需要導入模塊: from twisted.python import compat [as 別名]
# 或者: from twisted.python.compat import networkString [as 別名]
def test_invalidStartBytePos(self):
        """
        If a range is unsatisfiable due to the start not being less than the
        length of the resource, the response is 416 (Requested range not
        satisfiable) and no data is written to the response body (RFC 2616,
        section 14.35.1).
        """
        self.request.requestHeaders.addRawHeader(b'range', b'bytes=67-108')
        self.resource.render(self.request)
        self.assertEqual(
            self.request.responseCode, http.REQUESTED_RANGE_NOT_SATISFIABLE)
        self.assertEqual(b''.join(self.request.written), b'')
        self.assertEqual(
            self.request.responseHeaders.getRawHeaders(b'content-length')[0],
            b'0')
        # Sections 10.4.17 and 14.16
        self.assertEqual(
            self.request.responseHeaders.getRawHeaders(b'content-range')[0],
            networkString('bytes */%d' % (len(self.payload),))) 
開發者ID:proxysh,項目名稱:Safejumper-for-Desktop,代碼行數:21,代碼來源:test_static.py

示例9: test_getPageDeprecated

# 需要導入模塊: from twisted.python import compat [as 別名]
# 或者: from twisted.python.compat import networkString [as 別名]
def test_getPageDeprecated(self):
        """
        L{client.getPage} is deprecated.
        """
        port = reactor.listenTCP(
            0, server.Site(Data(b'', 'text/plain')), interface="127.0.0.1")
        portno = port.getHost().port
        self.addCleanup(port.stopListening)
        url = networkString("http://127.0.0.1:%d" % (portno,))

        d = client.getPage(url)
        warningInfo = self.flushWarnings([self.test_getPageDeprecated])
        self.assertEqual(len(warningInfo), 1)
        self.assertEqual(warningInfo[0]['category'], DeprecationWarning)
        self.assertEqual(
            warningInfo[0]['message'],
            "twisted.web.client.getPage was deprecated in "
            "Twisted 16.7.0; please use https://pypi.org/project/treq/ or twisted.web.client.Agent instead")

        return d.addErrback(lambda _: None) 
開發者ID:proxysh,項目名稱:Safejumper-for-Desktop,代碼行數:22,代碼來源:test_webclient.py

示例10: test_calculateResponse

# 需要導入模塊: from twisted.python import compat [as 別名]
# 或者: from twisted.python.compat import networkString [as 別名]
def test_calculateResponse(self):
        """
        The response to a Digest-MD5 challenge is computed according to RFC
        2831.
        """
        charset = 'utf-8'
        nonce = b'OA6MG9tEQGm2hh'
        nc = networkString('%08x' % (1,))
        cnonce = b'OA6MHXh6VqTrRk'

        username = u'\u0418chris'
        password = u'\u0418secret'
        host = u'\u0418elwood.innosoft.com'
        digestURI = u'imap/\u0418elwood.innosoft.com'.encode(charset)

        mechanism = sasl_mechanisms.DigestMD5(
            b'imap', host, None, username, password)
        response = mechanism._calculateResponse(
            cnonce, nc, nonce, username.encode(charset),
            password.encode(charset), host.encode(charset), digestURI)
        self.assertEqual(response, b'7928f233258be88392424d094453c5e3') 
開發者ID:proxysh,項目名稱:Safejumper-for-Desktop,代碼行數:23,代碼來源:test_jabbersaslmechanisms.py

示例11: test_oldNonce

# 需要導入模塊: from twisted.python import compat [as 別名]
# 或者: from twisted.python.compat import networkString [as 別名]
def test_oldNonce(self):
        """
        L{DigestCredentialFactory.decode} raises L{LoginFailed} when the given
        opaque is older than C{DigestCredentialFactory.CHALLENGE_LIFETIME_SECS}
        """
        credentialFactory = FakeDigestCredentialFactory(self.algorithm,
                                                        self.realm)
        challenge = credentialFactory.getChallenge(self.clientAddress.host)

        key = b",".join((challenge['nonce'],
                         networkString(self.clientAddress.host),
                         b'-137876876'))
        digest = hexlify(md5(key + credentialFactory.privateKey).digest())
        ekey = b64encode(key)

        oldNonceOpaque = b"-".join((digest, ekey.strip(b'\n')))

        self.assertRaises(
            LoginFailed,
            credentialFactory._verifyOpaque,
            oldNonceOpaque,
            challenge['nonce'],
            self.clientAddress.host) 
開發者ID:proxysh,項目名稱:Safejumper-for-Desktop,代碼行數:25,代碼來源:test_digestauth.py

示例12: test_mismatchedOpaqueChecksum

# 需要導入模塊: from twisted.python import compat [as 別名]
# 或者: from twisted.python.compat import networkString [as 別名]
def test_mismatchedOpaqueChecksum(self):
        """
        L{DigestCredentialFactory.decode} raises L{LoginFailed} when the opaque
        checksum fails verification.
        """
        credentialFactory = FakeDigestCredentialFactory(self.algorithm,
                                                        self.realm)
        challenge = credentialFactory.getChallenge(self.clientAddress.host)

        key = b",".join((challenge['nonce'],
                         networkString(self.clientAddress.host),
                         b'0'))

        digest = hexlify(md5(key + b'this is not the right pkey').digest())
        badChecksum = b"-".join((digest, b64encode(key)))

        self.assertRaises(
            LoginFailed,
            credentialFactory._verifyOpaque,
            badChecksum,
            challenge['nonce'],
            self.clientAddress.host) 
開發者ID:proxysh,項目名稱:Safejumper-for-Desktop,代碼行數:24,代碼來源:test_digestauth.py

示例13: verifyHostKey

# 需要導入模塊: from twisted.python import compat [as 別名]
# 或者: from twisted.python.compat import networkString [as 別名]
def verifyHostKey(self, hostKey, fingerprint):
        """
        Ask the L{KnownHostsFile} provider available on the factory which
        created this protocol this protocol to verify the given host key.

        @return: A L{Deferred} which fires with the result of
            L{KnownHostsFile.verifyHostKey}.
        """
        hostname = self.creator.hostname
        ip = networkString(self.transport.getPeer().host)

        self._state = b'SECURING'
        d = self.creator.knownHosts.verifyHostKey(
            self.creator.ui, hostname, ip, Key.fromString(hostKey))
        d.addErrback(self._saveHostKeyFailure)
        return d 
開發者ID:proxysh,項目名稱:Safejumper-for-Desktop,代碼行數:18,代碼來源:endpoints.py

示例14: test_destination

# 需要導入模塊: from twisted.python import compat [as 別名]
# 或者: from twisted.python.compat import networkString [as 別名]
def test_destination(self):
        """
        L{SSHCommandClientEndpoint} uses the L{IReactorTCP} passed to it to
        attempt a connection to the host/port address also passed to it.
        """
        endpoint = SSHCommandClientEndpoint.newConnection(
            self.reactor, b"/bin/ls -l", self.user, self.hostname, self.port,
            password=self.password, knownHosts=self.knownHosts,
            ui=FixedResponseUI(False))
        factory = Factory()
        factory.protocol = Protocol
        endpoint.connect(factory)

        host, port, factory, timeout, bindAddress = self.reactor.tcpClients[0]
        self.assertEqual(self.hostname, networkString(host))
        self.assertEqual(self.port, port)
        self.assertEqual(1, len(self.reactor.tcpClients)) 
開發者ID:proxysh,項目名稱:Safejumper-for-Desktop,代碼行數:19,代碼來源:test_endpoints.py

示例15: processEnded

# 需要導入模塊: from twisted.python import compat [as 別名]
# 或者: from twisted.python.compat import networkString [as 別名]
def processEnded(self, reason=None):
        """
        When we are told the process ended, try to notify the other side about
        how the process ended using the exit-signal or exit-status requests.
        Also, close the channel.
        """
        if reason is not None:
            err = reason.value
            if err.signal is not None:
                signame = self._getSignalName(err.signal)
                if (getattr(os, 'WCOREDUMP', None) is not None and
                    os.WCOREDUMP(err.status)):
                    log.msg('exitSignal: %s (core dumped)' % (signame,))
                    coreDumped = 1
                else:
                    log.msg('exitSignal: %s' % (signame,))
                    coreDumped = 0
                self.session.conn.sendRequest(self.session, b'exit-signal',
                        common.NS(networkString(signame[3:])) +
                        chr(coreDumped) + common.NS(b'') + common.NS(b''))
            elif err.exitCode is not None:
                log.msg('exitCode: %r' % (err.exitCode,))
                self.session.conn.sendRequest(self.session, b'exit-status',
                        struct.pack('>L', err.exitCode))
        self.session.loseConnection() 
開發者ID:proxysh,項目名稱:Safejumper-for-Desktop,代碼行數:27,代碼來源:session.py


注:本文中的twisted.python.compat.networkString方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。