-
Notifications
You must be signed in to change notification settings - Fork 0
/
helpers.py
50 lines (36 loc) · 1.14 KB
/
helpers.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# -*- coding: utf-8 -*-
import bz2
POST_PARAM_NAME = 'string'
# Available request actions
class Action:
COMPRESS = 'compress'
DECOMPRESS = 'decompress'
allowed = (COMPRESS, DECOMPRESS)
class Processor(object):
"""
Compress/decompress of a file-like object content
"""
CHUNK_SIZE = 32
def __init__(self, buffer_object, action):
self.buffer = buffer_object
self.action = action
def process(self):
"""
Compression/decompression
"""
processor = (bz2.BZ2Compressor() if self.action == Action.COMPRESS
else bz2.BZ2Decompressor())
# Processor method depends on action
action = getattr(processor, self.action)
# Reading request and responding by chunks
while True:
block = self.buffer.read(self.CHUNK_SIZE)
if not block:
break
# Actual compression/decompression
processed = action(block)
if processed:
yield processed
# Flush compression buffer
if self.action == Action.COMPRESS:
yield processor.flush()