1
2
3
4
5
6
7 import mimetypes
8 import os
9 import re
10 import urllib
11
12
13 from restkit.util import to_bytestring, url_quote, url_encode
14
15 MIME_BOUNDARY = 'END_OF_PART'
16 CRLF = '\r\n'
17
21
22
24 - def __init__(self, name, value, fname=None, filetype=None, filesize=None,
25 quote=url_quote):
26 self.quote = quote
27 self.name = quote(name)
28 if value is not None and not hasattr(value, 'read'):
29 value = self.encode_unreadable_value(value)
30 self.size = len(value)
31 self.value = value
32 if fname is not None:
33 if isinstance(fname, unicode):
34 fname = fname.encode("utf-8").encode("string_escape").replace('"', '\\"')
35 else:
36 fname = fname.encode("string_escape").replace('"', '\\"')
37 self.fname = fname
38 if filetype is not None:
39 filetype = to_bytestring(filetype)
40 self.filetype = filetype
41
42 if isinstance(value, file) and filesize is None:
43 try:
44 value.flush()
45 except IOError:
46 pass
47 self.size = int(os.fstat(value.fileno())[6])
48
49 self._encoded_hdr = None
50 self._encoded_bdr = None
51
53 """Returns the header of the encoding of this parameter"""
54 if not self._encoded_hdr or self._encoded_bdr != boundary:
55 boundary = self.quote(boundary)
56 self._encoded_bdr = boundary
57 headers = ["--%s" % boundary]
58 if self.fname:
59 disposition = 'form-data; name="%s"; filename="%s"' % (self.name,
60 self.fname)
61 else:
62 disposition = 'form-data; name="%s"' % self.name
63 headers.append("Content-Disposition: %s" % disposition)
64 if self.filetype:
65 filetype = self.filetype
66 else:
67 filetype = "text/plain; charset=utf-8"
68 headers.append("Content-Type: %s" % filetype)
69 headers.append("Content-Length: %i" % self.size)
70 headers.append("")
71 headers.append("")
72 self._encoded_hdr = CRLF.join(headers)
73 return self._encoded_hdr
74
76 """Returns the string encoding of this parameter"""
77 value = self.value
78 if re.search("^--%s$" % re.escape(boundary), value, re.M):
79 raise ValueError("boundary found in encoded string")
80
81 return "%s%s%s" % (self.encode_hdr(boundary), value, CRLF)
82
84 if not hasattr(self.value, "read"):
85 yield self.encode(boundary)
86 else:
87 yield self.encode_hdr(boundary)
88 while True:
89 block = self.value.read(blocksize)
90 if not block:
91 yield CRLF
92 return
93 yield block
94
97
98
146
147
170