Skip to content

Commit

Permalink
Fixing the request_body as key issue
Browse files Browse the repository at this point in the history
This is to fix #3
It turns out that by reading the request body from the `req.stream`, we are fully consuming it and so it is no longer available for the responder.

For now I just exclude the use of the request body in the cache key - if a feature request comes up later to include it, then will consider how we might be able to use it while still leaving it available for the responder.

Signed-off-by: Zoltan Fedor <zoltan.1.fedor@gmail.com>
  • Loading branch information
zoltan-fedor committed Dec 26, 2019
1 parent 3fcc6ec commit 5591191
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 12 deletions.
5 changes: 5 additions & 0 deletions CHANGES
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
Changelog
=========

Version 0.2.0
-------------

- The `request_body` is not longer included in the cache key, `see <https://github.com/zoltan-fedor/falcon-caching/issues/3>`_


Version 0.1.0
-------------
Expand Down
11 changes: 2 additions & 9 deletions falcon_caching/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,14 +110,7 @@ def process_response(self, req, resp, resource, req_succeeded):

@staticmethod
def generate_cache_key(req, method: str = None) -> str:
""" Generate the cache key from the request using the path, method and request body """

# Get the body of the request to be used in the key.
# If Content-Length happens to be 0, or the header is
# missing altogether, reading it as below will not block.
# see https://falcon.readthedocs.io/en/stable/api/request_and_response.html#falcon.Request.stream
request_body = req.stream.read(req.content_length or 0)
request_body = request_body.decode() if request_body else ''
""" Generate the cache key from the request using the path and the method """

path = req.path
if path.endswith('/'):
Expand All @@ -126,4 +119,4 @@ def generate_cache_key(req, method: str = None) -> str:
if not method:
method = req.method

return f'{path}:{method.upper()}:{request_body}'
return f'{path}:{method.upper()}'
5 changes: 2 additions & 3 deletions tests/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,13 @@ def get_cache_eviction_strategy(app: 'API'):
return get_cache(app).cache_config['CACHE_EVICTION_STRATEGY']


def delete_from_cache(app: 'API', path: str, method: str, request_body: str=None) -> None:
def delete_from_cache(app: 'API', path: str, method: str) -> None:
""" Delete / remove a certain key from the cache
"""
request_body = request_body if request_body else ''

if path.endswith('/'):
path = path[:-1]

key = f'{path}:{method.upper()}:{request_body}'
key = f'{path}:{method.upper()}'

get_cache(app).cache.delete(key)

0 comments on commit 5591191

Please sign in to comment.