Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 12 additions & 7 deletions pygeoapi/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@
from datetime import date, datetime, time, timezone
from decimal import Decimal
from enum import Enum
from heapq import heappush
import ipaddress
import json
import logging
Expand Down Expand Up @@ -743,14 +742,20 @@ def get_choice_from_headers(headers: dict,
match = re.match(r'^([^;]+)(?:;q=([\d.]+))?$', part.strip())
if match:
value, q_value = match.groups()
q_value = float(q_value) if q_value else 1.0
try:
q_value = float(q_value) if q_value else 1.0
except ValueError:
continue

# Sort choices by q value and index
if 0 <= q_value <= 1:
heappush(choices, (1 / q_value, i, value))
# q=0 means "not acceptable" (RFC 9110, section 12.4.2)
if 0 < q_value <= 1:
choices.append((-q_value, i, value))

# Drop q value
sorted_choices = [choice[-1] for choice in choices]
if not choices:
return

# Highest q value first; ties keep header order
sorted_choices = [choice[-1] for choice in sorted(choices)]

# Return one or all choices
return sorted_choices if all else sorted_choices[0]
Expand Down
16 changes: 16 additions & 0 deletions tests/other/test_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,22 @@ def test_get_choice_from_headers():
assert util.get_choice_from_headers(
{'accept-language': 'en_US', 'accept': '*/*'}, 'accept') == '*/*'

# all=True returns every choice ordered by q value, ties in header order
assert util.get_choice_from_headers(
{'accept-language': 'a;q=0.1,b;q=0.2,c;q=0.3,d;q=0.4,e;q=0.9,f'},
'accept-language', all=True) == ['f', 'e', 'd', 'c', 'b', 'a']
assert util.get_choice_from_headers(
{'accept': 'text/html,application/json'},
'accept', all=True) == ['text/html', 'application/json']

# q=0 means "not acceptable" and must not raise ZeroDivisionError
assert util.get_choice_from_headers(
{'accept-language': 'fr;q=0,en'}, 'accept-language') == 'en'
assert util.get_choice_from_headers(
{'accept-language': 'fr;q=0'}, 'accept-language') is None
assert util.get_choice_from_headers(
{'accept-language': 'fr;q=0'}, 'accept-language', all=True) is None


@pytest.mark.parametrize('url,allow_internal,result', [
['http://127.0.0.1/test', False, False],
Expand Down
Loading