Skip to content

Commit

Permalink
Use default redirect when nothing matches.
Browse files Browse the repository at this point in the history
Issue #86
  • Loading branch information
Wim-De-Clercq committed Feb 17, 2023
1 parent 2bfdf04 commit ca0abe7
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 13 deletions.
4 changes: 2 additions & 2 deletions tests/test_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,8 @@ def test_redirect_with_mime_match(self, urihandler):
def test_redirect_with_mime_no_match(self, urihandler):
req = testing.DummyRequest(accept="application/pdf")
req.host_url = "http://test.urihandler.org"
with pytest.raises(HTTPNotAcceptable):
urihandler.handle("http://test.urihandler.org/foobar/18", req)
res = urihandler.handle("http://test.urihandler.org/foobar/18", req)
assert res == "http://localhost:5555/foobar/18"

def test_redirect_default_mime(self, urihandler):
req = testing.DummyRequest()
Expand Down
38 changes: 27 additions & 11 deletions urihandler/handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,23 +34,39 @@ def handle(self, uri, request):
if m:
redirect = u["redirect"]
if isinstance(redirect, dict):
if isinstance(request.accept, AcceptNoHeader):
redirect = redirect.get("default")
if not redirect:
raise HTTPNotAcceptable()
else:
for mime, redirect in redirect.items():
if mime in request.accept:
break
else:
# No matching mime was found.
raise HTTPNotAcceptable()
redirect = _get_redirect_based_on_accept_header(request.accept, redirect)
redirect = redirect.format(**m.groupdict())
log.debug(f"Match found. Redirecting to {redirect}.")
return redirect
return None


def _get_redirect_based_on_accept_header(accept_header, redirect_rule):
"""
Return the redirect rule based on accept header.
At its core it simply looks for a matching mime between accept header
and the configured mime type redirects. But exceptions apply.
If there is no accept header specified or if no matching mime is found,
the default will be returned. If default is not set, HTTP 406 gets raised.
"""
default = redirect_rule.get("default")
if isinstance(accept_header, AcceptNoHeader):
if not default:
raise HTTPNotAcceptable()
return default

for mime, redirect in redirect_rule.items():
if mime in accept_header:
return redirect

if not default:
raise HTTPNotAcceptable()

return default


def _build_uri_handler(registry, handlerconfig):
"""
:param pyramid.registry.Registry registry: Pyramid registry
Expand Down

0 comments on commit ca0abe7

Please sign in to comment.