forked from cms-sw/cmsdist
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cherrypy-upload.patch
265 lines (250 loc) · 10.8 KB
/
cherrypy-upload.patch
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
From: Lassi Tuura <[email protected]>
Date: 2011-09-16 00:39:21 +0200
Subject: Add test to measure upload performance.
---
cherrypy/test/test_upload.py | 72 ++++++++++++++++++++++++++++++++++++++++++
1 files changed, 72 insertions(+), 0 deletions(-)
create mode 100644 cherrypy/test/test_upload.py
diff --git a/cherrypy/test/test_upload.py b/cherrypy/test/test_upload.py
new file mode 100644
index 0000000..f0c983c
--- /dev/null
+++ b/cherrypy/test/test_upload.py
@@ -0,0 +1,72 @@
+from cherrypy.test import test
+test.prefer_parent_path()
+
+import cherrypy, time, httplib, os, sys
+from cherrypy.test import helper
+
+def setup_server():
+ class Root:
+ @cherrypy.expose
+ def put(self, size, xtra, file):
+ assert xtra == 'foo'
+ now = time.time()
+ filelen = 0
+ while True:
+ data = file.file.read(8*1024*1024)
+ if not data: break
+ filelen += len(data)
+ cherrypy.response.headers["X-Timing"] = "%.3f" % (time.time() - now)
+ return "thanks len %d orig %d file '%s'" % (int(size), filelen, file.filename)
+
+ bufsize = int(os.environ.get("BODY_IO_SIZE", 1<<19))
+ cherrypy.tree.mount(Root(), "/small", config={'/': {}})
+ cherrypy.tree.mount(Root(), "/big", config={'/': {'request.body_io_size': bufsize}})
+ cherrypy.config.update({'server.max_request_body_size': 0, 'environment': 'test_suite'})
+
+class UploadTest(helper.CPWebCase):
+ def _encode(self, args, files, with_length):
+ body, crlf = '', '\r\n'
+ boundary = 'TEST'
+ for key, value in args.iteritems():
+ body += '--' + boundary + crlf
+ body += ('Content-Disposition: form-data; name="%s"' % key) + crlf
+ body += crlf + str(value) + crlf
+ for key, file in files.iteritems():
+ filename, filedata = file
+ body += '--' + boundary + crlf
+ body += ('Content-Disposition: form-data; name="%s"; filename="%s"'
+ % (key, filename)) + crlf
+ body += ('Content-Type: application/octet-stream') + crlf
+ if with_length:
+ body += ('Content-Length: %d' % len(filedata)) + crlf
+ body += crlf + filedata + crlf
+ body += '--' + boundary + '--' + crlf + crlf
+ return 'multipart/form-data; boundary=' + boundary, body
+
+ def _marshall(self, name, kbytes, with_length):
+ data = ("x" * 127 + "\n") * 8 * kbytes
+ args = { 'size': len(data), 'xtra': 'foo' }
+ files = { 'file': (name, data) }
+ type, body = self._encode(args, files, with_length)
+ headers = [('Content-Type', type), ('Content-Length', len(body))]
+ return headers, body
+
+ def _run_test(self, kind, kbytes, with_length):
+ nbytes = kbytes*1024
+ headers, body = self._marshall(kind + 'file', kbytes, with_length)
+ start = time.time()
+ self.getPage("/%s/put" % kind, method='POST', headers = headers, body = body)
+ self.assertStatus(200)
+ self.assertBody("thanks len %d orig %d file '%sfile'" % (nbytes, nbytes, kind))
+ self.assertHeader("X-Timing")
+ xtiming = [v for k, v in self.headers if k.lower() == "x-timing"][0]
+ print "time(client=%.3f server=%s)" % (time.time() - start, xtiming),
+
+ def test_small_smart(self): self._run_test('small', 10, True)
+ def test_small_dumb(self): self._run_test('small', 10, False)
+ def test_big_smart(self): self._run_test('big', 500*1024, True)
+ def test_big_dumb(self): self._run_test('big', 500*1024, False)
+
+if __name__ == "__main__":
+ setup_server()
+ helper.testmain()
From: Lassi Tuura <[email protected]>
Date: 2011-09-15 21:38:39 +0200
Subject: Parametrise the buffer size used for reading multipart body.
---
cherrypy/_cpcgifs.py | 2 ++
cherrypy/_cprequest.py | 10 +++++++++-
2 files changed, 11 insertions(+), 1 deletions(-)
diff --git a/cherrypy/_cpcgifs.py b/cherrypy/_cpcgifs.py
index 3eb5dd8..f1c1f15 100644
--- a/cherrypy/_cpcgifs.py
+++ b/cherrypy/_cpcgifs.py
@@ -5,6 +5,8 @@ import cherrypy
class FieldStorage(cgi.FieldStorage):
def __init__(self, *args, **kwds):
try:
+ size = kwds.get('environ', {}).get('_bufsize', None)
+ if size: cgi.FieldStorage.bufsize = size
cgi.FieldStorage.__init__(self, *args, **kwds)
except ValueError, ex:
if str(ex) == 'Maximum content length exceeded':
diff --git a/cherrypy/_cprequest.py b/cherrypy/_cprequest.py
index 23bdad2..83e8cdf 100644
--- a/cherrypy/_cprequest.py
+++ b/cherrypy/_cprequest.py
@@ -301,6 +301,12 @@ class Request(object):
can be sent with various HTTP method verbs). This value is set between
the 'before_request_body' and 'before_handler' hooks (assuming that
process_request_body is True)."""
+
+ body_io_size = _cpcgifs.FieldStorage.bufsize
+ body_io_size__doc = """
+ The I/O chunk size for reading multipart body content. The default is
+ suitable for small POST params, but for servers regularly receiving
+ large file uploads it is a good idea to increase this substantially."""
# Dispatch attributes
dispatch = cherrypy.dispatch.Dispatcher()
@@ -715,10 +721,12 @@ class Request(object):
h = self.headers
try:
+ self.rfile.rfile.default_bufsize = max(1<<16, self.body_io_size)
forms = _cpcgifs.FieldStorage(fp=self.rfile,
headers=h,
# FieldStorage only recognizes POST.
- environ={'REQUEST_METHOD': "POST"},
+ environ={'REQUEST_METHOD': "POST",
+ '_bufsize': self.body_io_size},
keep_blank_values=1)
except Exception, e:
if e.__class__.__name__ == 'MaxSizeExceeded':
From: Lassi Tuura <[email protected]>
Date: 2011-09-15 21:39:31 +0200
Subject: Avoid buffer object churn when reading in request body.
---
cherrypy/wsgiserver/__init__.py | 37 ++++++++++++++++++++-----------------
1 files changed, 20 insertions(+), 17 deletions(-)
diff --git a/cherrypy/wsgiserver/__init__.py b/cherrypy/wsgiserver/__init__.py
index c380e18..94d3438 100644
--- a/cherrypy/wsgiserver/__init__.py
+++ b/cherrypy/wsgiserver/__init__.py
@@ -721,6 +721,7 @@ class FatalSSLAlert(Exception):
if not _fileobject_uses_str_type:
class CP_fileobject(socket._fileobject):
"""Faux file object attached to a socket object."""
+ __read_pos = 0
def sendall(self, data):
"""Sendall for non-blocking sockets."""
@@ -754,6 +755,7 @@ if not _fileobject_uses_str_type:
# Use max, disallow tiny reads in a loop as they are very inefficient.
# We never leave read() with any leftover data from a new recv() call
# in our internal buffer.
+ pos = self.__read_pos
rbufsize = max(self._rbufsize, self.default_bufsize)
# Our use of StringIO rather than lists of string objects returned by
# recv() minimizes memory usage and fragmentation that occurs when
@@ -762,24 +764,25 @@ if not _fileobject_uses_str_type:
buf.seek(0, 2) # seek end
if size < 0:
# Read until EOF
+ self.__read_pos = 0
self._rbuf = StringIO.StringIO() # reset _rbuf. we consume it via buf.
while True:
data = self.recv(rbufsize)
if not data:
break
buf.write(data)
- return buf.getvalue()
+ return buf.getvalue()[pos:]
else:
# Read until size bytes or EOF seen, whichever comes first
- buf_len = buf.tell()
+ buf_len = buf.tell()-pos
if buf_len >= size:
# Already have size bytes in our buffer? Extract and return.
- buf.seek(0)
+ buf.seek(pos)
rv = buf.read(size)
- self._rbuf = StringIO.StringIO()
- self._rbuf.write(buf.read())
+ self.__read_pos = buf.tell()
return rv
+ self.__read_pos = 0
self._rbuf = StringIO.StringIO() # reset _rbuf. we consume it via buf.
while True:
left = size - buf_len
@@ -808,25 +811,26 @@ if not _fileobject_uses_str_type:
buf_len += n
del data # explicit free
#assert buf_len == buf.tell()
- return buf.getvalue()
+ return buf.getvalue()[pos:]
def readline(self, size=-1):
+ pos = self.__read_pos
buf = self._rbuf
buf.seek(0, 2) # seek end
- if buf.tell() > 0:
+ if buf.tell()-pos > 0:
# check if we already have it in our buffer
- buf.seek(0)
+ buf.seek(pos)
bline = buf.readline(size)
if bline.endswith('\n') or len(bline) == size:
- self._rbuf = StringIO.StringIO()
- self._rbuf.write(buf.read())
+ self.__read_pos = buf.tell()
return bline
del bline
+ self.__read_pos = 0
if size < 0:
# Read until \n or EOF, whichever comes first
if self._rbufsize <= 1:
# Speed up unbuffered case
- buf.seek(0)
+ buf.seek(pos)
buffers = [buf.read()]
self._rbuf = StringIO.StringIO() # reset _rbuf. we consume it via buf.
data = None
@@ -852,16 +856,15 @@ if not _fileobject_uses_str_type:
del data
break
buf.write(data)
- return buf.getvalue()
+ return buf.getvalue()[pos:]
else:
# Read until size bytes or \n or EOF seen, whichever comes first
buf.seek(0, 2) # seek end
- buf_len = buf.tell()
+ buf_len = buf.tell()-pos
if buf_len >= size:
- buf.seek(0)
+ buf.seek(pos)
rv = buf.read(size)
- self._rbuf = StringIO.StringIO()
- self._rbuf.write(buf.read())
+ self.__read_pos = buf.tell()
return rv
self._rbuf = StringIO.StringIO() # reset _rbuf. we consume it via buf.
while True:
@@ -894,7 +897,7 @@ if not _fileobject_uses_str_type:
buf.write(data)
buf_len += n
#assert buf_len == buf.tell()
- return buf.getvalue()
+ return buf.getvalue()[pos:]
else:
class CP_fileobject(socket._fileobject):