Multipart formdata builder py3

 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
__author__ = 'Sergey Snegirev <tz4678@gmail.com>'

import uuid, mimetypes, os

CRLF = b'\r\n'
DASH = b'--'
EMPTY_LINE = b''
CONTENT_DISPOSITION_HEADER = b'Content-Disposition: form-data; name='
FILENAME_HEADER = b'; filename='
CONTENT_TYPE_HEADER = b'Content-Type: '
DEFAULT_CONTENT_TYPE = 'application/octeat-stream'

class MultipartBuilder(object):
    def __init__(self, encoding='utf-8'):
        self._encoding = encoding
        self._boundary = self._make_boundary()
        self._content_type = \
        'multipart/form-data; boundary={}'.format(self.boundary)
        self._dash_boundary = DASH + self.boundary.encode('utf-8')
        self._close_boundary = self._dash_boundary + DASH
        self._lines = []

    @property
    def encoding(self):
        return self._encoding

    @property
    def boundary(self):
        return self._boundary

    @property
    def content_type(self):
        return self._content_type

    def _make_boundary(self):
        return uuid.uuid4().hex

    def _encode(self, s):
        return s.encode(self.encoding, 'replace')

    def _quote_encode(self, s):
        return self._encode('"{}"'.format(
            s.replace('\n', '%0A').replace('\r', '%0D').replace('"', '%22')))

    def _add(self, name, data, filename, content_type):
        self._lines.append(self._dash_boundary)
        name = self._quote_encode(name)
        disposition = CONTENT_DISPOSITION_HEADER + name

        if filename:
            disposition += FILENAME_HEADER + self._quote_encode(filename)

        self._lines.append(disposition)

        if content_type:
            content_type = content_type.encode('utf-8')
            self._lines.append(CONTENT_TYPE_HEADER + content_type)

        # каждый раз вызывать l.append(item) быстрее чем l.extend([item1, ...])
        self._lines.append(EMPTY_LINE)
        self._lines.append(data)

    def add_field(self, name, value=''):
        self._add(name, self._encode(value), None, None)

    def add_file(self, name, filename, content=None, content_type=None):
        if content is None:
            with open(filename, 'rb') as fp:
                content = fp.read()    
        elif hasattr(content, 'read'):
            content = content.read()

        filename = os.path.basename(filename)

        if content_type is None:
            content_type = mimetypes.guess_type(filename)[0]

        content_type = content_type or DEFAULT_CONTENT_TYPE
        self._add(name, content, filename, content_type)

    def build(self):
        # --%boundary%--\r\n\r\n
        self._lines.append(self._close_boundary)
        self._lines.append(EMPTY_LINE)
        self._lines.append(EMPTY_LINE)
        # это намного быстрее конкатенации строк + не происходит копирования
        # строки каждый раз
        body = CRLF.join(self._lines)
        self._lines = None
        return body
11 марта 2015, 18:11 0 tz4678@gmail.com
blog comments powered by Disqus