Skip to content

Commit

Permalink
flask_util.cached: cache werkzeug HTTPExceptions, eg raised by abort/…
Browse files Browse the repository at this point in the history
…error

catch and return them instead of letting them propagate so that flask-cache can cache them

pallets-eco/flask-caching#444
  • Loading branch information
snarfed committed Jan 25, 2023
1 parent 56df5bf commit b9fcfec
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
12 changes: 11 additions & 1 deletion flask_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -263,8 +263,18 @@ def unless():
request.cookies)

def decorator(f):
# catch werkzeug HTTPExceptions, eg raised by abort(), and return them
# instead of letting them propagate, so that flask-cache can cache them
@functools.wraps(f)
def httpexception_to_return(*args, **kwargs):
try:
return f(*args, **kwargs)
except HTTPException as e:
return e

decorated = cache.cached(timeout.total_seconds(), query_string=True,
response_filter=response_filter, unless=unless)(f)
response_filter=response_filter, unless=unless
)(httpexception_to_return)

# include specified headers in cache key:
# https://flask-caching.readthedocs.io/en/latest/api.html#flask_caching.Cache.cached
Expand Down
19 changes: 19 additions & 0 deletions tests/test_flask_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,25 @@ def error():
self.assertEqual(500, resp.status_code)
self.assertEqual(1, calls)

def test_cached_flask_util_error(self):
cache = Cache(self.app)
calls = 0

@self.app.route('/error')
@flask_util.cached(cache, datetime.timedelta(days=1))
def error():
nonlocal calls
calls += 1
flask_util.error('asdf', status=400)

resp = self.client.get('/error')
self.assertEqual(400, resp.status_code)
self.assertEqual(1, calls)

resp = self.client.get('/error')
self.assertEqual(400, resp.status_code)
self.assertEqual(1, calls)

def test_cached_headers(self):
cache = Cache(self.app)
calls = 0
Expand Down

0 comments on commit b9fcfec

Please sign in to comment.