Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

fixed rendering of non paginated responses #114

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
jerel merged 1 commit into django-json-api:develop from abdulhaq-e:non_paginated_fix
Oct 8, 2015
Merged
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
9 changes: 6 additions & 3 deletions example/settings/dev.py
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,12 @@
JSON_API_FORMAT_KEYS = 'camelize'
JSON_API_FORMAT_RELATION_KEYS = 'camelize'
REST_FRAMEWORK = {
'PAGINATE_BY': 5,
'PAGINATE_BY_PARAM': 'page_size',
'MAX_PAGINATE_BY': 100,
# 'PAGINATE_BY': 5,
# 'PAGINATE_BY_PARAM': 'page_size',
# 'MAX_PAGINATE_BY': 100,
'PAGE_SIZE': 5,
# 'PAGINATE_BY_PARAM' should now be in the pagination class
# Same for 'MAX_PAGINATE_BY'.
'EXCEPTION_HANDLER': 'rest_framework_json_api.exceptions.exception_handler',
'DEFAULT_PAGINATION_CLASS':
'rest_framework_json_api.pagination.PageNumberPagination',
Expand Down
3 changes: 2 additions & 1 deletion example/settings/test.py
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,6 @@
JSON_API_FORMAT_RELATION_KEYS = 'camelize'
JSON_API_PLURALIZE_RELATION_TYPE = True
REST_FRAMEWORK.update({
'PAGINATE_BY': 1,
# 'PAGINATE_BY': 1,
'PAGE_SIZE': 1,
})
24 changes: 24 additions & 0 deletions example/tests/conftest.py
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,27 @@
register(BlogFactory)
register(AuthorFactory)
register(EntryFactory)


@pytest.fixture
def single_entry(author_factory, entry_factory):

author = author_factory(name="Joel Spolsky")
entry = entry_factory(
headline=("The Absolute Minimum Every Software Developer"
"Absolutely, Positively Must Know About Unicode "
"and Character Sets (No Excuses!)"),
blog__name='Joel on Software',
authors=(author, )
)


@pytest.fixture
def multiple_entries(single_entry, author_factory, entry_factory):

author = author_factory(name="Ned Batchelder")
entry = entry_factory(
headline=("Pragmatic Unicode"),
blog__name='Ned Batchelder Blog',
authors=(author, )
)
9 changes: 7 additions & 2 deletions example/tests/test_format_keys.py
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,17 @@ def setUp(self):
self.detail_url = reverse('user-detail', kwargs={'pk': self.miles.pk})

# Set the format keys settings.
setattr(settings, 'JSON_API_FORMAT_KEYS', 'camelize')
# The below line is redundant because the default settings already
# use 'camelize'
# setattr(settings, 'JSON_API_FORMAT_KEYS', 'camelize')
# CAMELIZE capitalize the type, needs to be checked

def tearDown(self):
pass
# Remove the format keys settings.
setattr(settings, 'JSON_API_FORMAT_KEYS', 'dasherize')
# The below line is redundant because the default settings already
# use 'camelize'
# setattr(settings, 'JSON_API_FORMAT_KEYS', 'camelize')


def test_camelization(self):
Expand Down
10 changes: 10 additions & 0 deletions example/tests/test_generic_viewset.py
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,16 @@ class GenericViewSet(TestBase):
"""
Test expected responses coming from a Generic ViewSet
"""

def setUp(self):
super(GenericViewSet, self).setUp()

setattr(settings, 'JSON_API_FORMAT_KEYS', 'dasherize')
Copy link
Contributor Author

@abdulhaq-e abdulhaq-e Oct 2, 2015

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The attributes used in the JSON were dasherized so this is needed. Previously, the tests passed by coincidence due to another test changing the format to 'dasherize'.


def tearDown(self):

setattr(settings, 'JSON_API_FORMAT_KEYS', 'camelize')

def test_default_rest_framework_behavior(self):
"""
This is more of an example really, showing default behavior
Expand Down
7 changes: 7 additions & 0 deletions example/tests/test_model_viewsets.py
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from django.contrib.auth import get_user_model
from django.utils import encoding
from django.core.urlresolvers import reverse
from django.conf import settings

from example.tests import TestBase
from example.tests.utils import dump_json, redump_json
Expand All @@ -22,6 +23,12 @@ def setUp(self):
super(ModelViewSetTests, self).setUp()
self.detail_url = reverse('user-detail', kwargs={'pk': self.miles.pk})

setattr(settings, 'JSON_API_FORMAT_KEYS', 'dasherize')

def tearDown(self):

setattr(settings, 'JSON_API_FORMAT_KEYS', 'camelize')

def test_key_in_list_result(self):
"""
Ensure the result has a 'user' key since that is the name of the model
Expand Down
78 changes: 78 additions & 0 deletions example/tests/test_non_paginated_responses.py
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
from django.core.urlresolvers import reverse
from django.conf import settings

import pytest

from ..views import EntryViewSet
from rest_framework_json_api.pagination import PageNumberPagination

from example.tests.utils import dump_json, redump_json

pytestmark = pytest.mark.django_db


def test_multiple_entries_no_pagination(rf, multiple_entries):

expected = {
"data": [
{
"type": "posts",
"id": "1",
"attributes":
{
"headline": "The Absolute Minimum Every Software DeveloperAbsolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)",
"bodyText": "Here goes the body text",
"pubDate": None,
"modDate": None
},
"relationships":
{
"blog": {
"data": {"type": "blogs", "id": "1"}
},
"authors": {
"meta": {"count": 1},
"data": [{"type": "authors", "id": "1"}]
}
}
},
{
"type": "posts",
"id": "2",
"attributes":
{
"headline": "Pragmatic Unicode",
"bodyText": "Here goes the body text",
"pubDate": None,
"modDate": None
},
"relationships":
{
"blog": {
"data": {"type": "blogs", "id": "2"}
},
"authors": {
"meta": {"count": 1},
"data": [{"type": "authors", "id": "2"}]
}
}
},
]
}

class NoPagination(PageNumberPagination):
page_size = None

class NonPaginatedEntryViewSet(EntryViewSet):
pagination_class = NoPagination

request = rf.get(
reverse("entry-list"))
view = NonPaginatedEntryViewSet.as_view({'get': 'list'})
response = view(request)
response.render()
# print response.content
content_dump = redump_json(response.content)
expected_dump = dump_json(expected)

assert content_dump == expected_dump
19 changes: 3 additions & 16 deletions example/tests/test_pagination.py
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,6 @@
pytestmark = pytest.mark.django_db


@pytest.fixture
def single_entry(author_factory, entry_factory):

author = author_factory(name="Joel Spolsky")
entry = entry_factory(
headline=("The Absolute Minimum Every Software Developer"
"Absolutely, Positively Must Know About Unicode "
"and Character Sets (No Excuses!)"),
blog__name='Joel on Software',
authors=(author, )
)


def test_pagination_with_single_entry(single_entry, client):

expected = {
Expand All @@ -29,9 +16,9 @@ def test_pagination_with_single_entry(single_entry, client):
"attributes":
{
"headline": "The Absolute Minimum Every Software DeveloperAbsolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)",
"body-text": "Here goes the body text",
"pub-date": None,
"mod-date": None
"bodyText": "Here goes the body text",
"pubDate": None,
"modDate": None
Copy link
Member

@jsenecal jsenecal Oct 5, 2015

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why removing this test ?

Copy link
Contributor Author

@abdulhaq-e abdulhaq-e Oct 5, 2015

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This fixtures and the new fixture I used were moved to conftest.py. It's better than polluting the test files.

Copy link
Member

@jsenecal jsenecal Oct 5, 2015

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

oops - my bad 👍

},
"relationships":
{
Expand Down
3 changes: 3 additions & 0 deletions rest_framework_json_api/pagination.py
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,9 @@ class PageNumberPagination(BasePagination):
A json-api compatible pagination format
"""

page_size_query_param = 'page_size'
max_page_size = 100

Copy link
Member

@jsenecal jsenecal Oct 5, 2015

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is this there ?

# Default is 'None'. Set to eg 'page_size' to enable usage.
page_size_query_param = None
# Set to an integer to limit the maximum page size the client may request.
# Only relevant if 'page_size_query_param' has also been set.
max_page_size = None

From BasePagination class....

Copy link
Contributor Author

@abdulhaq-e abdulhaq-e Oct 5, 2015

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I moved those from the settings. Pagination configuration from Drf >= 3.1 should be set in the pagination class. Putting them in the view or settings as per Drf < 3.1 now produces a 'deprecation warning' and I think it will produce an error from Drf 3.3.

Copy link
Member

@jsenecal jsenecal Oct 5, 2015

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

HA! good catch ! Thanks for that!

def build_link(self, index):
if not index:
return None
Expand Down
18 changes: 11 additions & 7 deletions rest_framework_json_api/renderers.py
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -75,22 +75,26 @@ def render(self, data, accepted_media_type=None, renderer_context=None):

json_api_included = list()

if view and hasattr(view, 'action') and view.action == 'list' and \
isinstance(data, dict) and 'results' in data:
if view and hasattr(view, 'action') and view.action == 'list':
# The below is not true for non-paginated responses
# and isinstance(data, dict):

# If detail view then json api spec expects dict, otherwise a list
# - http://jsonapi.org/format/#document-top-level
# The `results` key may be missing if unpaginated or an OPTIONS request
if 'results' in data:
resources = data["results"]
else:
resources = data

results = data["results"]

resource_serializer = results.serializer
resource_serializer = resources.serializer

# Get the serializer fields
fields = utils.get_serializer_fields(resource_serializer)

json_api_data = list()
for position in range(len(results)):
resource = results[position] # Get current resource
for position in range(len(resources)):
resource = resources[position] # Get current resource
resource_instance = resource_serializer.instance[position] # Get current instance
json_api_data.append(
utils.build_json_resource_obj(fields, resource, resource_instance, resource_name))
Expand Down

AltStyle によって変換されたページ (->オリジナル) /