Movatterモバイル変換


[0]ホーム

URL:


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

Implements most of the JSON API 1.0 spec. If you're looking for rest_framework_ember (deprecated) check the `legacy` branch.

License

NotificationsYou must be signed in to change notification settings

imtapps-dev/django-rest-framework-json-api

 
 

Repository files navigation

https://travis-ci.org/django-json-api/django-rest-framework-json-api.svg?branch=master

This package started out as an Ember Data specific DRF adapter. It is now movingto the JSON API spec and supporting Ember as a side effect. See thedevelop branchfor the JSON API compliant version.

Join the chat at https://gitter.im/django-json-api/django-rest-framework-json-api

The default Ember Data REST Adapter conventions differ from the defaultDjango Rest Framework JSON request and response format. Instead of addinga Django specific adapter to Ember Data we use this adapter in Django tooutput and accept JSON in the format the Ember Data REST Adapter expects.

By default, Django REST Framework will produce a response like:

{    "count": 20,    "next": "http://example.com/api/1.0/identities/?page=2",    "previous": null,    "results": [        {            "id": 1,            "username": "john",            "full_name": "John Coltrane"        },        {            ...        }    ]}

However, for anidentity model in EmberJS, the Ember Data REST Adapterexpects a response to look like the following:

{    "identity": [        {            "id": 1,            "username": "john",            "full_name": "John Coltrane"        },        {            ...        }    ],    "meta": {        "count": 20,        "next": 2,        "next_link": "http://example.com/api/1.0/identities/?page=2",        "page": 1,        "previous": null,        "previous_link": null    }}

Requirements

  1. Django
  2. Django REST Framework

Installation

From PyPI

pip install rest_framework_ember

From Source

$ git clone https://github.com/django-json-api/rest_framework_ember.git$ cd rest_framework_ember && pip install -e .

Running Tests

$ python runtests.py

Usage

rest_framework_ember assumes you are using class-based views in DjangoRest Framework.

Settings

One can either addrest_framework_ember.parsers.JSONParser andrest_framework_ember.renderers.JSONRenderer to eachViewSet class, oroverridesettings.REST_FRAMEWORK:

REST_FRAMEWORK = {    'PAGINATE_BY': 10,    'PAGINATE_BY_PARAM': 'page_size',    'MAX_PAGINATE_BY': 100,    # DRF v3.1+    'DEFAULT_PAGINATION_CLASS':        'rest_framework_ember.pagination.PageNumberPagination',    # older than DRF v3.1    'DEFAULT_PAGINATION_SERIALIZER_CLASS':        'rest_framework_ember.pagination.PaginationSerializer',    'DEFAULT_PARSER_CLASSES': (        'rest_framework_ember.parsers.JSONParser',        'rest_framework.parsers.FormParser',        'rest_framework.parsers.MultiPartParser'    ),    'DEFAULT_RENDERER_CLASSES': (        'rest_framework_ember.renderers.JSONRenderer',        'rest_framework.renderers.BrowsableAPIRenderer',    ),}

IfPAGINATE_BY is set the renderer will return ameta object withrecord count and the next and previous links. Django Rest Framework looksfor thepage GET parameter by default allowing you to make requests forsubsets of the data withthis.store.find('identity', {page: 2});.

resource_name property

On resources that do not subclassrest_framework.viewsets.ModelViewSet,theresource_name property is required on the class:

class Me(generics.GenericAPIView):    """    Current user's identity endpoint.    GET /me    """    resource_name = 'data'    serializer_class = identity_serializers.IdentitySerializer    allowed_methods = ['GET']    permission_classes = (permissions.IsAuthenticated, )

Ember Data <-> Rest Framework Format Conversion

(camelization/underscore/pluralize)

This package includes the optional ability to automatically convert json requestsand responses from the Ember Data camelCase to python/rest_framework's preferredunderscore. Additionally resource names can be pluralized when an array of objectsare returned. To hook this up include the following in your project settings:

REST_EMBER_FORMAT_KEYS = TrueREST_EMBER_PLURALIZE_KEYS = True

Note: due to the way the inflector works address_1 will convert to address1on output but cannot convert address1 back to address_1 on POST or PUT. Keepthis in mind when naming fields with numbers in them.

Example - Without format conversion:

{   "identity": [      {         "id": 1,         "username": "john",         "first_name": "John",         "last_name": "Coltrane"      },      {         "id": 2,         "username": "frodo",         "first_name": "Bilbo",         "last_name": "Baggins"      },   ],   ...}

Example - With format conversion:

{   "identities": [      {         "id": 1,         "username": "john",         "firstName": "John",         "lastName": "Coltrane"      },      {         "id": 2,         "username": "frodo",         "firstName": "Bilbo",         "lastName": "Baggins"      },   ],   ...}

Managing the trailing slash

By default Django expects a trailing slash on urls and will 301 redirect anyrequests lacking a trailing slash. You can change the server side byinstantiating the Django REST Framework's router like so:

router = routers.SimpleRouter(trailing_slash=False)

If you aren't using SimpleRouter you can instead set APPEND_SLASH = Falsein Django's settings.py file and modify url pattern regex to match routeswithout a trailing slash.

If you prefer to make the change on the client side then add anapplication adapter to your Ember app and override the buildURL method:

App.ApplicationAdapter = DS.RESTAdapter.extend({  buildURL: function() {    var url = this._super.apply(this, arguments);    if (url.charAt(url.length -1) !== '/') {      url += '/';    }    return url;  }});

Displaying Server Side Validation Messages

Ember Data does not ship with a default implementation of a validation errorhandler except in the Rails ActiveModelAdapter so to display validation errorsyou will need to add a small client adapter:

App.ApplicationAdapter = DS.RESTAdapter.extend({  ajaxError: function(jqXHR) {    var error = this._super(jqXHR);    if (jqXHR && jqXHR.status === 400) {      var response = Ember.$.parseJSON(jqXHR.responseText),          errors = {},          keys = Ember.keys(response);      if (keys.length === 1) {        var jsonErrors = response[keys[0]];        Ember.EnumerableUtils.forEach(Ember.keys(jsonErrors), function(key) {          errors[key] = jsonErrors[key];        });      }      return new DS.InvalidError(errors);    } else {      return error;    }  }});

The adapter above will handle the following response format when the response hasa 400 status code. The root key ("post" in this example) is discarded:

{  "post": {    "slug": ["Post with this Slug already exists."]  }}

To display all errors add the following to the template:

{{#each message in errors.messages}}  {{message}}{{/each}}

To display a specific error inline use the following:

{{#each errors.title}}  <div>{{message}}</div>{{/each}}{{input name="title" value=title}}

Sideloading Resources

If you are using the JSON Renderer globally, this can lead to issueswhen hitting endpoints that are intended to sideload other objects.

For example:

{    "users": [],    "cars": []}

Set theresource_name property on the object toFalse, and the datawill be returned as it is above.

Mixins

The following mixin classes are available to use with Rest Frameworkresources.

rest_framework_ember.mixins.MultipleIDMixin

Overridesget_queryset to filter byids[] in URL query params.

About

Implements most of the JSON API 1.0 spec. If you're looking for rest_framework_ember (deprecated) check the `legacy` branch.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Python100.0%

[8]ページ先頭

©2009-2025 Movatter.jp