1
2
3
4
5
6
7 import mimetypes
8 import os
9 import re
10 import urllib
11
12
13 from .util import to_bytestring, url_quote
14
15 MIME_BOUNDARY = 'END_OF_PART'
16
23
24
26 - def __init__(self, name, value, fname=None, filetype=None, filesize=None):
27 self.name = url_quote(name)
28 if value is not None and not hasattr(value, 'read'):
29 value = url_quote(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
50 """Returns the header of the encoding of this parameter"""
51 boundary = url_quote(boundary)
52 headers = ["--%s" % boundary]
53 if self.fname:
54 disposition = 'form-data; name="%s"; filename="%s"' % (self.name,
55 self.fname)
56 else:
57 disposition = 'form-data; name="%s"' % self.name
58 headers.append("Content-Disposition: %s" % disposition)
59 if self.filetype:
60 filetype = self.filetype
61 else:
62 filetype = "text/plain; charset=utf-8"
63 headers.append("Content-Type: %s" % filetype)
64 headers.append("Content-Length: %i" % self.size)
65 headers.append("")
66 headers.append("")
67 return "\r\n".join(headers)
68
70 """Returns the string encoding of this parameter"""
71 value = self.value
72 if re.search("^--%s$" % re.escape(boundary), value, re.M):
73 raise ValueError("boundary found in encoded string")
74
75 return "%s%s\r\n" % (self.encode_hdr(boundary), value)
76
78 if not hasattr(self.value, "read"):
79 yield self.encode(boundary)
80 else:
81 yield self.encode_hdr(boundary)
82 while True:
83 block = self.value.read(blocksize)
84 if not block:
85 yield "\r\n"
86 break
87 yield block
88
89
131
132
140