diff --git a/graphene_django/tests/test_views.py b/graphene_django/tests/test_views.py index c31db8d..ae6cf6f 100644 --- a/graphene_django/tests/test_views.py +++ b/graphene_django/tests/test_views.py @@ -30,6 +30,20 @@ jl = lambda **kwargs: json.dumps([kwargs]) def test_graphiql_is_enabled(client): response = client.get(url_string(), HTTP_ACCEPT='text/html') assert response.status_code == 200 + assert response['Content-Type'].split(';')[0] == 'text/html' + +def test_qfactor_graphiql(client): + response = client.get(url_string(query='{test}'), HTTP_ACCEPT='application/json;q=0.8, text/html;q=0.9') + assert response.status_code == 200 + assert response['Content-Type'].split(';')[0] == 'text/html' + +def test_qfactor_json(client): + response = client.get(url_string(query='{test}'), HTTP_ACCEPT='text/html;q=0.8, application/json;q=0.9') + assert response.status_code == 200 + assert response['Content-Type'].split(';')[0] == 'application/json' + assert response_json(response) == { + 'data': {'test': "Hello World"} + } def test_allows_get_with_query_param(client): diff --git a/graphene_django/views.py b/graphene_django/views.py index 0c8174d..32ea19c 100644 --- a/graphene_django/views.py +++ b/graphene_django/views.py @@ -35,8 +35,8 @@ def get_accepted_content_types(request): match = re.match(r'(^|;)q=(0(\.\d{,3})?|1(\.0{,3})?)(;|$)', parts[1]) if match: - return parts[0], float(match.group(2)) - return parts[0], 1 + return parts[0].strip(), float(match.group(2)) + return parts[0].strip(), 1 raw_content_types = request.META.get('HTTP_ACCEPT', '*/*').split(',') qualified_content_types = map(qualify, raw_content_types) @@ -280,10 +280,13 @@ class GraphQLView(View): @classmethod def request_wants_html(cls, request): accepted = get_accepted_content_types(request) - html_index = accepted.count('text/html') - json_index = accepted.count('application/json') + accepted_length = len(accepted) + # the list will be ordered in preferred first - so we have to make + # sure the most preferred gets the highest number + html_priority = accepted_length - accepted.index('text/html') if 'text/html' in accepted else 0 + json_priority = accepted_length - accepted.index('application/json') if 'application/json' in accepted else 0 - return html_index > json_index + return html_priority > json_priority @staticmethod def get_graphql_params(request, data):