Last active
September 19, 2021 18:08
-
-
Save pipex/f5dc5fa8906b23510b28 to your computer and use it in GitHub Desktop.
Support Chunked Transfer Encoding in Flask
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from flask import Flask | |
MAX_CONTENT_LENGTH = 16 * 1024 * 1024 | |
app = Flask(__name__) | |
app.config['MAX_CONTENT_LENGTH'] = MAX_CONTENT_LENGTH | |
class WSGITransferEncodingChunked: | |
"""Support HTTP Transfer-Encoding: chunked transfers""" | |
def __init__(self, app): | |
self.app = app | |
def __call__(self, environ, start_response): | |
from cStringIO import StringIO | |
input = environ.get('wsgi.input') | |
length = environ.get('CONTENT_LENGTH', '0') | |
length = 0 if length == '' else int(length) | |
body = '' | |
if length == 0: | |
if input is None: | |
return | |
if environ.get('HTTP_TRANSFER_ENCODING','0') == 'chunked': | |
size = int(input.readline(),16) | |
total_size = 0 | |
while size > 0: | |
# Validate max size to avoid DoS attacks | |
total_size += size | |
if total_size > MAX_CONTENT_LENGTH: | |
# Avoid DoS (using all available memory by streaming an infinite file) | |
start_response('413 Request Entity Too Large', [('Content-Type', 'text/plain')]) | |
return [] | |
body += input.read(size+2) | |
size = int(input.readline(),16) | |
else: | |
body = environ['wsgi.input'].read(length) | |
environ["CONTENT_LENGTH"] = str(len(body)) | |
environ['wsgi.input'] = StringIO(body) | |
return self.app(environ, start_response) | |
# Setup wsgi app | |
app.wsgi_app = WSGITransferEncodingChunked(app.wsgi_app) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Source http://stackoverflow.com/questions/14146824/flask-and-transfer-encoding-chunked/21342631#21342631