limiter.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. # -*- coding: utf-8 -*-
  2. """
  3. werkzeug.contrib.limiter
  4. ~~~~~~~~~~~~~~~~~~~~~~~~
  5. A middleware that limits incoming data. This works around problems with
  6. Trac_ or Django_ because those directly stream into the memory.
  7. .. _Trac: http://trac.edgewall.org/
  8. .. _Django: http://www.djangoproject.com/
  9. :copyright: (c) 2014 by the Werkzeug Team, see AUTHORS for more details.
  10. :license: BSD, see LICENSE for more details.
  11. """
  12. from warnings import warn
  13. from werkzeug.wsgi import LimitedStream
  14. class StreamLimitMiddleware(object):
  15. """Limits the input stream to a given number of bytes. This is useful if
  16. you have a WSGI application that reads form data into memory (django for
  17. example) and you don't want users to harm the server by uploading tons of
  18. data.
  19. Default is 10MB
  20. .. versionchanged:: 0.9
  21. Deprecated middleware.
  22. """
  23. def __init__(self, app, maximum_size=1024 * 1024 * 10):
  24. warn(DeprecationWarning('This middleware is deprecated'))
  25. self.app = app
  26. self.maximum_size = maximum_size
  27. def __call__(self, environ, start_response):
  28. limit = min(self.maximum_size, int(environ.get('CONTENT_LENGTH') or 0))
  29. environ['wsgi.input'] = LimitedStream(environ['wsgi.input'], limit)
  30. return self.app(environ, start_response)