Skip to content

Commit

Permalink
improve cache key build to working with http method and sorted query …
Browse files Browse the repository at this point in the history
…string
  • Loading branch information
drgarcia1986 committed Aug 8, 2015
1 parent 4503507 commit 91ecfb2
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 3 deletions.
9 changes: 7 additions & 2 deletions muffin_cache/handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,14 @@ class CacheHandler(Handler):
CACHED_HTTP_METHODS = ('GET', 'OPTIONS')

def _build_cache_key(self, request):
return 'muffin-cache-{path}-{query}'.format(
sorted_query_string = '-'.join(
sorted(request.query_string.split('&'))
)

return 'muffin-cache-{method}-{path}-{query}'.format(
method=request.method,
path=request.raw_path,
query=request.query_string
query=sorted_query_string
)

@asyncio.coroutine
Expand Down
2 changes: 1 addition & 1 deletion muffin_cache/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ def start(self, app):
if 'redis' not in app.ps:
raise PluginException(
'muffin-cache required muffin-redis package.'
'pip install muffin-redis to install'
'use pip install muffin-redis to install'
)

def finish(self, app):
Expand Down
51 changes: 51 additions & 0 deletions tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,57 @@ def get(self, request):
assert hit_view_count == 2


def test_should_cache_response_in_any_querystring_parameters_order(
app, client
):

hit_view_count = 0

@app.register('/cache-sorted-qs')
class View(CacheHandler):

def get(self, request):
nonlocal hit_view_count
hit_view_count += 1
return 'result'

response = client.get('/cache-sorted-qs?foo=1&bar=2')
assert response.text == 'result'
assert hit_view_count == 1

response = client.get('/cache-sorted-qs?bar=2&foo=1')
assert response.text == 'result'
assert hit_view_count == 1


def test_should_cache_response_by_http_method(app, client):

hit_view_count = 0

@app.register('/cache-http-method')
class View(CacheHandler):

def get(self, request):
nonlocal hit_view_count
hit_view_count += 1
return 'result'

def options(self, request):
nonlocal hit_view_count
hit_view_count += 1
return 'result options'

for _ in range(2):
response = client.get('/cache-http-method')
assert response.text == 'result'
assert hit_view_count == 1

for _ in range(2):
response = client.options('/cache-http-method')
assert response.text == 'result options'
assert hit_view_count == 2


def test_should_cache_json_response(app, client):

hit_view_count = 0
Expand Down

0 comments on commit 91ecfb2

Please sign in to comment.