1+Request Content Checksums2+=========================3+4+Various pieces of code can consume the request data and preprocess it.5+For instance JSON data ends up on the request object already read and6+processed, form data ends up there as well but goes through a different7+code path. This seems inconvenient when you want to calculate the8+checksum of the incoming request data. This is necessary sometimes for9+some APIs.10+11+Fortunately this is however very simple to change by wrapping the input12+stream.13+14+The following example calculates the SHA1 checksum of the incoming data as15+it gets read and stores it in the WSGI environment::16+17+ import hashlib18+19+ class ChecksumCalcStream(object):20+21+ def __init__(self, stream):22+ self._stream = stream23+ self._hash = hashlib.sha1()24+25+ def read(self, bytes):26+ rv = self._stream.read(bytes)27+ self._hash.update(rv)28+ return rv29+30+ def readline(self, size_hint):31+ rv = self._stream.readline(size_hint)32+ self._hash.update(rv)33+ return rv34+35+ def generate_checksum(request):36+ env = request.environ37+ stream = ChecksumCalcStream(env['wsgi.input'])38+ env['wsgi.input'] = stream39+ return stream._hash40+41+To use this, all you need to do is to hook the calculating stream in42+before the request starts consuming data. (Eg: be careful accessing43+``request.form`` or anything of that nature. ``before_request_handlers``44+for instance should be careful not to access it).45+46+Example usage::47+48+ @app.route('/special-api', methods=['POST'])49+ def special_api():50+ hash = generate_checksum(request)51+ # Accessing this parses the input stream52+ files = request.files53+ # At this point the hash is fully constructed.54+ checksum = hash.hexdigest()55+ return 'Hash was: %s' % checksum