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


Python BytesIO.flush方法代码示例

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


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

示例1: test_round_trip_rss

# 需要导入模块: from six import BytesIO [as 别名]
# 或者: from six.BytesIO import flush [as 别名]
def test_round_trip_rss():
    now = datetime.utcnow().replace(microsecond=0)
    feed = rss_gen.RSS2(
        title='Feed Title',
        link='http://example.com/link/',
        description='feed description',
        lastBuildDate=now,
        items=[
            rss_gen.RSSItem(
                title='Item Title',
                link='http://example.com/1/',
                description='item description',
                pubDate=now - timedelta(seconds=5),
            ),
            rss_gen.RSSItem(
                title='Second Item Title',
                link='http://example.com/2/',
                description='another item description',
                pubDate=now - timedelta(seconds=10),
            )
        ]
    )
    pseudofile = BytesIO()
    feed.write_xml(pseudofile, encoding='utf-8')
    pseudofile.flush()
    pseudofile.seek(0)
    parsed = parse_rss(pseudofile)
    assert_feeds_equal(feed, parsed)
开发者ID:tikitu,项目名称:dripfeed,代码行数:30,代码来源:test_dripfeed.py

示例2: UniversalBytesIO

# 需要导入模块: from six import BytesIO [as 别名]
# 或者: from six.BytesIO import flush [as 别名]
class UniversalBytesIO(object):

    def __init__(self, container=None, charset=None):
        self.charset = charset or settings.DEFAULT_CHARSET
        self._container = BytesIO() if container is None else container

    # These methods partially implement the file-like object interface.
    # See https://docs.python.org/3/library/io.html#io.IOBase

    def close(self):
        self._container.close()

    def write(self, content):
        self._container.write(self.make_bytes(content))

    def flush(self):
        self._container.flush()

    def tell(self):
        return self._container.tell()

    def readable(self):
        return False

    def seekable(self):
        return False

    def writable(self):
        return True

    def writelines(self, lines):
        for line in lines:
            self.write(line)

    def make_bytes(self, value):
        """Turn a value into a bytestring encoded in the output charset."""
        if isinstance(value, bytes):
            return bytes(value)
        if isinstance(value, six.text_type):
            return bytes(value.encode(self.charset))

        # Handle non-string types
        return force_bytes(value, self.charset)

    def get_string_value(self):
        return self._container.getvalue().decode(self.charset)

    def getvalue(self):
        return self._container.getvalue()

    if sys.version_info[0:2] < (3, 5):
        def seek(self, *args, **kwargs):
            pass
开发者ID:rubickcz,项目名称:django-pyston,代码行数:55,代码来源:helpers.py

示例3: process

# 需要导入模块: from six import BytesIO [as 别名]
# 或者: from six.BytesIO import flush [as 别名]
    def process(self, request, ids):
        if isinstance(ids, six.string_types) and ids == "all":
            return JsonResponse({"error": ugettext("Selecting all is not supported.")})
        shipment_ids = set(Shipment.objects.filter(order_id__in=ids).values_list("id", flat=True))
        if len(shipment_ids) == 1:
            try:
                shipment_id = shipment_ids.pop()
                response = get_delivery_pdf(request, shipment_id)
                response['Content-Disposition'] = 'attachment; filename=shipment_%s_delivery.pdf' % shipment_id
                return response
            except Exception as e:
                msg = e.message if hasattr(e, "message") else e
                return JsonResponse({"error": force_text(msg)})
        buff = BytesIO()
        archive = zipfile.ZipFile(buff, 'w', zipfile.ZIP_DEFLATED)

        added = 0
        errors = []
        for id in shipment_ids:
            try:
                pdf_file = get_delivery_pdf(request, id)
                filename = "shipment_%d_delivery.pdf" % id
                archive.writestr(filename, pdf_file.content)
                added += 1
            except Exception as e:
                msg = e.message if hasattr(e, "message") else e
                errors.append(force_text(msg))
                continue
        if added:
            archive.close()
            buff.flush()
            ret_zip = buff.getvalue()
            buff.close()
            response = HttpResponse(content_type='application/zip')
            response['Content-Disposition'] = 'attachment; filename=order_delivery_pdf.zip'
            response.write(ret_zip)
            return response
        return JsonResponse({"errors": errors})
开发者ID:ruqaiya,项目名称:shuup,代码行数:40,代码来源:mass_actions.py

示例4: process

# 需要导入模块: from six import BytesIO [as 别名]
# 或者: from six.BytesIO import flush [as 别名]
    def process(self, request, ids):
        if isinstance(ids, six.string_types) and ids == "all":
            return JsonResponse({"error": ugettext("Selecting all is not supported.")}, status=400)
        if len(ids) == 1:
            try:
                response = get_confirmation_pdf(request, ids[0])
                response['Content-Disposition'] = 'attachment; filename=order_%s_confirmation.pdf' % ids[0]
                return response
            except Exception as e:
                msg = e.message if hasattr(e, "message") else e
                return JsonResponse({"error": force_text(msg)}, status=400)

        buff = BytesIO()
        archive = zipfile.ZipFile(buff, 'w', zipfile.ZIP_DEFLATED)
        added = 0
        errors = []
        for id in ids:
            try:
                pdf_file = get_confirmation_pdf(request, id)
                filename = "order_%d_confirmation.pdf" % id
                archive.writestr(filename, pdf_file.content)
                added += 1
            except Exception as e:
                msg = e.message if hasattr(e, "message") else e
                errors.append(force_text(msg))
                continue
        if added:
            archive.close()
            buff.flush()
            ret_zip = buff.getvalue()
            buff.close()
            response = HttpResponse(content_type='application/zip')
            response['Content-Disposition'] = 'attachment; filename=order_confirmation_pdf.zip'
            response.write(ret_zip)
            return response
        return JsonResponse({"errors": errors}, status=400)
开发者ID:suutari-ai,项目名称:shuup,代码行数:38,代码来源:mass_actions.py

示例5: TeeInput

# 需要导入模块: from six import BytesIO [as 别名]
# 或者: from six.BytesIO import flush [as 别名]
class TeeInput(object):
    CHUNK_SIZE = conn.CHUNK_SIZE

    def __init__(self, stream):
        self.buf = StringIO()
        self.eof = False

        if isinstance(stream, six.string_types):
            stream = StringIO(stream)
            self.tmp = StringIO()
        else:
            self.tmp = tempfile.TemporaryFile()

        self.stream = stream

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, traceback):
        return

    def seek(self, offset, whence=0):
        """ naive implementation of seek """
        current_size = self._tmp_size()
        diff = 0
        if whence == 0:
            diff = offset - current_size
        elif whence == 2:
            diff = (self.tmp.tell() + offset) - current_size
        elif whence == 3 and not self.eof:
            # we read until the end
            while True:
                self.tmp.seek(0, 2)
                if not self._tee(self.CHUNK_SIZE):
                    break

        if not self.eof and diff > 0:
            self._ensure_length(StringIO(), diff)
        self.tmp.seek(offset, whence)

    def flush(self):
        self.tmp.flush()

    def read(self, length=-1):
        """ read """
        if self.eof:
            return self.tmp.read(length)

        if length < 0:
            buf = StringIO()
            buf.write(self.tmp.read())
            while True:
                chunk = self._tee(self.CHUNK_SIZE)
                if not chunk:
                    break
                buf.write(chunk)
            return buf.getvalue()
        else:
            dest = StringIO()
            diff = self._tmp_size() - self.tmp.tell()
            if not diff:
                dest.write(self._tee(length))
                return self._ensure_length(dest, length)
            else:
                l = min(diff, length)
                dest.write(self.tmp.read(l))
                return self._ensure_length(dest, length)

    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()

    def readlines(self, sizehint=0):
        total = 0
        lines = []
        line = self.readline()
#.........这里部分代码省略.........
开发者ID:pashinin,项目名称:restkit,代码行数:103,代码来源:tee.py


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