8 buf.update(urlparse.parse_qsl(req.query))
9 if req.ihead.get("Content-Type") == "application/x-www-form-urlencoded":
10 rbody = req.input(2 ** 20)
11 if len(rbody) >= 2 ** 20:
12 raise ValueError("x-www-form-urlencoded data is absurdly long")
13 buf.update(urlparse.parse_qsl(rbody))
16 class badmultipart(Exception):
19 class formpart(object):
20 def __init__(self, form):
29 def fillbuf(self, sz):
31 mboundary = "\r\n--" + self.form.boundary + "\r\n"
32 lboundary = "\r\n--" + self.form.boundary + "--\r\n"
34 p = self.form.buf.find(mboundary)
36 self.buf += self.form.buf[:p]
37 self.form.buf = self.form.buf[p + len(mboundary):]
40 p = self.form.buf.find(lboundary)
42 self.buf += self.form.buf[:p]
43 self.form.buf = self.form.buf[p + len(lboundary):]
47 self.buf += self.form.buf[:-len(lboundary)]
48 self.form.buf = self.form.buf[-len(lboundary):]
49 if sz >= 0 and len(self.buf) >= sz:
51 while len(self.form.buf) <= len(lboundary):
52 ret = req.input.read(8192)
54 raise badmultipart("Missing last multipart boundary")
57 def read(self, limit=-1):
60 ret = self.buf[:limit]
61 self.buf = self.buf[limit:]
67 def readline(self, limit=-1):
70 p = self.buf.find('\n', last)
77 self.fillbuf(last + 128)
79 ret = self.buf[:p + 1]
80 self.buf = self.buf[p + 1:]
89 def __exit__(self, *excinfo):
95 ln = self.readline(256)
97 raise badmultipart("Too long header line in part")
107 if not ln[1:].isspace():
112 raise badmultipart("Malformed multipart header line")
113 self.head[buf[:p].strip().lower()] = buf[p + 1:].lstrip()
115 val, par = proto.pmimehead(self.head.get("content-disposition", ""))
116 if val != "form-data":
117 raise badmultipart("Unexpected Content-Disposition in form part: %r" % val)
118 if not "name" in par:
119 raise badmultipart("Missing name in form part")
120 self.name = par["name"]
121 self.filename = par.get("filename")
122 val, par = proto.pmimehead(self.head.get("content-type", ""))
124 self.charset = par.get("charset")
125 encoding = self.head.get("content-transfer-encoding", "binary")
126 if encoding != "binary":
127 raise badmultipart("Form part uses unexpected transfer encoding: %r" % encoding)
129 class multipart(object):
130 def __init__(self, req):
131 val, par = proto.pmimehead(req.ihead.get("Content-Type", ""))
132 if req.method != "POST" or val != "multipart/form-data":
133 raise badmultipart("Request is not a multipart form")
134 if "boundary" not in par:
135 raise badmultipart("Multipart form lacks boundary")
136 self.boundary = par["boundary"]
140 self.lastpart = formpart(self)
141 self.lastpart.close()
147 if not self.lastpart.eof:
148 raise RuntimeError("All form parts must be read entirely")
150 raise StopIteration()
151 self.lastpart = formpart(self)
152 self.lastpart.parsehead()
156 return req.item(formparse)