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


Python brotli.compress方法代碼示例

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


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

示例1: CompressBrotli

# 需要導入模塊: import brotli [as 別名]
# 或者: from brotli import compress [as 別名]
def CompressBrotli(string):
    """
    CompressBrotli(string) -> str
    Returns without delimiters the given string compressed \
using Google's brotli compression method.

    """
    compressed = brotli.compress(string.encode("ascii"))
    number = 1
    for c in compressed:
        number = number * 256 + c
    result = ""
    while number:
        result = Codepage[number % 255] + result
        number //= 255
    return Codepage[BROTLI_ENCODING] + result 
開發者ID:somebody1234,項目名稱:Charcoal,代碼行數:18,代碼來源:compression.py

示例2: CompressLZMA

# 需要導入模塊: import brotli [as 別名]
# 或者: from brotli import compress [as 別名]
def CompressLZMA(string):
    """
    CompressBrotli(string) -> str
    Returns without delimiters the given string compressed \
using the lzstring compression method.

    """
    compressed = lzma.compress(
        string.encode("ascii"),
        format=lzma.FORMAT_RAW,
        filters=[{'id': lzma.FILTER_LZMA2, 'preset': 9 | lzma.PRESET_EXTREME}]
    )
    number = 1
    for c in compressed:
        number = number * 256 + c
    result = ""
    while number:
        result = Codepage[number % 255] + result
        number //= 255
    return Codepage[LZMA_ENCODING] + result 
開發者ID:somebody1234,項目名稱:Charcoal,代碼行數:22,代碼來源:compression.py

示例3: post_build

# 需要導入模塊: import brotli [as 別名]
# 或者: from brotli import compress [as 別名]
def post_build(self, pkt, pay):
        if not conf.contribs["http"]["auto_compression"]:
            return pkt + pay
        encodings = self._get_encodings()
        # Compress
        if "deflate" in encodings:
            import zlib
            pay = zlib.compress(pay)
        elif "gzip" in encodings:
            pay = gzip_compress(pay)
        elif "compress" in encodings:
            import lzw
            pay = lzw.compress(pay)
        elif "br" in encodings and is_brotli_available:
            pay = brotli.compress(pay)
        return pkt + pay 
開發者ID:secdev,項目名稱:scapy,代碼行數:18,代碼來源:http.py

示例4: compress

# 需要導入模塊: import brotli [as 別名]
# 或者: from brotli import compress [as 別名]
def compress(content, method='gzip', compress_level=None):
  """
  Compresses file content.

  Required:
    content (bytes): The information to be compressed
    method (str, default: 'gzip'): None or gzip
  Raises: 
    NotImplementedError if an unsupported codec is specified. 
    compression.DecodeError if the encoder has an issue

  Return: compressed content
  """
  if method == True:
    method = 'gzip' # backwards compatibility

  method = (method or '').lower()

  if method == '':
    return content
  elif method == 'gzip': 
    return gzip_compress(content, compresslevel=compress_level)
  elif method == 'br':
    return brotli_compress(content, quality=compress_level)
  raise NotImplementedError(str(method) + ' is not currently supported. Supported Options: None, gzip') 
開發者ID:seung-lab,項目名稱:cloud-volume,代碼行數:27,代碼來源:compression.py

示例5: test_streaming_compression

# 需要導入模塊: import brotli [as 別名]
# 或者: from brotli import compress [as 別名]
def test_streaming_compression(one_compressed_file,
                               chunk_size,
                               mode,
                               quality,
                               lgwin,
                               lgblock):
    """
    Confirm that the streaming compressor works as expected.
    """
    compressed_chunks = []
    c = brotli.Compressor(
        mode=mode, quality=quality, lgwin=lgwin, lgblock=lgblock
    )
    with open(one_compressed_file, 'rb') as f:
        while True:
            next_data = f.read(chunk_size)
            if not next_data:
                break

            compressed_chunks.append(c.compress(next_data))

    compressed_chunks.append(c.finish())
    decompressed = brotli.decompress(b''.join(compressed_chunks))
    with open(one_compressed_file, 'rb') as f:
        assert decompressed == f.read() 
開發者ID:python-hyper,項目名稱:brotlipy,代碼行數:27,代碼來源:test_simple_compression.py

示例6: _calcFlavorDataOffsetsAndSize

# 需要導入模塊: import brotli [as 別名]
# 或者: from brotli import compress [as 別名]
def _calcFlavorDataOffsetsAndSize(self, start):
		"""Calculate offsets and lengths for any meta- and/or private data."""
		offset = start
		data = self.flavorData
		if data.metaData:
			self.metaOrigLength = len(data.metaData)
			self.metaOffset = offset
			self.compressedMetaData = brotli.compress(
				data.metaData, mode=brotli.MODE_TEXT)
			self.metaLength = len(self.compressedMetaData)
			offset += self.metaLength
		else:
			self.metaOffset = self.metaLength = self.metaOrigLength = 0
			self.compressedMetaData = b""
		if data.privData:
			# make sure private data is padded to 4-byte boundary
			offset = (offset + 3) & ~3
			self.privOffset = offset
			self.privLength = len(data.privData)
			offset += self.privLength
		else:
			self.privOffset = self.privLength = 0
		return offset 
開發者ID:MitchTalmadge,項目名稱:Emoji-Tools,代碼行數:25,代碼來源:woff2.py

示例7: post_dissect

# 需要導入模塊: import brotli [as 別名]
# 或者: from brotli import compress [as 別名]
def post_dissect(self, s):
        if not conf.contribs["http"]["auto_compression"]:
            return s
        encodings = self._get_encodings()
        # Un-chunkify
        if "chunked" in encodings:
            data = b""
            while s:
                length, _, body = s.partition(b"\r\n")
                try:
                    length = int(length, 16)
                except ValueError:
                    # Not a valid chunk. Ignore
                    break
                else:
                    load = body[:length]
                    if body[length:length + 2] != b"\r\n":
                        # Invalid chunk. Ignore
                        break
                    s = body[length + 2:]
                    data += load
            if not s:
                s = data
        # Decompress
        try:
            if "deflate" in encodings:
                import zlib
                s = zlib.decompress(s)
            elif "gzip" in encodings:
                s = gzip_decompress(s)
            elif "compress" in encodings:
                import lzw
                s = lzw.decompress(s)
            elif "br" in encodings and is_brotli_available:
                s = brotli.decompress(s)
        except Exception:
            # Cannot decompress - probably incomplete data
            pass
        return s 
開發者ID:secdev,項目名稱:scapy,代碼行數:41,代碼來源:http.py

示例8: encode_image_url

# 需要導入模塊: import brotli [as 別名]
# 或者: from brotli import compress [as 別名]
def encode_image_url(url, referer=None):
    try:
        text = json.dumps(validate_image_url(dict(url=url, referer=referer)))
        data = brotli.compress(text.encode('utf-8'), quality=6)
        return base64.urlsafe_b64encode(data).decode()
    except (Invalid, json.JSONDecodeError, brotli.error, UnicodeEncodeError) as ex:
        raise ImageUrlEncodeError(str(ex)) from ex 
開發者ID:anyant,項目名稱:rssant,代碼行數:9,代碼來源:image_url.py

示例9: verify_and_get_compress_func

# 需要導入模塊: import brotli [as 別名]
# 或者: from brotli import compress [as 別名]
def verify_and_get_compress_func(compression_type, compression_level=9):
    # type: (str, int) -> Optional[Callable]
    """
    Given a compression_type (bz2, zlib, lz4, zstandard), verify that compression works and return
    the compress() function with compression level pre-applied.

    @param compression_type: Compression type.
    @type compression_type: str

    @param compression_level: Compression level to use.
    @ type: compression_level: int

    @returns: The compress() function for the specified compression_type. None, if compression_type
        is not supported or if underlying libs are not installed properly,
    """
    if compression_type not in SUPPORTED_COMPRESSION_ALGORITHMS:
        return None

    try:
        compress_func, decompress_func = get_compress_and_decompress_func(
            compression_type, compression_level=compression_level
        )

        # Perform a sanity check that data compresses and that it can be decompressed
        cdata = compress_func(COMPRESSION_TEST_STR)

        if (
            len(cdata) < len(COMPRESSION_TEST_STR)
            and decompress_func(cdata) == COMPRESSION_TEST_STR
        ):
            return compress_func
    except Exception:
        pass

    return None 
開發者ID:scalyr,項目名稱:scalyr-agent-2,代碼行數:37,代碼來源:util.py

示例10: brotli_compress

# 需要導入模塊: import brotli [as 別名]
# 或者: from brotli import compress [as 別名]
def brotli_compress(content, quality=None):
  if quality is None:
    # 5/6 are good balance between compression speed and compression rate
    quality = 5
  return brotli.compress(content, quality=quality) 
開發者ID:seung-lab,項目名稱:cloud-volume,代碼行數:7,代碼來源:compression.py

示例11: test_roundtrip_compression_with_files

# 需要導入模塊: import brotli [as 別名]
# 或者: from brotli import compress [as 別名]
def test_roundtrip_compression_with_files(simple_compressed_file):
    """
    Roundtripping data through the compressor works correctly.
    """
    with open(simple_compressed_file[0], 'rb') as f:
        uncompressed_data = f.read()

    assert brotli.decompress(
        brotli.compress(uncompressed_data)
    ) == uncompressed_data 
開發者ID:python-hyper,項目名稱:brotlipy,代碼行數:12,代碼來源:test_simple_compression.py

示例12: test_streaming_compression_flush

# 需要導入模塊: import brotli [as 別名]
# 或者: from brotli import compress [as 別名]
def test_streaming_compression_flush(one_compressed_file,
                                     chunk_size,
                                     mode,
                                     quality,
                                     lgwin,
                                     lgblock):
    """
    Confirm that the streaming compressor works as expected, including flushes
    after each chunk.
    """
    compressed_chunks = []
    c = brotli.Compressor(
        mode=mode, quality=quality, lgwin=lgwin, lgblock=lgblock
    )
    with open(one_compressed_file, 'rb') as f:
        while True:
            next_data = f.read(chunk_size)
            if not next_data:
                break

            compressed_chunks.append(c.compress(next_data))
            compressed_chunks.append(c.flush())

    compressed_chunks.append(c.finish())
    decompressed = brotli.decompress(b''.join(compressed_chunks))
    with open(one_compressed_file, 'rb') as f:
        assert decompressed == f.read() 
開發者ID:python-hyper,項目名稱:brotlipy,代碼行數:29,代碼來源:test_simple_compression.py

示例13: test_compressed_data_roundtrips

# 需要導入模塊: import brotli [as 別名]
# 或者: from brotli import compress [as 別名]
def test_compressed_data_roundtrips(s):
    assert brotli.decompress(brotli.compress(s)) == s 
開發者ID:python-hyper,項目名稱:brotlipy,代碼行數:4,代碼來源:test_simple_compression.py

示例14: test_compressed_data_with_dictionaries

# 需要導入模塊: import brotli [as 別名]
# 或者: from brotli import compress [as 別名]
def test_compressed_data_with_dictionaries(s, dictionary):
    d = brotli.Decompressor(dictionary)
    compressed = brotli.compress(s, dictionary=dictionary)
    uncompressed = d.decompress(compressed)
    assert uncompressed == s 
開發者ID:python-hyper,項目名稱:brotlipy,代碼行數:7,代碼來源:test_simple_compression.py

示例15: setUpClass

# 需要導入模塊: import brotli [as 別名]
# 或者: from brotli import compress [as 別名]
def setUpClass(cls):
		assert os.path.exists(METADATA)
		with open(METADATA, 'rb') as f:
			cls.xml_metadata = f.read()
		cls.compressed_metadata = brotli.compress(cls.xml_metadata, mode=brotli.MODE_TEXT)
		# make random byte strings; font data must be 4-byte aligned
		cls.fontdata = bytes(bytearray(random.sample(range(0, 256), 80)))
		cls.privData = bytes(bytearray(random.sample(range(0, 256), 20))) 
開發者ID:MitchTalmadge,項目名稱:Emoji-Tools,代碼行數:10,代碼來源:woff2_test.py


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