Skip to content
Myr

Added a new example for checksums on input data. This fixes #601

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Armin Ronacher · committed by Armin Ronacher · parent c4f2075 · Browse files · 2 files+56 added−0 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+56 added−0 removed

  • other:+56 added−0 removed

2 files+56 added−0 removed

modified:docs/patterns/index.rst+1 added
36 unmodified lines
37 favicon38 streaming39 deferredcallbacks40 methodoverrides41 requestchecksum
added:docs/patterns/requestchecksum.rst+55 added
1Request Content Checksums2=========================34Various pieces of code can consume the request data and preprocess it.5For instance JSON data ends up on the request object already read and6processed, form data ends up there as well but goes through a different7code path. This seems inconvenient when you want to calculate the8checksum of the incoming request data. This is necessary sometimes for9some APIs.1011Fortunately this is however very simple to change by wrapping the input12stream.1314The following example calculates the SHA1 checksum of the incoming data as15it gets read and stores it in the WSGI environment::1617 import hashlib1819 class ChecksumCalcStream(object):2021 def __init__(self, stream):22 self._stream = stream23 self._hash = hashlib.sha1()2425 def read(self, bytes):26 rv = self._stream.read(bytes)27 self._hash.update(rv)28 return rv2930 def readline(self, size_hint):31 rv = self._stream.readline(size_hint)32 self._hash.update(rv)33 return rv3435 def generate_checksum(request):36 env = request.environ37 stream = ChecksumCalcStream(env['wsgi.input'])38 env['wsgi.input'] = stream39 return stream._hash4041To use this, all you need to do is to hook the calculating stream in42before the request starts consuming data. (Eg: be careful accessing43``request.form`` or anything of that nature. ``before_request_handlers``44for instance should be careful not to access it).4546Example usage::4748 @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