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

Python compat.intToBytes函数代码示例

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

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



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

示例1: n

 def n(self, proto, handler, buf):
     if buf == b'6':
         x, y = handler.reportCursorPosition()
         proto.transport.write(b'\x1b['
                               + intToBytes(x+1)
                               + b';'
                               + intToBytes(y+1)
                               + b'R')
     else:
         handler.unhandledControlSequence(b'\x1b[' + buf + b'n')
开发者ID:JohnDoes95,项目名称:project_parser,代码行数:10,代码来源:insults.py


示例2: setScrollRegion

 def setScrollRegion(self, first=None, last=None):
     if first is not None:
         first = intToBytes(first)
     else:
         first = b''
     if last is not None:
         last = intToBytes(last)
     else:
         last = b''
     self.write(b'\x1b[' + first + b';' + last + b'r')
开发者ID:JohnDoes95,项目名称:project_parser,代码行数:10,代码来源:insults.py


示例3: test_selectGraphicRendition

 def test_selectGraphicRendition(self):
     """
     L{ServerProtocol.selectGraphicRendition} writes a control
     sequence containing the requested attributes and ending with
     L{CSFinalByte.SGR}
     """
     self.protocol.selectGraphicRendition(str(BLINK), str(UNDERLINE))
     self.assertEqual(self.transport.value(),
                      self.CSI +
                      intToBytes(BLINK) + b';' + intToBytes(UNDERLINE) +
                      CSFinalByte.SGR.value)
开发者ID:JohnDoes95,项目名称:project_parser,代码行数:11,代码来源:test_insults.py


示例4: cbStarted

        def cbStarted(ignored):
            connectionRefused = client.startedDeferred = defer.Deferred()
            client.transport.connect("127.0.0.1", 80)

            for i in range(10):
                client.transport.write(intToBytes(i))
                server.transport.write(intToBytes(i), ("127.0.0.1", 80))

            return self.assertFailure(
                connectionRefused,
                error.ConnectionRefusedError)
开发者ID:0004c,项目名称:VTK,代码行数:11,代码来源:test_udp.py


示例5: __bytes__

    def __bytes__(self):
        """
        Return a byte string representation of the channel
        """
        name = self.name
        if not name:
            name = b'None'

        return (b'<SSHChannel ' + name +
                b' (lw ' + intToBytes(self.localWindowLeft) +
                b' rw ' + intToBytes(self.remoteWindowLeft) +
                b')>')
开发者ID:JohnDoes95,项目名称:project_parser,代码行数:12,代码来源:channel.py


示例6: testSimpleCardinals

    def testSimpleCardinals(self):
        self.parser.dataReceived(
            b''.join(
                    [b''.join([b'\x1b[' + n + ch
                             for n in (b'', intToBytes(2), intToBytes(20), intToBytes(200))]
                           ) for ch in iterbytes(b'BACD')
                    ]))
        occs = occurrences(self.proto)

        for meth in ("Down", "Up", "Forward", "Backward"):
            for count in (1, 2, 20, 200):
                result = self.assertCall(occs.pop(0), "cursor" + meth, (count,))
                self.assertFalse(occurrences(result))
        self.assertFalse(occs)
开发者ID:JohnDoes95,项目名称:project_parser,代码行数:14,代码来源:test_insults.py


示例7: __init__

    def __init__(self, code, message=None, response=None):
        """
        Initializes a basic exception.

        @type code: L{bytes} or L{int}
        @param code: Refers to an HTTP status code (for example, 200) either as
            an integer or a bytestring representing such. If no C{message} is
            given, C{code} is mapped to a descriptive bytestring that is used
            instead.

        @type message: L{bytes}
        @param message: A short error message, for example "NOT FOUND".

        @type response: L{bytes}
        @param response: A complete HTML document for an error page.
        """
        message = message or _codeToMessage(code)

        Exception.__init__(self, code, message, response)

        if isinstance(code, int):
            # If we're given an int, convert it to a bytestring
            # downloadPage gives a bytes, Agent gives an int, and it worked by
            # accident previously, so just make it keep working.
            code = intToBytes(code)

        self.status = code
        self.message = message
        self.response = response
开发者ID:Lovelykira,项目名称:frameworks_try,代码行数:29,代码来源:error.py


示例8: test_blksize

    def test_blksize(self):
        self.s = MockSession()
        opts = self.proto.processOptions(OrderedDict({b'blksize':b'8'}))
        self.proto.applyOptions(self.s, opts)
        self.assertEqual(self.s.block_size, 8)
        self.assertEqual(opts, OrderedDict({b'blksize':b'8'}))

        self.s = MockSession()
        opts = self.proto.processOptions(OrderedDict({b'blksize':b'foo'}))
        self.proto.applyOptions(self.s, opts)
        self.assertEqual(self.s.block_size, 512)
        self.assertEqual(opts, OrderedDict())

        self.s = MockSession()
        opts = self.proto.processOptions(OrderedDict({b'blksize':b'65464'}))
        self.proto.applyOptions(self.s, opts)
        self.assertEqual(self.s.block_size, MAX_BLOCK_SIZE)
        self.assertEqual(opts, OrderedDict({b'blksize':intToBytes(MAX_BLOCK_SIZE)}))

        self.s = MockSession()
        opts = self.proto.processOptions(OrderedDict({b'blksize':b'65465'}))
        self.proto.applyOptions(self.s, opts)
        self.assertEqual(self.s.block_size, 512)
        self.assertEqual(opts, OrderedDict())

        self.s = MockSession()
        opts = self.proto.processOptions(OrderedDict({b'blksize':b'7'}))
        self.proto.applyOptions(self.s, opts)
        self.assertEqual(self.s.block_size, 512)
        self.assertEqual(opts, OrderedDict())
开发者ID:aivins,项目名称:python-tx-tftp,代码行数:30,代码来源:test_bootstrap.py


示例9: render_GET

 def render_GET(self, request):
     data = json.dumps(request.args)
     request.setHeader(b"content-type", networkString("application/json"))
     request.setHeader(b"content-length", intToBytes(len(data)))
     if request.method == b"HEAD":
         return b""
     return data
开发者ID:Cray,项目名称:buildbot,代码行数:7,代码来源:test_util_httpclientservice.py


示例10: _spawn

def _spawn(script, outputFD):
    """
    Start a script that is a peer of this test as a subprocess.

    @param script: the module name of the script in this directory (no
        package prefix, no '.py')
    @type script: C{str}

    @rtype: L{StartStopProcessProtocol}
    """
    pyExe = FilePath(sys.executable).asBytesMode().path
    env = bytesEnviron()
    env[b"PYTHONPATH"] = FilePath(
        pathsep.join(sys.path)).asBytesMode().path
    sspp = StartStopProcessProtocol()
    reactor.spawnProcess(
        sspp, pyExe, [
            pyExe,
            FilePath(__file__).sibling(script + ".py").asBytesMode().path,
            intToBytes(outputFD),
        ],
        env=env,
        childFDs={0: "w", 1: "r", 2: "r", outputFD: outputFD}
    )
    return sspp
开发者ID:alfonsjose,项目名称:international-orders-app,代码行数:25,代码来源:test_sendmsg.py


示例11: render_GET

 def render_GET(self, request):
     data = json.dumps(request.args)
     request.setHeader(b'content-type', networkString('application/json'))
     request.setHeader(b'content-length', intToBytes(len(data)))
     if request.method == b'HEAD':
         return b''
     return data
开发者ID:nand0p,项目名称:buildbot,代码行数:7,代码来源:test_util_httpclientservice.py


示例12: render_GET

    def render_GET(self, request):
        def decode(x):
            if isinstance(x, bytes):
                return bytes2unicode(x)
            elif isinstance(x, (list, tuple)):
                return [bytes2unicode(y) for y in x]
            elif isinstance(x, dict):
                newArgs = {}
                for a, b in x.items():
                    newArgs[decode(a)] = decode(b)
                return newArgs
            return x

        args = decode(request.args)
        content_type = request.getHeader(b'content-type')
        if content_type == b"application/json":
            jsonBytes = request.content.read()
            jsonStr = bytes2unicode(jsonBytes)
            args['json_received'] = json.loads(jsonStr)

        data = json.dumps(args)
        data = unicode2bytes(data)
        request.setHeader(b'content-type', b'application/json')
        request.setHeader(b'content-length', intToBytes(len(data)))
        if request.method == b'HEAD':
            return b''
        return data
开发者ID:buildbot,项目名称:buildbot,代码行数:27,代码来源:test_util_httpclientservice.py


示例13: _cbRender

    def _cbRender(self, result, request, responseFailed=None):
        if responseFailed:
            return

        if isinstance(result, Handler):
            result = result.result
        if not isinstance(result, Fault):
            result = (result,)
        try:
            try:
                content = xmlrpclib.dumps(
                    result, methodresponse=True,
                    allow_none=self.allowNone)
            except Exception as e:
                f = Fault(self.FAILURE, "Can't serialize output: %s" % (e,))
                content = xmlrpclib.dumps(f, methodresponse=True,
                                          allow_none=self.allowNone)

            if isinstance(content, unicode):
                content = content.encode('utf8')
            request.setHeader(
                b"content-length", intToBytes(len(content)))
            request.write(content)
        except:
            log.err()
        request.finish()
开发者ID:JohnDoes95,项目名称:project_parser,代码行数:26,代码来源:xmlrpc.py


示例14: spin

 def spin():
     for value in count:
         if value == howMany:
             connection.loseConnection()
             return
         connection.write(intToBytes(value))
         break
     reactor.callLater(0, spin)
开发者ID:Architektor,项目名称:PySnip,代码行数:8,代码来源:test_stdio.py


示例15: contentFinish

    def contentFinish(self, content):
        if self.obj.client_supports_gzip:
            self.setHeader(b'content-encoding', b'gzip')
            content = self.zip(content, True)

        self.setHeader(b'content-length', intToBytes(len(content)))
        self.write(content)
        self.finish()
开发者ID:dichead1,项目名称:Tor2web-3.0,代码行数:8,代码来源:t2w.py


示例16: _extractURLparts

def _extractURLparts(request):
    """
    Extracts and decodes URI parts from C{request}.

    All strings must be UTF8-decodable.

    @param request: A Twisted Web request.
    @type request: L{twisted.web.iweb.IRequest}

    @raise URLDecodeError: If one of the parts could not be decoded as UTF-8.

    @return: L{tuple} of the URL scheme, the server name, the server port, the
        path info and the script name.
    @rtype: L{tuple} of L{unicode}, L{unicode}, L{int}, L{unicode}, L{unicode}
    """
    server_name = request.getRequestHostname()
    if hasattr(request.getHost(), 'port'):
        server_port = request.getHost().port
    else:
        server_port = 0
    if (bool(request.isSecure()), server_port) not in [
            (True, 443), (False, 80), (False, 0), (True, 0)]:
        server_name = server_name + b":" + intToBytes(server_port)

    script_name = b''
    if request.prepath:
        script_name = b'/'.join(request.prepath)

        if not script_name.startswith(b'/'):
            script_name = b'/' + script_name

    path_info = b''
    if request.postpath:
        path_info = b'/'.join(request.postpath)

        if not path_info.startswith(b'/'):
            path_info = b'/' + path_info

    url_scheme = u'https' if request.isSecure() else u'http'

    utf8Failures = []
    try:
        server_name = server_name.decode("utf-8")
    except UnicodeDecodeError:
        utf8Failures.append(("SERVER_NAME", failure.Failure()))
    try:
        path_info = path_info.decode("utf-8")
    except UnicodeDecodeError:
        utf8Failures.append(("PATH_INFO", failure.Failure()))
    try:
        script_name = script_name.decode("utf-8")
    except UnicodeDecodeError:
        utf8Failures.append(("SCRIPT_NAME", failure.Failure()))

    if utf8Failures:
        raise _URLDecodeError(utf8Failures)

    return url_scheme, server_name, server_port, path_info, script_name
开发者ID:GeekTemo,项目名称:klein,代码行数:58,代码来源:resource.py


示例17: _render

    def _render(self, request):
        origin = request.getHeader('Origin')
        if origin:
            request.setHeader('Access-Control-Allow-Origin', origin)
            request.setHeader('Access-Control-Allow-Credentials', 'true')
        else:
            request.setHeader('Access-Control-Allow-Origin', '*')
        request.setHeader('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE, OPTIONS, HEAD')
        request.setHeader('Access-Control-Allow-Headers',
                          'Origin, Content-Type, Cache-Control, X-Requested-With, Authorization')

        ret = None
        try:
            ret = yield self.handle_request(request)
            # allow views to take full control of output streaming
            if ret is not NOT_DONE_YET and ret is not EmptyResponse:
                request.setHeader('Content-Type', 'application/json')
                json_data = json.dumps(ret, indent=2, cls=JsonSetEncoder)
                request.setHeader('Content-Length', intToBytes(len(json_data)))
                request.write(json_data)
        except HttpStatus as exc:
            request.setResponseCode(exc.status_code, exc.status_description)
            for name, value in exc.headers.items():
                request.responseHeaders.addRawHeader(name, value)
            # emit a header with location of the trusted keystone instance
            if get_config().getboolean('auth', 'use_keystone', False):
                keystone_uri = get_config().getstring('keystone', 'keystone_uri')
                request.setHeader('WWW-Authenticate', 'Keystone uri=%s' % keystone_uri)
            if exc.body:
                request.write(json.dumps(exc.body))
            else:
                request.write("%s %s\n" % (exc.status_code, exc.status_description))
            if exc.message:
                request.write("%s\n" % exc.message)
        except Exception:
            request.setHeader('Content-Type', 'text/plain')
            request.setResponseCode(500, "Server Error")
            error_message = "%s %s\n\n" % (500, "Server Error")
            request.setHeader('Content-Length', intToBytes(len(error_message)))
            request.write(error_message)
            log.err(system='httprest')
            failure.Failure().printTraceback(request)
        finally:
            if ret is not NOT_DONE_YET:
                request.finish()
开发者ID:AsherBond,项目名称:opennode-management,代码行数:45,代码来源:root.py


示例18: lineReceived

 def lineReceived(self, line):
     self.i += 1
     if self.i < 4:
         # by this point we should have connection closed,
         # but just in case we didn't we won't ever send 'Hello 4'
         self.sendLine(b"Hello " + intToBytes(self.i))
     SimpleProtocol.lineReceived(self, line)
     if self.lines[-1] == b"Hello 3":
         self.transport.loseConnection()
开发者ID:0004c,项目名称:VTK,代码行数:9,代码来源:test_loopback.py


示例19: testHostHeader

 def testHostHeader(self):
     # if we pass Host header explicitly, it should be used, otherwise
     # it should extract from url
     return defer.gatherResults([
         client.getPage(self.getURL("host")).addCallback(
                 self.assertEqual, b"127.0.0.1:" + intToBytes(self.portno)),
         client.getPage(self.getURL("host"),
                        headers={b"Host": b"www.example.com"}).addCallback(
                 self.assertEqual, b"www.example.com")])
开发者ID:alfonsjose,项目名称:international-orders-app,代码行数:9,代码来源:test_webclient.py


示例20: forwardData

    def forwardData(self, data, end=False):
        if not self.startedWriting:
            if self.obj.client_supports_gzip:
                self.setHeader(b'content-encoding', b'gzip')

            if data != '' and end:
                self.setHeader(b'content-length', intToBytes(len(data)))

        if data != '':
            self.write(data)
开发者ID:dichead1,项目名称:Tor2web-3.0,代码行数:10,代码来源:t2w.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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