当前位置: 首页>>代码示例>>Python>>正文


Python BytesIO.write方法代码示例

本文整理汇总了Python中six.BytesIO.write方法的典型用法代码示例。如果您正苦于以下问题:Python BytesIO.write方法的具体用法?Python BytesIO.write怎么用?Python BytesIO.write使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在six.BytesIO的用法示例。


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

示例1: readline

# 需要导入模块: from six import BytesIO [as 别名]
# 或者: from six.BytesIO import write [as 别名]
    def readline(self, size=-1):
        if self.eof:
            return self.tmp.readline()

        orig_size = self._tmp_size()
        if self.tmp.tell() == orig_size:
            if not self._tee(self.CHUNK_SIZE):
                return ''
            self.tmp.seek(orig_size)

        # now we can get line
        line = self.tmp.readline()
        if line.find("\n") >=0:
            return line

        buf = StringIO()
        buf.write(line)
        while True:
            orig_size = self.tmp.tell()
            data = self._tee(self.CHUNK_SIZE)
            if not data:
                break
            self.tmp.seek(orig_size)
            buf.write(self.tmp.readline())
            if data.find("\n") >= 0:
                break
        return buf.getvalue()
开发者ID:pashinin,项目名称:restkit,代码行数:29,代码来源:tee.py

示例2: render

# 需要导入模块: from six import BytesIO [as 别名]
# 或者: from six.BytesIO import write [as 别名]
    def render(self, data, media_type=None, renderer_context=None):
        renderer_context = renderer_context or {}
        request = renderer_context['request']
        template = request.query_params.get('template', 'export')
        view = renderer_context['view']
        data = json.loads(json.dumps(data, cls=encoders.JSONEncoder))
        if template == 'import':
            data = [data[0]] if data else data

        try:
            serializer = view.get_serializer()
            self.set_response_disposition(serializer, renderer_context)
        except Exception as e:
            logger.debug(e, exc_info=True)
            value = 'The resource not support export!'.encode('utf-8')
        else:
            fields = serializer.get_fields()
            header = self._get_header(fields, template)
            labels = {k: v.label for k, v in fields.items() if v.label}
            table = self._gen_table(data, header, labels)

            csv_buffer = BytesIO()
            csv_buffer.write(codecs.BOM_UTF8)
            csv_writer = unicodecsv.writer(csv_buffer, encoding='utf-8')
            for row in table:
                csv_writer.writerow(row)

            value = csv_buffer.getvalue()

        return value
开发者ID:jumpserver,项目名称:jumpserver,代码行数:32,代码来源:csv.py

示例3: __init__

# 需要导入模块: from six import BytesIO [as 别名]
# 或者: from six.BytesIO import write [as 别名]
    def __init__(self, host, port, backend_mod=None, pool=None,
                 is_ssl=False, extra_headers=[], proxy_pieces=None, **ssl_args):

        # connect the socket, if we are using an SSL connection, we wrap
        # the socket.
        self._s = backend_mod.Socket(socket.AF_INET, socket.SOCK_STREAM)
        self._s.connect((host, port))
        if proxy_pieces:
            self._s.sendall(proxy_pieces)
            response = StringIO()
            while response.getvalue()[-4:] != b'\r\n\r\n':
                response.write(self._s.recv(1))
            response.close()
        if is_ssl:
            self._s = ssl.wrap_socket(self._s, **ssl_args)

        self.extra_headers = extra_headers
        self.is_ssl = is_ssl
        self.backend_mod = backend_mod
        self.host = host
        self.port = port
        self._connected = True
        self._life = time.time() - random.randint(0, 10)
        self._pool = pool
        self._released = False
开发者ID:pashinin,项目名称:restkit,代码行数:27,代码来源:conn.py

示例4: _pack_data_records_unchecked

# 需要导入模块: from six import BytesIO [as 别名]
# 或者: from six.BytesIO import write [as 别名]
def _pack_data_records_unchecked(contents):
    f = BytesIO()
    for record in contents:
        record = record.encode("ascii")
        write_uleb128(len(record), f)
        f.write(record)
    return f.getvalue()
开发者ID:njsmith,项目名称:zs,代码行数:9,代码来源:make-broken.py

示例5: get_certificate

# 需要导入模块: from six import BytesIO [as 别名]
# 或者: from six.BytesIO import write [as 别名]
    def get_certificate(self):
        # Get the file in a StringIO
        f = BytesIO()
        for chunk in self.cleaned_data['pem_file'].chunks():
            f.write(chunk)

        # Read Certificate Informations
        cert = crypto.load_certificate(crypto.FILETYPE_PEM, f.getvalue())

        params = {}
        serial = UUID(str(hex(
            cert.get_serial_number())).lstrip('0x').rstrip('L'))
        params['serial'] = str(serial).replace('-', '')
        params['dn'] = get_subject_from_components(
            cert.get_subject().get_components())
        params['created_at'] = parse(cert.get_notBefore())
        params['expire_at'] = parse(cert.get_notAfter())

        try:
            certificate = Certificate.objects.get(serial=params['serial'])
        except Certificate.DoesNotExist:
            return Certificate.objects.create(**params)
        else:
            exception = CertificateAlreadyExist(
                'This certificate already exists %s' % params['serial'])
            exception.certificate = certificate
            raise exception
开发者ID:novafloss,项目名称:django-x509,代码行数:29,代码来源:forms.py

示例6: recvbytes

# 需要导入模块: from six import BytesIO [as 别名]
# 或者: from six.BytesIO import write [as 别名]
def recvbytes(self, bytes_needed, sock_buf = None):
    """
        Atomic read of bytes_needed bytes.

        This function either returns exactly the nmber of bytes requested in a
        StringIO buffer, None, or raises a socket error.

        If the return value is None, it means the socket is closed by the other side.
    """
    if sock_buf is None:
        sock_buf = BytesIO()
    bytes_count = 0
    while bytes_count < bytes_needed:
        chunk = self.recv(min(bytes_needed - bytes_count, 32768))
        part_count = len(chunk)

        if type(chunk) == str:
            chunk = b(chunk)

        if part_count < 1:
            return None

        bytes_count += part_count
        sock_buf.write(chunk)

    return sock_buf
开发者ID:ZJDong,项目名称:Wayfindr-Py,代码行数:28,代码来源:network.py

示例7: serialize

# 需要导入模块: from six import BytesIO [as 别名]
# 或者: from six.BytesIO import write [as 别名]
    def serialize(self, xid=None):
        buff = BytesIO()

        formats = []
        data = []
        if xid is not None:
            formats.append(Int.fmt)
            data.append(xid)
        if self.opcode:
            formats.append(Int.fmt)
            data.append(self.opcode)

        for request in self.requests:
            header = MultiHeader(type=request.opcode, done=False, error=-1)
            header_format, header_data = header.render()
            formats.append(header_format)
            data.extend(header_data)

            payload_format, payload_data = request.render()
            formats.append(payload_format)
            data.extend(payload_data)

        footer = MultiHeader(type=-1, done=True, error=-1)
        footer_format, footer_data = footer.render()
        formats.append(footer_format)
        data.extend(footer_data)

        buff.write(struct.pack("!" + "".join(formats), *data))

        return buff.getvalue()
开发者ID:wglass,项目名称:zoonado,代码行数:32,代码来源:transaction.py

示例8: serialize

# 需要导入模块: from six import BytesIO [as 别名]
# 或者: from six.BytesIO import write [as 别名]
    def serialize(self):
        """
        Returns a bytesring representation of the request instance.

        Prefaces the output with certain information::

          api_key => Int16
          api_version => Int16
          correlation_id => Int32
          client_id => String

        Since this is a ``Part`` subclass the rest is a matter of
        appending the result of a ``render()`` call.
        """
        buff = BytesIO()

        preamble_parts = (
            ("api_key", Int16),
            ("api_version", Int16),
            ("correlation_id", Int32),
            ("client_id", String),
        )

        preamble_format, data = self.render(preamble_parts)

        payload_format, payload_data = self.render()

        fmt = "".join(["!", preamble_format, payload_format])
        data.extend(payload_data)

        buff.write(struct.pack(fmt, *data))

        return buff.getvalue()
开发者ID:FlorianLudwig,项目名称:kiel,代码行数:35,代码来源:request.py

示例9: decompress

# 需要导入模块: from six import BytesIO [as 别名]
# 或者: from six.BytesIO import write [as 别名]
def decompress(data):
    """
    Decompresses the given data via the snappy algorithm.

    If ``python-snappy`` is not installed a ``RuntimeError`` is raised.
    """
    if not snappy_available:
        raise RuntimeError("Snappy compression unavailable.")

    buff_offset = len(raw_header)  # skip the header
    length = len(data) - len(raw_header)

    output = BytesIO()

    while buff_offset <= length:
        block_size = struct.unpack_from("!i", data, buff_offset)[0]
        buff_offset += struct.calcsize("!i")

        block = struct.unpack_from("!%ds" % block_size, data, buff_offset)[0]
        buff_offset += block_size

        output.write(snappy.uncompress(block))

    result = output.getvalue()

    output.close()

    return result
开发者ID:FlorianLudwig,项目名称:kiel,代码行数:30,代码来源:snappy.py

示例10: handle

# 需要导入模块: from six import BytesIO [as 别名]
# 或者: from six.BytesIO import write [as 别名]
def handle(name, cfg, cloud, log, _args):
    mycfg = cfg.get('random_seed', {})
    seed_path = mycfg.get('file', '/dev/urandom')
    seed_data = mycfg.get('data', b'')

    seed_buf = BytesIO()
    if seed_data:
        seed_buf.write(_decode(seed_data, encoding=mycfg.get('encoding')))

    # 'random_seed' is set up by Azure datasource, and comes already in
    # openstack meta_data.json
    metadata = cloud.datasource.metadata
    if metadata and 'random_seed' in metadata:
        seed_buf.write(util.encode_text(metadata['random_seed']))

    seed_data = seed_buf.getvalue()
    if len(seed_data):
        log.debug("%s: adding %s bytes of random seed entropy to %s", name,
                  len(seed_data), seed_path)
        util.append_file(seed_path, seed_data)

    command = mycfg.get('command', None)
    req = mycfg.get('command_required', False)
    try:
        env = os.environ.copy()
        env['RANDOM_SEED_FILE'] = seed_path
        handle_random_seed_command(command=command, required=req, env=env)
    except ValueError as e:
        log.warn("handling random command [%s] failed: %s", command, e)
        raise e
开发者ID:BenjaminSchiborr,项目名称:cloud-init,代码行数:32,代码来源:cc_seed_random.py

示例11: make_stream

# 需要导入模块: from six import BytesIO [as 别名]
# 或者: from six.BytesIO import write [as 别名]
def make_stream(size):
    """Make a stream of a given size."""
    s = BytesIO()
    s.seek(size - 1)
    s.write(b'\0')
    s.seek(0)
    return s
开发者ID:inveniosoftware,项目名称:invenio-files-rest,代码行数:9,代码来源:test_models_multipart.py

示例12: TFramedTransport

# 需要导入模块: from six import BytesIO [as 别名]
# 或者: from six.BytesIO import write [as 别名]
class TFramedTransport(TTransportBase, CReadableTransport):
  """Class that wraps another transport and frames its I/O when writing."""

  def __init__(self, trans,):
    self.__trans = trans
    self.__rbuf = BytesIO()
    self.__wbuf = BytesIO()

  def isOpen(self):
    return self.__trans.isOpen()

  def open(self):
    return self.__trans.open()

  def close(self):
    return self.__trans.close()

  def read(self, sz):
    ret = self.__rbuf.read(sz)
    if len(ret) != 0:
      return ret

    self.readFrame()
    return self.__rbuf.read(sz)

  def readFrame(self):
    buff = self.__trans.readAll(4)
    sz, = unpack('!i', buff)
    self.__rbuf = BytesIO(self.__trans.readAll(sz))

  def write(self, buf):
    self.__wbuf.write(buf)

  def flush(self):
    wout = self.__wbuf.getvalue()
    wsz = len(wout)
    # reset wbuf before write/flush to preserve state on underlying failure
    self.__wbuf = BytesIO()
    # N.B.: Doing this string concatenation is WAY cheaper than making
    # two separate calls to the underlying socket object. Socket writes in
    # Python turn out to be REALLY expensive, but it seems to do a pretty
    # good job of managing string buffer operations without excessive copies
    buf = pack("!i", wsz) + wout
    self.__trans.write(buf)
    self.__trans.flush()

  # Implement the CReadableTransport interface.
  @property
  def cstringio_buf(self):
    return self.__rbuf

  def cstringio_refill(self, prefix, reqlen):
    # self.__rbuf will already be empty here because fastbinary doesn't
    # ask for a refill until the previous buffer is empty.  Therefore,
    # we can start reading new frames immediately.
    while len(prefix) < reqlen:
      self.readFrame()
      prefix += self.__rbuf.getvalue()
    self.__rbuf = BytesIO(prefix)
    return self.__rbuf
开发者ID:AndyHovingh,项目名称:intellij-community,代码行数:62,代码来源:TTransport.py

示例13: parsestring

# 需要导入模块: from six import BytesIO [as 别名]
# 或者: from six.BytesIO import write [as 别名]
 def parsestring(self, s):
     """Parse s as an N-Triples string."""
     if not isinstance(s, string_types):
         raise ParseError("Item to parse must be a string instance.")
     f = BytesIO()
     f.write(cast_bytes(s))
     f.seek(0)
     self.parse(f)
开发者ID:drewp,项目名称:rdflib,代码行数:10,代码来源:ntriples.py

示例14: TBufferedTransport

# 需要导入模块: from six import BytesIO [as 别名]
# 或者: from six.BytesIO import write [as 别名]
class TBufferedTransport(TTransportBase, CReadableTransport):
  """Class that wraps another transport and buffers its I/O.

  The implementation uses a (configurable) fixed-size read buffer
  but buffers all writes until a flush is performed.
  """
  DEFAULT_BUFFER = 4096

  def __init__(self, trans, rbuf_size=DEFAULT_BUFFER):
    self.__trans = trans
    self.__wbuf = BytesIO()
    self.__rbuf = BytesIO("")
    self.__rbuf_size = rbuf_size

  def isOpen(self):
    return self.__trans.isOpen()

  def open(self):
    return self.__trans.open()

  def close(self):
    return self.__trans.close()

  def read(self, sz):
    ret = self.__rbuf.read(sz)
    if len(ret) != 0:
      return ret

    self.__rbuf = BytesIO(self.__trans.read(max(sz, self.__rbuf_size)))
    return self.__rbuf.read(sz)

  def write(self, buf):
    self.__wbuf.write(buf)

  def flush(self):
    out = self.__wbuf.getvalue()
    # reset wbuf before write/flush to preserve state on underlying failure
    self.__wbuf = BytesIO()
    self.__trans.write(out)
    self.__trans.flush()

  # Implement the CReadableTransport interface.
  @property
  def cstringio_buf(self):
    return self.__rbuf

  def cstringio_refill(self, partialread, reqlen):
    retstring = partialread
    if reqlen < self.__rbuf_size:
      # try to make a read of as much as we can.
      retstring += self.__trans.read(self.__rbuf_size)

    # but make sure we do read reqlen bytes.
    if len(retstring) < reqlen:
      retstring += self.__trans.readAll(reqlen - len(retstring))

    self.__rbuf = BytesIO(retstring)
    return self.__rbuf
开发者ID:Unidata,项目名称:python-awips,代码行数:60,代码来源:TTransport.py

示例15: write

# 需要导入模块: from six import BytesIO [as 别名]
# 或者: from six.BytesIO import write [as 别名]
 def write(self, s):
     # Ensure we always write bytes. This means that wrapped code calling
     # print(<a string object>) in Python 3 will still work. Sigh.
     if isinstance(s, six.text_type):
         s = s.encode('utf-8')
     # Write out to our capturing object & any CC's
     IO.write(self, s)
     for writer in self.cc:
         writer.write(s)
开发者ID:bitprophet,项目名称:spec,代码行数:11,代码来源:trap.py


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