Skip to content

Commit dbd3957

Browse files
authored
Merge pull request #340 from urbandove/qfactor
Fix qfactor rankings for HTTP-ACCEPT
2 parents 5b17e98 + 28cccb4 commit dbd3957

File tree

2 files changed

+22
-5
lines changed

2 files changed

+22
-5
lines changed

graphene_django/tests/test_views.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,20 @@ def response_json(response):
3030
def test_graphiql_is_enabled(client):
3131
response = client.get(url_string(), HTTP_ACCEPT='text/html')
3232
assert response.status_code == 200
33+
assert response['Content-Type'].split(';')[0] == 'text/html'
34+
35+
def test_qfactor_graphiql(client):
36+
response = client.get(url_string(query='{test}'), HTTP_ACCEPT='application/json;q=0.8, text/html;q=0.9')
37+
assert response.status_code == 200
38+
assert response['Content-Type'].split(';')[0] == 'text/html'
39+
40+
def test_qfactor_json(client):
41+
response = client.get(url_string(query='{test}'), HTTP_ACCEPT='text/html;q=0.8, application/json;q=0.9')
42+
assert response.status_code == 200
43+
assert response['Content-Type'].split(';')[0] == 'application/json'
44+
assert response_json(response) == {
45+
'data': {'test': "Hello World"}
46+
}
3347

3448

3549
def test_allows_get_with_query_param(client):

graphene_django/views.py

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -35,8 +35,8 @@ def qualify(x):
3535
match = re.match(r'(^|;)q=(0(\.\d{,3})?|1(\.0{,3})?)(;|$)',
3636
parts[1])
3737
if match:
38-
return parts[0], float(match.group(2))
39-
return parts[0], 1
38+
return parts[0].strip(), float(match.group(2))
39+
return parts[0].strip(), 1
4040

4141
raw_content_types = request.META.get('HTTP_ACCEPT', '*/*').split(',')
4242
qualified_content_types = map(qualify, raw_content_types)
@@ -280,10 +280,13 @@ def can_display_graphiql(cls, request, data):
280280
@classmethod
281281
def request_wants_html(cls, request):
282282
accepted = get_accepted_content_types(request)
283-
html_index = accepted.count('text/html')
284-
json_index = accepted.count('application/json')
283+
accepted_length = len(accepted)
284+
# the list will be ordered in preferred first - so we have to make
285+
# sure the most preferred gets the highest number
286+
html_priority = accepted_length - accepted.index('text/html') if 'text/html' in accepted else 0
287+
json_priority = accepted_length - accepted.index('application/json') if 'application/json' in accepted else 0
285288

286-
return html_index > json_index
289+
return html_priority > json_priority
287290

288291
@staticmethod
289292
def get_graphql_params(request, data):

0 commit comments

Comments
 (0)