The input stream has no end-of-file marker. If you would call theread() method on the wsgi.input stream you would cause yourapplication to hang on conforming servers. This is actually intentionalhowever painful. Werkzeug solves that problem by wrapping the inputstream in a special LimitedStream. The input stream is exposedon the request objects as stream. This one is eitheran empty stream (if the form data was parsed) or a limited stream withthe contents of the input stream.
Werkzeug parses the incoming data under the following situations:
These calls are not interchangeable. If you invoke parse_form_data()you must not use the request object or at least not the attributes thattrigger the parsing process.
This is also true if you read from the wsgi.input stream before theparsing.
General rule: Leave the WSGI input stream alone. Especially inWSGI middlewares. Use either the parsing functions or the requestobject. Do not mix multiple WSGI utility libraries for form dataparsing or anything else that works on the input stream.
The standard Werkzeug parsing behavior handles three cases:
Special note on the get_data method: Calling thisloads the full request data into memory. This is only safe to do if themax_content_length is set. Also you can eitherread the stream or call get_data().
To avoid being the victim of a DDOS attack you can set the maximumaccepted content length and request field sizes. The BaseRequestclass has two attributes for that: max_content_lengthand max_form_memory_size.
The first one can be used to limit the total content length. For exampleby setting it to 1024102416 the request won't accept more than16MB of transmitted data.
Because certain data can't be moved to the hard disk (regular post data)whereas temporary files can, there is a second limit you can set. Themax_form_memory_size limits the size of POSTtransmitted form data. By setting it to 102410242 you can makesure that all in memory-stored fields is not more than 2MB in size.
This however does not affect in-memory stored files if thestream_factory used returns a in-memory file.
Modern web applications transmit a lot more than multipart form data orurl encoded data. Extending the parsing capabilities by subclassingthe BaseRequest is simple. The following example implementsparsing for incoming JSON data:
from werkzeug.utils import cached_property
from werkzeug.wrappers import Request
from simplejson import loads
class JSONRequest(Request):
# accept up to 4MB of transmitted data.
max_content_length = 1024 * 1024 * 4
@cached_property
def json(self):
if self.headers.get('content-type') == 'application/json':
return loads(self.data)
更多建議: