Commit 5356af86 by Tom Christie

Merge pull request #808 from tomchristie/2.3

2.3
parents 287ff43c 0f00da84
# Django REST framework # Django REST framework
**A toolkit for building well-connected, self-describing web APIs.** **Awesome web-browseable Web APIs.**
**Author:** Tom Christie. [Follow me on Twitter][twitter].
**Support:** [REST framework group][group], or `#restframework` on freenode IRC.
[![build-status-image]][travis] [![build-status-image]][travis]
--- **Note**: Full documentation for the project is available at [http://django-rest-framework.org][docs].
**Full documentation for REST framework is available on [http://django-rest-framework.org][docs].** # Overview
--- Django REST framework is a powerful and flexible toolkit that makes it easy to build Web APIs.
# Overview Some reasons you might want to use REST framework:
Django REST framework is a lightweight library that makes it easy to build Web APIs. It is designed as a modular and easy to customize architecture, based on Django's class based views. * The Web browseable API is a huge useability win for your developers.
* Authentication policies including OAuth1a and OAuth2 out of the box.
* Serialization that supports both ORM and non-ORM data sources.
* Customizable all the way down - just use regular function-based views if you don't need the more powerful features.
* Extensive documentation, and great community support.
Web APIs built using REST framework are fully self-describing and web browsable - a huge useability win for your developers. It also supports a wide range of media types, authentication and permission policies out of the box. There is a live example API for testing purposes, [available here][sandbox].
If you are considering using REST framework for your API, we recommend reading the [REST framework 2 announcement][rest-framework-2-announcement] which gives a good overview of the framework and it's capabilities. **Below**: *Screenshot from the browseable API*
There is also a sandbox API you can use for testing purposes, [available here][sandbox]. ![Screenshot][image]
# Requirements # Requirements
* Python (2.6.5+, 2.7, 3.2, 3.3) * Python (2.6.5+, 2.7, 3.2, 3.3)
* Django (1.3, 1.4, 1.5) * Django (1.3, 1.4, 1.5)
**Optional:**
* [Markdown][markdown] - Markdown support for the self describing API.
* [PyYAML][pyyaml] - YAML content type support.
* [defusedxml][defusedxml] - XML content-type support.
* [django-filter][django-filter] - Filtering support.
# Installation # Installation
Install using `pip`, including any optional packages you want... Install using `pip`...
pip install djangorestframework pip install djangorestframework
pip install markdown # Markdown support for the browsable API.
pip install pyyaml # YAML content-type support.
pip install defusedxml # XML content-type support.
pip install django-filter # Filtering support
...or clone the project from github.
git clone git@github.com:tomchristie/django-rest-framework.git
cd django-rest-framework
pip install -r requirements.txt
pip install -r optionals.txt
Add `'rest_framework'` to your `INSTALLED_APPS` setting. Add `'rest_framework'` to your `INSTALLED_APPS` setting.
...@@ -60,28 +42,65 @@ Add `'rest_framework'` to your `INSTALLED_APPS` setting. ...@@ -60,28 +42,65 @@ Add `'rest_framework'` to your `INSTALLED_APPS` setting.
'rest_framework', 'rest_framework',
) )
If you're intending to use the browsable API you'll probably also want to add REST framework's login and logout views. Add the following to your root `urls.py` file. # Example
Let's take a look at a quick example of using REST framework to build a simple model-backed API for accessing users and groups.
Here's our project's root `urls.py` module:
from django.conf.urls.defaults import url, patterns, include
from django.contrib.auth.models import User, Group
from rest_framework import viewsets, routers
# ViewSets define the view behavior.
class UserViewSet(viewsets.ModelViewSet):
model = User
class GroupViewSet(viewsets.ModelViewSet):
model = Group
# Routers provide an easy way of automatically determining the URL conf
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)
# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browseable API.
urlpatterns = patterns('', urlpatterns = patterns('',
... url(r'^', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
) )
Note that the URL path can be whatever you want, but you must include `'rest_framework.urls'` with the `'rest_framework'` namespace. We'd also like to configure a couple of settings for our API.
Add the following to your `settings.py` module:
# Development REST_FRAMEWORK = {
# Use hyperlinked styles by default.
# Only used if the `serializer_class` attribute is not set on a view.
'DEFAULT_MODEL_SERIALIZER_CLASS':
'rest_framework.serializers.HyperlinkedModelSerializer',
To build the docs. # Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
]
}
./mkdocs.py Don't forget to make sure you've also added `rest_framework` to your `INSTALLED_APPS` setting.
To run the tests. That's it, we're done!
./rest_framework/runtests/runtests.py # Documentation & Support
To run the tests against all supported configurations, first install [the tox testing tool][tox] globally, using `pip install tox`, then simply run `tox`: Full documentation for the project is available at [http://django-rest-framework.org][docs].
tox For questions and support, use the [REST framework discussion group][group], or `#restframework` on freenode IRC.
You may also want to [follow the author on Twitter][twitter].
# License # License
...@@ -116,9 +135,14 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ...@@ -116,9 +135,14 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
[sandbox]: http://restframework.herokuapp.com/ [sandbox]: http://restframework.herokuapp.com/
[rest-framework-2-announcement]: http://django-rest-framework.org/topics/rest-framework-2-announcement.html [rest-framework-2-announcement]: http://django-rest-framework.org/topics/rest-framework-2-announcement.html
[2.1.0-notes]: https://groups.google.com/d/topic/django-rest-framework/Vv2M0CMY9bg/discussion [2.1.0-notes]: https://groups.google.com/d/topic/django-rest-framework/Vv2M0CMY9bg/discussion
[image]: http://django-rest-framework.org/img/quickstart.png
[tox]: http://testrun.org/tox/latest/ [tox]: http://testrun.org/tox/latest/
[tehjones]: https://twitter.com/tehjones/status/294986071979196416
[wlonk]: https://twitter.com/wlonk/status/261689665952833536
[laserllama]: https://twitter.com/laserllama/status/328688333750407168
[docs]: http://django-rest-framework.org/ [docs]: http://django-rest-framework.org/
[urlobject]: https://github.com/zacharyvoase/urlobject [urlobject]: https://github.com/zacharyvoase/urlobject
[markdown]: http://pypi.python.org/pypi/Markdown/ [markdown]: http://pypi.python.org/pypi/Markdown/
......
...@@ -43,7 +43,8 @@ The default authentication schemes may be set globally, using the `DEFAULT_AUTHE ...@@ -43,7 +43,8 @@ The default authentication schemes may be set globally, using the `DEFAULT_AUTHE
) )
} }
You can also set the authentication scheme on a per-view basis, using the `APIView` class based views. You can also set the authentication scheme on a per-view or per-viewset basis,
using the `APIView` class based views.
class ExampleView(APIView): class ExampleView(APIView):
authentication_classes = (SessionAuthentication, BasicAuthentication) authentication_classes = (SessionAuthentication, BasicAuthentication)
......
...@@ -248,6 +248,12 @@ A floating point representation. ...@@ -248,6 +248,12 @@ A floating point representation.
Corresponds to `django.db.models.fields.FloatField`. Corresponds to `django.db.models.fields.FloatField`.
## DecimalField
A decimal representation.
Corresponds to `django.db.models.fields.DecimalField`.
## FileField ## FileField
A file representation. Performs Django's standard FileField validation. A file representation. Performs Django's standard FileField validation.
......
...@@ -8,7 +8,7 @@ ...@@ -8,7 +8,7 @@
The default behavior of REST framework's generic list views is to return the entire queryset for a model manager. Often you will want your API to restrict the items that are returned by the queryset. The default behavior of REST framework's generic list views is to return the entire queryset for a model manager. Often you will want your API to restrict the items that are returned by the queryset.
The simplest way to filter the queryset of any view that subclasses `MultipleObjectAPIView` is to override the `.get_queryset()` method. The simplest way to filter the queryset of any view that subclasses `GenericAPIView` is to override the `.get_queryset()` method.
Overriding this method allows you to customize the queryset returned by the view in a number of different ways. Overriding this method allows you to customize the queryset returned by the view in a number of different ways.
...@@ -21,7 +21,6 @@ You can do so by filtering based on the value of `request.user`. ...@@ -21,7 +21,6 @@ You can do so by filtering based on the value of `request.user`.
For example: For example:
class PurchaseList(generics.ListAPIView) class PurchaseList(generics.ListAPIView)
model = Purchase
serializer_class = PurchaseSerializer serializer_class = PurchaseSerializer
def get_queryset(self): def get_queryset(self):
...@@ -44,7 +43,6 @@ For example if your URL config contained an entry like this: ...@@ -44,7 +43,6 @@ For example if your URL config contained an entry like this:
You could then write a view that returned a purchase queryset filtered by the username portion of the URL: You could then write a view that returned a purchase queryset filtered by the username portion of the URL:
class PurchaseList(generics.ListAPIView) class PurchaseList(generics.ListAPIView)
model = Purchase
serializer_class = PurchaseSerializer serializer_class = PurchaseSerializer
def get_queryset(self): def get_queryset(self):
...@@ -62,7 +60,6 @@ A final example of filtering the initial queryset would be to determine the init ...@@ -62,7 +60,6 @@ A final example of filtering the initial queryset would be to determine the init
We can override `.get_queryset()` to deal with URLs such as `http://example.com/api/purchases?username=denvercoder9`, and filter the queryset only if the `username` parameter is included in the URL: We can override `.get_queryset()` to deal with URLs such as `http://example.com/api/purchases?username=denvercoder9`, and filter the queryset only if the `username` parameter is included in the URL:
class PurchaseList(generics.ListAPIView) class PurchaseList(generics.ListAPIView)
model = Purchase
serializer_class = PurchaseSerializer serializer_class = PurchaseSerializer
def get_queryset(self): def get_queryset(self):
...@@ -82,25 +79,25 @@ We can override `.get_queryset()` to deal with URLs such as `http://example.com/ ...@@ -82,25 +79,25 @@ We can override `.get_queryset()` to deal with URLs such as `http://example.com/
As well as being able to override the default queryset, REST framework also includes support for generic filtering backends that allow you to easily construct complex filters that can be specified by the client using query parameters. As well as being able to override the default queryset, REST framework also includes support for generic filtering backends that allow you to easily construct complex filters that can be specified by the client using query parameters.
REST framework supports pluggable backends to implement filtering, and provides an implementation which uses the [django-filter] package. ## DjangoFilterBackend
To use REST framework's filtering backend, first install `django-filter`. To use REST framework's `DjangoFilterBackend`, first install `django-filter`.
pip install django-filter pip install django-filter
You must also set the filter backend to `DjangoFilterBackend` in your settings: You must also set the filter backend to `DjangoFilterBackend` in your settings:
REST_FRAMEWORK = { REST_FRAMEWORK = {
'FILTER_BACKEND': 'rest_framework.filters.DjangoFilterBackend' 'DEFAULT_FILTER_BACKENDS': ['rest_framework.filters.DjangoFilterBackend']
} }
## Specifying filter fields #### Specifying filter fields
If all you need is simple equality-based filtering, you can set a `filter_fields` attribute on the view, listing the set of fields you wish to filter against. If all you need is simple equality-based filtering, you can set a `filter_fields` attribute on the view, or viewset, listing the set of fields you wish to filter against.
class ProductList(generics.ListAPIView): class ProductList(generics.ListAPIView):
model = Product queryset = Product.objects.all()
serializer_class = ProductSerializer serializer_class = ProductSerializer
filter_fields = ('category', 'in_stock') filter_fields = ('category', 'in_stock')
...@@ -108,7 +105,7 @@ This will automatically create a `FilterSet` class for the given fields, and wil ...@@ -108,7 +105,7 @@ This will automatically create a `FilterSet` class for the given fields, and wil
http://example.com/api/products?category=clothing&in_stock=True http://example.com/api/products?category=clothing&in_stock=True
## Specifying a FilterSet #### Specifying a FilterSet
For more advanced filtering requirements you can specify a `FilterSet` class that should be used by the view. For example: For more advanced filtering requirements you can specify a `FilterSet` class that should be used by the view. For example:
...@@ -120,7 +117,7 @@ For more advanced filtering requirements you can specify a `FilterSet` class tha ...@@ -120,7 +117,7 @@ For more advanced filtering requirements you can specify a `FilterSet` class tha
fields = ['category', 'in_stock', 'min_price', 'max_price'] fields = ['category', 'in_stock', 'min_price', 'max_price']
class ProductList(generics.ListAPIView): class ProductList(generics.ListAPIView):
model = Product queryset = Product.objects.all()
serializer_class = ProductSerializer serializer_class = ProductSerializer
filter_class = ProductFilter filter_class = ProductFilter
...@@ -134,13 +131,13 @@ For more details on using filter sets see the [django-filter documentation][djan ...@@ -134,13 +131,13 @@ For more details on using filter sets see the [django-filter documentation][djan
**Hints & Tips** **Hints & Tips**
* By default filtering is not enabled. If you want to use `DjangoFilterBackend` remember to make sure it is installed by using the `'FILTER_BACKEND'` setting. * By default filtering is not enabled. If you want to use `DjangoFilterBackend` remember to make sure it is installed by using the `'DEFAULT_FILTER_BACKENDS'` setting.
* When using boolean fields, you should use the values `True` and `False` in the URL query parameters, rather than `0`, `1`, `true` or `false`. (The allowed boolean values are currently hardwired in Django's [NullBooleanSelect implementation][nullbooleanselect].) * When using boolean fields, you should use the values `True` and `False` in the URL query parameters, rather than `0`, `1`, `true` or `false`. (The allowed boolean values are currently hardwired in Django's [NullBooleanSelect implementation][nullbooleanselect].)
* `django-filter` supports filtering across relationships, using Django's double-underscore syntax. * `django-filter` supports filtering across relationships, using Django's double-underscore syntax.
--- ---
### Filtering and object lookups ## Filtering and object lookups
Note that if a filter backend is configured for a view, then as well as being used to filter list views, it will also be used to filter the querysets used for returning a single object. Note that if a filter backend is configured for a view, then as well as being used to filter list views, it will also be used to filter the querysets used for returning a single object.
...@@ -172,12 +169,12 @@ You can also provide your own generic filtering backend, or write an installable ...@@ -172,12 +169,12 @@ You can also provide your own generic filtering backend, or write an installable
To do so override `BaseFilterBackend`, and override the `.filter_queryset(self, request, queryset, view)` method. The method should return a new, filtered queryset. To do so override `BaseFilterBackend`, and override the `.filter_queryset(self, request, queryset, view)` method. The method should return a new, filtered queryset.
To install the filter backend, set the `'FILTER_BACKEND'` key in your `'REST_FRAMEWORK'` setting, using the dotted import path of the filter backend class. To install the filter backend, set the `'DEFAULT_FILTER_BACKENDS'` key in your `'REST_FRAMEWORK'` setting, using the dotted import path of the filter backend class.
For example: For example:
REST_FRAMEWORK = { REST_FRAMEWORK = {
'FILTER_BACKEND': 'custom_filters.CustomFilterBackend' 'DEFAULT_FILTER_BACKENDS': ['custom_filters.CustomFilterBackend']
} }
[cite]: https://docs.djangoproject.com/en/dev/topics/db/queries/#retrieving-specific-objects-with-filters [cite]: https://docs.djangoproject.com/en/dev/topics/db/queries/#retrieving-specific-objects-with-filters
......
...@@ -93,7 +93,8 @@ The default pagination style may be set globally, using the `DEFAULT_PAGINATION_ ...@@ -93,7 +93,8 @@ The default pagination style may be set globally, using the `DEFAULT_PAGINATION_
You can also set the pagination style on a per-view basis, using the `ListAPIView` generic class-based view. You can also set the pagination style on a per-view basis, using the `ListAPIView` generic class-based view.
class PaginatedListView(ListAPIView): class PaginatedListView(ListAPIView):
model = ExampleModel queryset = ExampleModel.objects.all()
serializer_class = ExampleModelSerializer
paginate_by = 10 paginate_by = 10
paginate_by_param = 'page_size' paginate_by_param = 'page_size'
......
...@@ -34,7 +34,8 @@ The default set of parsers may be set globally, using the `DEFAULT_PARSER_CLASSE ...@@ -34,7 +34,8 @@ The default set of parsers may be set globally, using the `DEFAULT_PARSER_CLASSE
) )
} }
You can also set the renderers used for an individual view, using the `APIView` class based views. You can also set the renderers used for an individual view, or viewset,
using the `APIView` class based views.
class ExampleView(APIView): class ExampleView(APIView):
""" """
......
...@@ -44,7 +44,8 @@ If not specified, this setting defaults to allowing unrestricted access: ...@@ -44,7 +44,8 @@ If not specified, this setting defaults to allowing unrestricted access:
'rest_framework.permissions.AllowAny', 'rest_framework.permissions.AllowAny',
) )
You can also set the authentication policy on a per-view basis, using the `APIView` class based views. You can also set the authentication policy on a per-view, or per-viewset basis,
using the `APIView` class based views.
class ExampleView(APIView): class ExampleView(APIView):
permission_classes = (IsAuthenticated,) permission_classes = (IsAuthenticated,)
...@@ -101,15 +102,14 @@ This permission class ties into Django's standard `django.contrib.auth` [model p ...@@ -101,15 +102,14 @@ This permission class ties into Django's standard `django.contrib.auth` [model p
* `PUT` and `PATCH` requests require the user to have the `change` permission on the model. * `PUT` and `PATCH` requests require the user to have the `change` permission on the model.
* `DELETE` requests require the user to have the `delete` permission on the model. * `DELETE` requests require the user to have the `delete` permission on the model.
If you want to use `DjangoModelPermissions` but also allow unauthenticated users to have read permission, override the class and set the `authenticated_users_only` property to `False`. For example:
class HasModelPermissionsOrReadOnly(DjangoModelPermissions):
authenticated_users_only = False
The default behaviour can also be overridden to support custom model permissions. For example, you might want to include a `view` model permission for `GET` requests. The default behaviour can also be overridden to support custom model permissions. For example, you might want to include a `view` model permission for `GET` requests.
To use custom model permissions, override `DjangoModelPermissions` and set the `.perms_map` property. Refer to the source code for details. To use custom model permissions, override `DjangoModelPermissions` and set the `.perms_map` property. Refer to the source code for details.
## DjangoModelPermissionsOrAnonReadOnly
Similar to `DjangoModelPermissions`, but also allows unauthenticated users to have read-only access to the API.
## TokenHasReadWriteScope ## TokenHasReadWriteScope
This permission class is intended for use with either of the `OAuthAuthentication` and `OAuth2Authentication` classes, and ties into the scoping that their backends provide. This permission class is intended for use with either of the `OAuthAuthentication` and `OAuth2Authentication` classes, and ties into the scoping that their backends provide.
......
...@@ -123,9 +123,9 @@ Would serialize to a representation like this: ...@@ -123,9 +123,9 @@ Would serialize to a representation like this:
'album_name': 'Graceland', 'album_name': 'Graceland',
'artist': 'Paul Simon' 'artist': 'Paul Simon'
'tracks': [ 'tracks': [
'http://www.example.com/api/tracks/45', 'http://www.example.com/api/tracks/45/',
'http://www.example.com/api/tracks/46', 'http://www.example.com/api/tracks/46/',
'http://www.example.com/api/tracks/47', 'http://www.example.com/api/tracks/47/',
... ...
] ]
} }
...@@ -138,9 +138,7 @@ By default this field is read-write, although you can change this behavior using ...@@ -138,9 +138,7 @@ By default this field is read-write, although you can change this behavior using
* `many` - If applied to a to-many relationship, you should set this argument to `True`. * `many` - If applied to a to-many relationship, you should set this argument to `True`.
* `required` - If set to `False`, the field will accept values of `None` or the empty-string for nullable relationships. * `required` - If set to `False`, the field will accept values of `None` or the empty-string for nullable relationships.
* `queryset` - By default `ModelSerializer` classes will use the default queryset for the relationship. `Serializer` classes must either set a queryset explicitly, or set `read_only=True`. * `queryset` - By default `ModelSerializer` classes will use the default queryset for the relationship. `Serializer` classes must either set a queryset explicitly, or set `read_only=True`.
* `slug_field` - The field on the target that should be used for the lookup. Default is `'slug'`. * `lookup_field` - The field on the target that should be used for the lookup. Should correspond to a URL keyword argument on the referenced view. Default is `'pk'`.
* `pk_url_kwarg` - The named url parameter for the pk field lookup. Default is `pk`.
* `slug_url_kwarg` - The named url parameter for the slug field lookup. Default is to use the same value as given for `slug_field`.
* `format` - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the `format` argument. * `format` - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the `format` argument.
## SlugRelatedField ## SlugRelatedField
...@@ -196,7 +194,7 @@ Would serialize to a representation like this: ...@@ -196,7 +194,7 @@ Would serialize to a representation like this:
{ {
'album_name': 'The Eraser', 'album_name': 'The Eraser',
'artist': 'Thom Yorke' 'artist': 'Thom Yorke'
'track_listing': 'http://www.example.com/api/track_list/12', 'track_listing': 'http://www.example.com/api/track_list/12/',
} }
This field is always read-only. This field is always read-only.
...@@ -291,32 +289,23 @@ This custom field would then serialize to the following representation. ...@@ -291,32 +289,23 @@ This custom field would then serialize to the following representation.
## Reverse relations ## Reverse relations
Note that reverse relationships are not automatically generated by the `ModelSerializer` and `HyperlinkedModelSerializer` classes. To include a reverse relationship, you cannot simply add it to the fields list. Note that reverse relationships are not automatically included by the `ModelSerializer` and `HyperlinkedModelSerializer` classes. To include a reverse relationship, you must explicitly add it to the fields list. For example:
**The following will not work:**
class AlbumSerializer(serializers.ModelSerializer): class AlbumSerializer(serializers.ModelSerializer):
class Meta: class Meta:
fields = ('tracks', ...) fields = ('tracks', ...)
Instead, you must explicitly add it to the serializer. For example: You'll normally want to ensure that you've set an appropriate `related_name` argument on the relationship, that you can use as the field name. For example:
class AlbumSerializer(serializers.ModelSerializer):
tracks = serializers.PrimaryKeyRelatedField(many=True)
...
By default, the field will uses the same accessor as it's field name to retrieve the relationship, so in this example, `Album` instances would need to have the `tracks` attribute for this relationship to work.
The best way to ensure this is typically to make sure that the relationship on the model definition has it's `related_name` argument properly set. For example:
class Track(models.Model): class Track(models.Model):
album = models.ForeignKey(Album, related_name='tracks') album = models.ForeignKey(Album, related_name='tracks')
... ...
Alternatively, you can use the `source` argument on the serializer field, to use a different accessor attribute than the field name. For example. If you have not set a related name for the reverse relationship, you'll need to use the automatically generated related name in the `fields` argument. For example:
class AlbumSerializer(serializers.ModelSerializer): class AlbumSerializer(serializers.ModelSerializer):
tracks = serializers.PrimaryKeyRelatedField(many=True, source='track_set') class Meta:
fields = ('track_set', ...)
See the Django documentation on [reverse relationships][reverse-relationships] for more details. See the Django documentation on [reverse relationships][reverse-relationships] for more details.
...@@ -394,6 +383,40 @@ Note that reverse generic keys, expressed using the `GenericRelation` field, can ...@@ -394,6 +383,40 @@ Note that reverse generic keys, expressed using the `GenericRelation` field, can
For more information see [the Django documentation on generic relations][generic-relations]. For more information see [the Django documentation on generic relations][generic-relations].
## Advanced Hyperlinked fields
If you have very specific requirements for the style of your hyperlinked relationships you can override `HyperlinkedRelatedField`.
There are two methods you'll need to override.
#### get_url(self, obj, view_name, request, format)
This method should return the URL that corresponds to the given object.
May raise a `NoReverseMatch` if the `view_name` and `lookup_field`
attributes are not configured to correctly match the URL conf.
#### get_object(self, queryset, view_name, view_args, view_kwargs)
This method should the object that corresponds to the matched URL conf arguments.
May raise an `ObjectDoesNotExist` exception.
### Example
For example, if all your object URLs used both a account and a slug in the the URL to reference the object, you might create a custom field like this:
class CustomHyperlinkedField(serializers.HyperlinkedRelatedField):
def get_url(self, obj, view_name, request, format):
kwargs = {'account': obj.account, 'slug': obj.slug}
return reverse(view_name, kwargs=kwargs, request=request, format=format)
def get_object(self, queryset, view_name, view_args, view_kwargs):
account = view_kwargs['account']
slug = view_kwargs['slug']
return queryset.get(account=account, slug=sug)
--- ---
## Deprecated APIs ## Deprecated APIs
......
...@@ -27,7 +27,8 @@ The default set of renderers may be set globally, using the `DEFAULT_RENDERER_CL ...@@ -27,7 +27,8 @@ The default set of renderers may be set globally, using the `DEFAULT_RENDERER_CL
) )
} }
You can also set the renderers used for an individual view, using the `APIView` class based views. You can also set the renderers used for an individual view, or viewset,
using the `APIView` class based views.
class UserCountView(APIView): class UserCountView(APIView):
""" """
...@@ -127,7 +128,7 @@ An example of a view that uses `TemplateHTMLRenderer`: ...@@ -127,7 +128,7 @@ An example of a view that uses `TemplateHTMLRenderer`:
""" """
A view that returns a templated HTML representations of a given user. A view that returns a templated HTML representations of a given user.
""" """
model = Users queryset = User.objects.all()
renderer_classes = (TemplateHTMLRenderer,) renderer_classes = (TemplateHTMLRenderer,)
def get(self, request, *args, **kwargs) def get(self, request, *args, **kwargs)
......
<a class="github" href="routers.py"></a>
# Routers
> Resource routing allows you to quickly declare all of the common routes for a given resourceful controller. Instead of declaring separate routes for your index... a resourceful route declares them in a single line of code.
>
> &mdash; [Ruby on Rails Documentation][cite]
Some Web frameworks such as Rails provide functionality for automatically determining how the URLs for an application should be mapped to the logic that deals with handling incoming requests.
REST framework adds support for automatic URL routing to Django, and provides you with a simple, quick and consistent way of wiring your view logic to a set of URLs.
## Usage
Here's an example of a simple URL conf, that uses `DefaultRouter`.
router = routers.SimpleRouter()
router.register(r'users', UserViewSet)
router.register(r'accounts', AccountViewSet)
urlpatterns = router.urls
There are two mandatory arguments to the `register()` method:
* `prefix` - The URL prefix to use for this set of routes.
* `viewset` - The viewset class.
Optionally, you may also specify an additional argument:
* `base_name` - The base to use for the URL names that are created. If unset the basename will be automatically generated based on the `model` or `queryset` attribute on the viewset, if it has one.
The example above would generate the following URL patterns:
* URL pattern: `^users/$` Name: `'user-list'`
* URL pattern: `^users/{pk}/$` Name: `'user-detail'`
* URL pattern: `^accounts/$` Name: `'account-list'`
* URL pattern: `^accounts/{pk}/$` Name: `'account-detail'`
### Extra link and actions
Any methods on the viewset decorated with `@link` or `@action` will also be routed.
For example, a given method like this on the `UserViewSet` class:
@action(permission_classes=[IsAdminOrIsSelf])
def set_password(self, request, pk=None):
...
The following URL pattern would additionally be generated:
* URL pattern: `^users/{pk}/set_password/$` Name: `'user-set-password'`
# API Guide
## SimpleRouter
This router includes routes for the standard set of `list`, `create`, `retrieve`, `update`, `partial_update` and `destroy` actions. The viewset can also mark additional methods to be routed, using the `@link` or `@action` decorators.
<table border=1>
<tr><th>URL Style</th><th>HTTP Method</th><th>Action</th><th>URL Name</th></tr>
<tr><td rowspan=2>{prefix}/</td><td>GET</td><td>list</td><td rowspan=2>{basename}-list</td></tr></tr>
<tr><td>POST</td><td>create</td></tr>
<tr><td rowspan=4>{prefix}/{lookup}/</td><td>GET</td><td>retrieve</td><td rowspan=4>{basename}-detail</td></tr></tr>
<tr><td>PUT</td><td>update</td></tr>
<tr><td>PATCH</td><td>partial_update</td></tr>
<tr><td>DELETE</td><td>destroy</td></tr>
<tr><td rowspan=2>{prefix}/{lookup}/{methodname}/</td><td>GET</td><td>@link decorated method</td><td rowspan=2>{basename}-{methodname}</td></tr>
<tr><td>POST</td><td>@action decorated method</td></tr>
</table>
## DefaultRouter
This router is similar to `SimpleRouter` as above, but additionally includes a default API root view, that returns a response containing hyperlinks to all the list views. It also generates routes for optional `.json` style format suffixes.
<table border=1>
<tr><th>URL Style</th><th>HTTP Method</th><th>Action</th><th>URL Name</th></tr>
<tr><td>[.format]</td><td>GET</td><td>automatically generated root view</td><td>api-root</td></tr></tr>
<tr><td rowspan=2>{prefix}/[.format]</td><td>GET</td><td>list</td><td rowspan=2>{basename}-list</td></tr></tr>
<tr><td>POST</td><td>create</td></tr>
<tr><td rowspan=4>{prefix}/{lookup}/[.format]</td><td>GET</td><td>retrieve</td><td rowspan=4>{basename}-detail</td></tr></tr>
<tr><td>PUT</td><td>update</td></tr>
<tr><td>PATCH</td><td>partial_update</td></tr>
<tr><td>DELETE</td><td>destroy</td></tr>
<tr><td rowspan=2>{prefix}/{lookup}/{methodname}/[.format]</td><td>GET</td><td>@link decorated method</td><td rowspan=2>{basename}-{methodname}</td></tr>
<tr><td>POST</td><td>@action decorated method</td></tr>
</table>
# Custom Routers
Implementing a custom router isn't something you'd need to do very often, but it can be useful if you have specfic requirements about how the your URLs for your API are strutured. Doing so allows you to encapsulate the URL structure in a reusable way that ensures you don't have to write your URL patterns explicitly for each new view.
The simplest way to implement a custom router is to subclass one of the existing router classes. The `.routes` attribute is used to template the URL patterns that will be mapped to each viewset.
## Example
The following example will only route to the `list` and `retrieve` actions, and unlike the routers included by REST framework, it does not use the trailing slash convention.
class ReadOnlyRouter(SimpleRouter):
"""
A router for read-only APIs, which doesn't use trailing suffixes.
"""
routes = [
(r'^{prefix}$', {'get': 'list'}, '{basename}-list'),
(r'^{prefix}/{lookup}$', {'get': 'retrieve'}, '{basename}-detail')
]
## Advanced custom routers
If you want to provide totally custom behavior, you can override `BaseRouter` and override the `get_urls(self)` method. The method should insect the registered viewsets and return a list of URL patterns. The registered prefix, viewset and basename tuples may be inspected by accessing the `self.registry` attribute.
You may also want to override the `get_default_base_name(self, viewset)` method, or else always explicitly set the `base_name` argument when registering your viewsets with the router.
[cite]: http://guides.rubyonrails.org/routing.html
...@@ -295,7 +295,7 @@ The context dictionary can be used within any serializer field logic, such as a ...@@ -295,7 +295,7 @@ The context dictionary can be used within any serializer field logic, such as a
--- ---
# ModelSerializers # ModelSerializer
Often you'll want serializer classes that map closely to model definitions. Often you'll want serializer classes that map closely to model definitions.
The `ModelSerializer` class lets you automatically create a Serializer class with fields that correspond to the Model fields. The `ModelSerializer` class lets you automatically create a Serializer class with fields that correspond to the Model fields.
...@@ -306,7 +306,42 @@ The `ModelSerializer` class lets you automatically create a Serializer class wit ...@@ -306,7 +306,42 @@ The `ModelSerializer` class lets you automatically create a Serializer class wit
By default, all the model fields on the class will be mapped to corresponding serializer fields. By default, all the model fields on the class will be mapped to corresponding serializer fields.
Any foreign keys on the model will be mapped to `PrimaryKeyRelatedField` if you're using a `ModelSerializer`, or `HyperlinkedRelatedField` if you're using a `HyperlinkedModelSerializer`. Any relationships such as foreign keys on the model will be mapped to `PrimaryKeyRelatedField`. Other models fields will be mapped to a corresponding serializer field.
## Specifying which fields should be included
If you only want a subset of the default fields to be used in a model serializer, you can do so using `fields` or `exclude` options, just as you would with a `ModelForm`.
For example:
class AccountSerializer(serializers.ModelSerializer):
class Meta:
model = Account
fields = ('id', 'account_name', 'users', 'created')
## Specifying nested serialization
The default `ModelSerializer` uses primary keys for relationships, but you can also easily generate nested representations using the `depth` option:
class AccountSerializer(serializers.ModelSerializer):
class Meta:
model = Account
fields = ('id', 'account_name', 'users', 'created')
depth = 1
The `depth` option should be set to an integer value that indicates the depth of relationships that should be traversed before reverting to a flat representation.
## Specifying which fields should be read-only
You may wish to specify multiple fields as read-only. Instead of adding each field explicitly with the `read_only=True` attribute, you may use the `read_only_fields` Meta option, like so:
class AccountSerializer(serializers.ModelSerializer):
class Meta:
model = Account
fields = ('id', 'account_name', 'users', 'created')
read_only_fields = ('account_name',)
Model fields which have `editable=False` set, and `AutoField` fields will be set to read-only by default, and do not need to be added to the `read_only_fields` option.
## Specifying fields explicitly ## Specifying fields explicitly
...@@ -329,43 +364,68 @@ Alternative representations include serializing using hyperlinks, serializing co ...@@ -329,43 +364,68 @@ Alternative representations include serializing using hyperlinks, serializing co
For full details see the [serializer relations][relations] documentation. For full details see the [serializer relations][relations] documentation.
## Specifying which fields should be included ---
If you only want a subset of the default fields to be used in a model serializer, you can do so using `fields` or `exclude` options, just as you would with a `ModelForm`. # HyperlinkedModelSerializer
For example: The `HyperlinkedModelSerializer` class is similar to the `ModelSerializer` class except that it uses hyperlinks to represent relationships, rather than primary keys.
class AccountSerializer(serializers.ModelSerializer): By default the serializer will include a `url` field instead of a primary key field.
class Meta:
model = Account
exclude = ('id',)
## Specifiying nested serialization The url field will be represented using a `HyperlinkedIdentityField` serializer field, and any relationships on the model will be represented using a `HyperlinkedRelatedField` serializer field.
The default `ModelSerializer` uses primary keys for relationships, but you can also easily generate nested representations using the `depth` option: You can explicitly include the primary key by adding it to the `fields` option, for example:
class AccountSerializer(serializers.ModelSerializer): class AccountSerializer(serializers.HyperlinkedModelSerializer):
class Meta: class Meta:
model = Account model = Account
exclude = ('id',) fields = ('url', 'id', 'account_name', 'users', 'created')
depth = 1
The `depth` option should be set to an integer value that indicates the depth of relationships that should be traversed before reverting to a flat representation. ## How hyperlinked views are determined
## Specifying which fields should be read-only There needs to be a way of determining which views should be used for hyperlinking to model instances.
You may wish to specify multiple fields as read-only. Instead of adding each field explicitly with the `read_only=True` attribute, you may use the `read_only_fields` Meta option, like so: By default hyperlinks are expected to correspond to a view name that matches the style `'{model_name}-detail'`, and looks up the instance by a `pk` keyword argument.
class AccountSerializer(serializers.ModelSerializer): You can change the field that is used for object lookups by setting the `lookup_field` option. The value of this option should correspond both with a kwarg in the URL conf, and with an field on the model. For example:
class AccountSerializer(serializers.HyperlinkedModelSerializer):
class Meta: class Meta:
model = Account model = Account
read_only_fields = ('created', 'modified') fields = ('url', 'account_name', 'users', 'created')
lookup_field = 'slug'
For more specfic requirements such as specifying a different lookup for each field, you'll want to set the fields on the serializer explicitly. For example:
class AccountSerializer(serializers.HyperlinkedModelSerializer):
url = serializers.HyperlinkedIdentityField(
view_name='account_detail',
lookup_field='account_name'
)
users = serializers.HyperlinkedRelatedField(
view_name='user-detail',
lookup_field='username',
many=True,
read_only=True
)
class Meta:
model = Account
fields = ('url', 'account_name', 'users', 'created')
---
# Advanced serializer usage
You can create customized subclasses of `ModelSerializer` or `HyperlinkedModelSerializer` that use a different set of default fields.
Doing so should be considered advanced usage, and will only be needed if you have some particular serializer requirements that you often need to repeat.
## Customising the default fields ## Customising the default fields
You can create customized subclasses of `ModelSerializer` that use a different set of default fields for the representation, by overriding various `get_<field_type>_field` methods. The `field_mapping` attribute is a dictionary that maps model classes to serializer classes. Overriding the attribute will let you set a different set of default serializer classes.
Each of these methods may either return a field or serializer instance, or `None`. For more advanced customization than simply changing the default serializer class you can override various `get_<field_type>_field` methods. Doing so will allow you to customize the arguments that each serializer field is initialized with. Each of these methods may either return a field or serializer instance, or `None`.
### get_pk_field ### get_pk_field
...@@ -375,23 +435,27 @@ Returns the field instance that should be used to represent the pk field. ...@@ -375,23 +435,27 @@ Returns the field instance that should be used to represent the pk field.
### get_nested_field ### get_nested_field
**Signature**: `.get_nested_field(self, model_field)` **Signature**: `.get_nested_field(self, model_field, related_model, to_many)`
Returns the field instance that should be used to represent a related field when `depth` is specified as being non-zero. Returns the field instance that should be used to represent a related field when `depth` is specified as being non-zero.
Note that the `model_field` argument will be `None` for reverse relationships. The `related_model` argument will be the model class for the target of the field. The `to_many` argument will be a boolean indicating if this is a to-one or to-many relationship.
### get_related_field ### get_related_field
**Signature**: `.get_related_field(self, model_field, to_many=False)` **Signature**: `.get_related_field(self, model_field, related_model, to_many)`
Returns the field instance that should be used to represent a related field when `depth` is not specified, or when nested representations are being used and the depth reaches zero. Returns the field instance that should be used to represent a related field when `depth` is not specified, or when nested representations are being used and the depth reaches zero.
Note that the `model_field` argument will be `None` for reverse relationships. The `related_model` argument will be the model class for the target of the field. The `to_many` argument will be a boolean indicating if this is a to-one or to-many relationship.
### get_field ### get_field
**Signature**: `.get_field(self, model_field)` **Signature**: `.get_field(self, model_field)`
Returns the field instance that should be used for non-relational, non-pk fields. Returns the field instance that should be used for non-relational, non-pk fields.
### Example: ## Example
The following custom model serializer could be used as a base class for model serializers that should always exclude the pk by default. The following custom model serializer could be used as a base class for model serializers that should always exclude the pk by default.
......
...@@ -112,9 +112,10 @@ A class the determines the default serialization style for paginated responses. ...@@ -112,9 +112,10 @@ A class the determines the default serialization style for paginated responses.
Default: `rest_framework.pagination.PaginationSerializer` Default: `rest_framework.pagination.PaginationSerializer`
#### FILTER_BACKEND #### DEFAULT_FILTER_BACKENDS
The filter backend class that should be used for generic filtering. If set to `None` then generic filtering is disabled. A list of filter backend classes that should be used for generic filtering.
If set to `None` then generic filtering is disabled.
#### PAGINATE_BY #### PAGINATE_BY
......
...@@ -40,7 +40,8 @@ The default throttling policy may be set globally, using the `DEFAULT_THROTTLE_C ...@@ -40,7 +40,8 @@ The default throttling policy may be set globally, using the `DEFAULT_THROTTLE_C
The rate descriptions used in `DEFAULT_THROTTLE_RATES` may include `second`, `minute`, `hour` or `day` as the throttle period. The rate descriptions used in `DEFAULT_THROTTLE_RATES` may include `second`, `minute`, `hour` or `day` as the throttle period.
You can also set the throttling policy on a per-view basis, using the `APIView` class based views. You can also set the throttling policy on a per-view or per-viewset basis,
using the `APIView` class based views.
class ExampleView(APIView): class ExampleView(APIView):
throttle_classes = (UserThrottle,) throttle_classes = (UserThrottle,)
......
<a class="github" href="viewsets.py"></a>
# ViewSets
> After routing has determined which controller to use for a request, your controller is responsible for making sense of the request and producing the appropriate output.
>
> &mdash; [Ruby on Rails Documentation][cite]
Django REST framework allows you to combine the logic for a set of related views in a single class, called a `ViewSet`. In other frameworks you may also find conceptually similar implementations named something like 'Resources' or 'Controllers'.
A `ViewSet` class is simply **a type of class-based View, that does not provide any method handlers** such as `.get()` or `.post()`, and instead provides actions such as `.list()` and `.create()`.
The method handlers for a `ViewSet` are only bound to the corresponding actions at the point of finalizing the view, using the `.as_view()` method.
Typically, rather than exlicitly registering the views in a viewset in the urlconf, you'll register the viewset with a router class, that automatically determines the urlconf for you.
## Example
Let's define a simple viewset that can be used to listing or retrieving all the users in the system.
class UserViewSet(viewsets.ViewSet):
"""
A simple ViewSet that for listing or retrieving users.
"""
def list(self, request):
queryset = User.objects.all()
serializer = UserSerializer(queryset, many=True)
return Response(serializer.data)
def retrieve(self, request, pk=None):
queryset = User.objects.all()
user = get_object_or_404(queryset, pk=pk)
serializer = UserSerializer(user)
return Response(serializer.data)
If we need to, we can bind this viewset into two seperate views, like so:
user_list = UserViewSet.as_view({'get': 'list'})
user_detail = UserViewSet.as_view({'get': 'retrieve'})
Typically we wouldn't do this, but would instead register the viewset with a router, and allow the urlconf to be automatically generated.
router = DefaultRouter()
router.register(r'users', UserViewSet)
urlpatterns = router.urls
Rather than writing your own viewsets, you'll often want to use the existing base classes that provide a default set of behavior. For example:
class UserViewSet(viewsets.ModelViewSet):
"""
A viewset for viewing and editing user instances.
"""
serializer_class = UserSerializer
queryset = User.objects.all()
There are two main advantages of using a `ViewSet` class over using a `View` class.
* Repeated logic can be combined into a single class. In the above example, we only need to specify the `queryset` once, and it'll be used across multiple views.
* By using routers, we no longer need to deal with wiring up the URL conf ourselves.
Both of these come with a trade-off. Using regular views and URL confs is more explicit and gives you more control. ViewSets are helpful if you want to get up and running quickly, or when you have a large API and you want to enforce a consistent URL configuration throughout.
## Marking extra methods for routing
The default routers included with REST framework will provide routes for a standard set of create/retrieve/update/destroy style operations, as shown below:
class UserViewSet(viewsets.VietSet):
"""
Example empty viewset demonstrating the standard
actions that will be handled by a router class.
If you're using format suffixes, make sure to also include
the `format=None` keyword argument for each action.
"""
def list(self, request):
pass
def create(self, request):
pass
def retrieve(self, request, pk=None):
pass
def update(self, request, pk=None):
pass
def partial_update(self, request, pk=None):
pass
def destroy(self, request, pk=None):
pass
If you have ad-hoc methods that you need to be routed to, you can mark them as requiring routing using the `@link` or `@action` decorators. The `@link` decorator will route `GET` requests, and the `@action` decroator will route `POST` requests.
For example:
from django.contrib.auth.models import User
from rest_framework import viewsets
from rest_framework.decorators import action
from myapp.serializers import UserSerializer
class UserViewSet(viewsets.ModelViewSet):
"""
A viewset that provides the standard actions
"""
queryset = User.objects.all()
serializer_class = UserSerializer
@action
def set_password(self, request, pk=None):
user = self.get_object()
serializer = PasswordSerializer(data=request.DATA)
if serializer.is_valid():
user.set_password(serializer.data['password'])
user.save()
return Response({'status': 'password set'})
else:
return Response(serializer.errors,
status=status.HTTP_400_BAD_REQUEST)
The `@action` and `@link` decorators can additionally take extra arguments that will be set for the routed view only. For example...
@action(permission_classes=[IsAdminOrIsSelf])
def set_password(self, request, pk=None):
...
---
# API Reference
## ViewSet
The `ViewSet` class inherits from `APIView`. You can use any of the standard attributes such as `permission_classes`, `authentication_classes` in order to control the API policy on the viewset.
The `ViewSet` class does not provide any implementations of actions. In order to use a `ViewSet` class you'll override the class and define the action implementations explicitly.
## ModelViewSet
The `ModelViewSet` class inherits from `GenericAPIView` and includes implementations for various actions, by mixing in the behavior of the
The actions provided by the `ModelViewSet` class are `.list()`, `.retrieve()`, `.create()`, `.update()`, and `.destroy()`.
#### Example
Because `ModelViewSet` extends `GenericAPIView`, you'll normally need to provide at least the `queryset` and `serializer_class` attributes. For example:
class AccountViewSet(viewsets.ModelViewSet):
"""
A simple ViewSet for viewing and editing accounts.
"""
queryset = Account.objects.all()
serializer_class = AccountSerializer
permission_classes = [IsAccountAdminOrReadOnly]
Note that you can use any of the standard attributes or method overrides provided by `GenericAPIView`. For example, to use a `ViewSet` that dynamically determines the queryset it should operate on, you might do something like this:
class AccountViewSet(viewsets.ModelViewSet):
"""
A simple ViewSet for viewing and editing the accounts
associated with the user.
"""
serializer_class = AccountSerializer
permission_classes = [IsAccountAdminOrReadOnly]
def get_queryset(self):
return request.user.accounts.all()
Also note that although this class provides the complete set of create/list/retrieve/update/destroy actions by default, you can restrict the available operations by using the standard permission classes.
## ReadOnlyModelViewSet
The `ReadOnlyModelViewSet` class also inherits from `GenericAPIView`. As with `ModelViewSet` it also includes implementations for various actions, but unlike `ModelViewSet` only provides the 'read-only' actions, `.list()` and `.retrieve()`.
#### Example
As with `ModelViewSet`, you'll normally need to provide at least the `queryset` and `serializer_class` attributes. For example:
class AccountViewSet(viewsets.ReadOnlyModelViewSet):
"""
A simple ViewSet for viewing accounts.
"""
queryset = Account.objects.all()
serializer_class = AccountSerializer
Again, as with `ModelViewSet`, you can use any of the standard attributes and method overrides available to `GenericAPIView`.
# Custom ViewSet base classes
Any standard `View` class can be turned into a `ViewSet` class by mixing in `ViewSetMixin`. You can use this to define your own base classes.
## Example
For example, we can create a base viewset class that provides `retrieve`, `update` and `list` operations:
class RetrieveUpdateListViewSet(mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.ListModelMixin,
viewsets.ViewSetMixin,
generics.GenericAPIView):
"""
A viewset that provides `retrieve`, `update`, and `list` actions.
To use it, override the class and set the `.queryset` and
`.serializer_class` attributes.
"""
pass
By creating your own base `ViewSet` classes, you can provide common behavior that can be reused in multiple views across your API.
[cite]: http://guides.rubyonrails.org/routing.html
...@@ -288,3 +288,13 @@ footer a:hover { ...@@ -288,3 +288,13 @@ footer a:hover {
@media (max-width: 650px) { @media (max-width: 650px) {
.repo-link.btn-inverse {display: none;} .repo-link.btn-inverse {display: none;}
} }
td, th {
padding: 0.25em;
background-color: #f7f7f9;
border-color: #e1e1e8;
}
table {
border-color: white;
}
...@@ -11,13 +11,17 @@ ...@@ -11,13 +11,17 @@
**Awesome web-browsable Web APIs.** **Awesome web-browsable Web APIs.**
Django REST framework is a flexible, powerful Web API toolkit. It is designed as a modular and easy to customize architecture, based on Django's class based views. Django REST framework is a powerful and flexible toolkit that makes it easy to build Web APIs.
APIs built using REST framework are fully self-describing and web browsable - a huge useability win for your developers. It also supports a wide range of media types, authentication and permission policies out of the box. Some reasons you might want to use REST framework:
If you are considering using REST framework for your API, we recommend reading the [REST framework 2 announcement][rest-framework-2-announcement] which gives a good overview of the framework and it's capabilities. * The Web browseable API is a huge useability win for your developers.
* Authentication policies including OAuth1a and OAuth2 out of the box.
* Serialization that supports both ORM and non-ORM data sources.
* Customizable all the way down - just use regular function-based views if you don't need the more powerful features.
* Extensive documentation, and great community support.
There is also a sandbox API you can use for testing purposes, [available here][sandbox]. There is a live example API for testing purposes, [available here][sandbox].
**Below**: *Screenshot from the browsable API* **Below**: *Screenshot from the browsable API*
...@@ -47,15 +51,11 @@ Install using `pip`, including any optional packages you want... ...@@ -47,15 +51,11 @@ Install using `pip`, including any optional packages you want...
pip install djangorestframework pip install djangorestframework
pip install markdown # Markdown support for the browsable API. pip install markdown # Markdown support for the browsable API.
pip install pyyaml # YAML content-type support.
pip install django-filter # Filtering support pip install django-filter # Filtering support
...or clone the project from github. ...or clone the project from github.
git clone git@github.com:tomchristie/django-rest-framework.git git clone git@github.com:tomchristie/django-rest-framework.git
cd django-rest-framework
pip install -r requirements.txt
pip install -r optionals.txt
Add `'rest_framework'` to your `INSTALLED_APPS` setting. Add `'rest_framework'` to your `INSTALLED_APPS` setting.
...@@ -73,6 +73,57 @@ If you're intending to use the browsable API you'll probably also want to add RE ...@@ -73,6 +73,57 @@ If you're intending to use the browsable API you'll probably also want to add RE
Note that the URL path can be whatever you want, but you must include `'rest_framework.urls'` with the `'rest_framework'` namespace. Note that the URL path can be whatever you want, but you must include `'rest_framework.urls'` with the `'rest_framework'` namespace.
## Example
Let's take a look at a quick example of using REST framework to build a simple model-backed API.
We'll create a read-write API for accessing users and groups.
Any global settings for a REST framework API are kept in a single configuration dictionary named `REST_FRAMEWORK`. Start off by adding the following to your `settings.py` module:
REST_FRAMEWORK = {
# Use hyperlinked styles by default.
# Only used if the `serializer_class` attribute is not set on a view.
'DEFAULT_MODEL_SERIALIZER_CLASS':
'rest_framework.serializers.HyperlinkedModelSerializer',
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
]
}
Don't forget to make sure you've also added `rest_framework` to your `INSTALLED_APPS`.
We're ready to create our API now.
Here's our project's root `urls.py` module:
from django.conf.urls.defaults import url, patterns, include
from django.contrib.auth.models import User, Group
from rest_framework import viewsets, routers
# ViewSets define the view behavior.
class UserViewSet(viewsets.ModelViewSet):
model = User
class GroupViewSet(viewsets.ModelViewSet):
model = Group
# Routers provide an easy way of automatically determining the URL conf
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)
# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browseable API.
urlpatterns = patterns('',
url(r'^', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
)
## Quickstart ## Quickstart
Can't wait to get started? The [quickstart guide][quickstart] is the fastest way to get up and running, and building APIs with REST framework. Can't wait to get started? The [quickstart guide][quickstart] is the fastest way to get up and running, and building APIs with REST framework.
...@@ -86,6 +137,7 @@ The tutorial will walk you through the building blocks that make up REST framewo ...@@ -86,6 +137,7 @@ The tutorial will walk you through the building blocks that make up REST framewo
* [3 - Class based views][tut-3] * [3 - Class based views][tut-3]
* [4 - Authentication & permissions][tut-4] * [4 - Authentication & permissions][tut-4]
* [5 - Relationships & hyperlinked APIs][tut-5] * [5 - Relationships & hyperlinked APIs][tut-5]
* [6 - Viewsets & routers][tut-6]
## API Guide ## API Guide
...@@ -95,6 +147,8 @@ The API guide is your complete reference manual to all the functionality provide ...@@ -95,6 +147,8 @@ The API guide is your complete reference manual to all the functionality provide
* [Responses][response] * [Responses][response]
* [Views][views] * [Views][views]
* [Generic views][generic-views] * [Generic views][generic-views]
* [Viewsets][viewsets]
* [Routers][routers]
* [Parsers][parsers] * [Parsers][parsers]
* [Renderers][renderers] * [Renderers][renderers]
* [Serializers][serializers] * [Serializers][serializers]
...@@ -122,6 +176,7 @@ General guides to using REST framework. ...@@ -122,6 +176,7 @@ General guides to using REST framework.
* [REST, Hypermedia & HATEOAS][rest-hypermedia-hateoas] * [REST, Hypermedia & HATEOAS][rest-hypermedia-hateoas]
* [2.0 Announcement][rest-framework-2-announcement] * [2.0 Announcement][rest-framework-2-announcement]
* [2.2 Announcement][2.2-announcement] * [2.2 Announcement][2.2-announcement]
* [2.3 Announcement][2.3-announcement]
* [Release Notes][release-notes] * [Release Notes][release-notes]
* [Credits][credits] * [Credits][credits]
...@@ -197,11 +252,14 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ...@@ -197,11 +252,14 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
[tut-3]: tutorial/3-class-based-views.md [tut-3]: tutorial/3-class-based-views.md
[tut-4]: tutorial/4-authentication-and-permissions.md [tut-4]: tutorial/4-authentication-and-permissions.md
[tut-5]: tutorial/5-relationships-and-hyperlinked-apis.md [tut-5]: tutorial/5-relationships-and-hyperlinked-apis.md
[tut-6]: tutorial/6-viewsets-and-routers.md
[request]: api-guide/requests.md [request]: api-guide/requests.md
[response]: api-guide/responses.md [response]: api-guide/responses.md
[views]: api-guide/views.md [views]: api-guide/views.md
[generic-views]: api-guide/generic-views.md [generic-views]: api-guide/generic-views.md
[viewsets]: api-guide/viewsets.md
[routers]: api-guide/routers.md
[parsers]: api-guide/parsers.md [parsers]: api-guide/parsers.md
[renderers]: api-guide/renderers.md [renderers]: api-guide/renderers.md
[serializers]: api-guide/serializers.md [serializers]: api-guide/serializers.md
...@@ -226,6 +284,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ...@@ -226,6 +284,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
[contributing]: topics/contributing.md [contributing]: topics/contributing.md
[rest-framework-2-announcement]: topics/rest-framework-2-announcement.md [rest-framework-2-announcement]: topics/rest-framework-2-announcement.md
[2.2-announcement]: topics/2.2-announcement.md [2.2-announcement]: topics/2.2-announcement.md
[2.3-announcement]: topics/2.3-announcement.md
[release-notes]: topics/release-notes.md [release-notes]: topics/release-notes.md
[credits]: topics/credits.md [credits]: topics/credits.md
......
...@@ -62,6 +62,7 @@ ...@@ -62,6 +62,7 @@
<li><a href="{{ base_url }}/tutorial/3-class-based-views{{ suffix }}">3 - Class based views</a></li> <li><a href="{{ base_url }}/tutorial/3-class-based-views{{ suffix }}">3 - Class based views</a></li>
<li><a href="{{ base_url }}/tutorial/4-authentication-and-permissions{{ suffix }}">4 - Authentication and permissions</a></li> <li><a href="{{ base_url }}/tutorial/4-authentication-and-permissions{{ suffix }}">4 - Authentication and permissions</a></li>
<li><a href="{{ base_url }}/tutorial/5-relationships-and-hyperlinked-apis{{ suffix }}">5 - Relationships and hyperlinked APIs</a></li> <li><a href="{{ base_url }}/tutorial/5-relationships-and-hyperlinked-apis{{ suffix }}">5 - Relationships and hyperlinked APIs</a></li>
<li><a href="{{ base_url }}/tutorial/6-viewsets-and-routers{{ suffix }}">6 - Viewsets and routers</a></li>
</ul> </ul>
</li> </li>
<li class="dropdown"> <li class="dropdown">
...@@ -71,6 +72,8 @@ ...@@ -71,6 +72,8 @@
<li><a href="{{ base_url }}/api-guide/responses{{ suffix }}">Responses</a></li> <li><a href="{{ base_url }}/api-guide/responses{{ suffix }}">Responses</a></li>
<li><a href="{{ base_url }}/api-guide/views{{ suffix }}">Views</a></li> <li><a href="{{ base_url }}/api-guide/views{{ suffix }}">Views</a></li>
<li><a href="{{ base_url }}/api-guide/generic-views{{ suffix }}">Generic views</a></li> <li><a href="{{ base_url }}/api-guide/generic-views{{ suffix }}">Generic views</a></li>
<li><a href="{{ base_url }}/api-guide/viewsets{{ suffix }}">Viewsets</a></li>
<li><a href="{{ base_url }}/api-guide/routers{{ suffix }}">Routers</a></li>
<li><a href="{{ base_url }}/api-guide/parsers{{ suffix }}">Parsers</a></li> <li><a href="{{ base_url }}/api-guide/parsers{{ suffix }}">Parsers</a></li>
<li><a href="{{ base_url }}/api-guide/renderers{{ suffix }}">Renderers</a></li> <li><a href="{{ base_url }}/api-guide/renderers{{ suffix }}">Renderers</a></li>
<li><a href="{{ base_url }}/api-guide/serializers{{ suffix }}">Serializers</a></li> <li><a href="{{ base_url }}/api-guide/serializers{{ suffix }}">Serializers</a></li>
...@@ -98,6 +101,7 @@ ...@@ -98,6 +101,7 @@
<li><a href="{{ base_url }}/topics/rest-hypermedia-hateoas{{ suffix }}">REST, Hypermedia & HATEOAS</a></li> <li><a href="{{ base_url }}/topics/rest-hypermedia-hateoas{{ suffix }}">REST, Hypermedia & HATEOAS</a></li>
<li><a href="{{ base_url }}/topics/rest-framework-2-announcement{{ suffix }}">2.0 Announcement</a></li> <li><a href="{{ base_url }}/topics/rest-framework-2-announcement{{ suffix }}">2.0 Announcement</a></li>
<li><a href="{{ base_url }}/topics/2.2-announcement{{ suffix }}">2.2 Announcement</a></li> <li><a href="{{ base_url }}/topics/2.2-announcement{{ suffix }}">2.2 Announcement</a></li>
<li><a href="{{ base_url }}/topics/2.3-announcement{{ suffix }}">2.3 Announcement</a></li>
<li><a href="{{ base_url }}/topics/release-notes{{ suffix }}">Release Notes</a></li> <li><a href="{{ base_url }}/topics/release-notes{{ suffix }}">Release Notes</a></li>
<li><a href="{{ base_url }}/topics/credits{{ suffix }}">Credits</a></li> <li><a href="{{ base_url }}/topics/credits{{ suffix }}">Credits</a></li>
</ul> </ul>
......
# 2.0 Migration Guide
> Move fast and break things
>
> &mdash; Mark Zuckerberg, [the Hacker Way][cite].
REST framework 2.0 introduces a radical redesign of the core components, and a large number of backwards breaking changes.
### Serialization redesign.
REST framework's serialization and deserialization previously used a slightly odd combination of serializers for output, and Django Forms and Model Forms for input. The serialization core has been completely redesigned based on work that was originally intended for Django core.
2.0's form-like serializers comprehensively address those issues, and are a much more flexible and clean solution to the problems around accepting both form-based and non-form based inputs.
### Generic views improved.
When REST framework 0.1 was released the current Django version was 1.2. REST framework included a backport of the Django 1.3's upcoming `View` class, but it didn't take full advantage of the generic view implementations.
As of 2.0 the generic views in REST framework tie in much more cleanly and obviously with Django's existing codebase, and the mixin architecture is radically simplified.
### Cleaner request-response cycle.
REST framework 2.0's request-response cycle is now much less complex.
* Responses inherit from `SimpleTemplateResponse`, allowing rendering to be delegated to the response, not handled by the view.
* Requests extend the regular `HttpRequest`, allowing authentication and parsing to be delegated to the request, not handled by the view.
### Renamed attributes & classes.
Various attributes and classes have been renamed in order to fit in better with Django's conventions.
## Example: Blog Posts API
Let's take a look at an example from the REST framework 0.4 documentation...
from djangorestframework.resources import ModelResource
from djangorestframework.reverse import reverse
from blogpost.models import BlogPost, Comment
class BlogPostResource(ModelResource):
"""
A Blog Post has a *title* and *content*, and can be associated
with zero or more comments.
"""
model = BlogPost
fields = ('created', 'title', 'slug', 'content', 'url', 'comments')
ordering = ('-created',)
def url(self, instance):
return reverse('blog-post',
kwargs={'key': instance.key},
request=self.request)
def comments(self, instance):
return reverse('comments',
kwargs={'blogpost': instance.key},
request=self.request)
class CommentResource(ModelResource):
"""
A Comment is associated with a given Blog Post and has a
*username* and *comment*, and optionally a *rating*.
"""
model = Comment
fields = ('username', 'comment', 'created', 'rating', 'url', 'blogpost')
ordering = ('-created',)
def blogpost(self, instance):
return reverse('blog-post',
kwargs={'key': instance.blogpost.key},
request=self.request)
There's a bit of a mix of concerns going on there. We've got some information about how the data should be serialized, such as the `fields` attribute, and some information about how it should be retrieved from the database - the `ordering` attribute.
Let's start to re-write this for REST framework 2.0.
from rest_framework import serializers
class BlogPostSerializer(serializers.HyperlinkedModelSerializer):
model = BlogPost
fields = ('created', 'title', 'slug', 'content', 'url', 'comments')
class CommentSerializer(serializers.HyperlinkedModelSerializer):
model = Comment
fields = ('username', 'comment', 'created', 'rating', 'url', 'blogpost')
[cite]: http://www.wired.com/business/2012/02/zuck-letter/
...@@ -38,6 +38,22 @@ You can determine your currently installed version using `pip freeze`: ...@@ -38,6 +38,22 @@ You can determine your currently installed version using `pip freeze`:
--- ---
## 2.3.x series
### 2.3.0
* ViewSets and Routers.
* ModelSerializers support reverse relations in 'fields' option.
* HyperLinkedModelSerializers support 'id' field in 'fields' option.
* Cleaner generic views.
* Support for multiple filter classes.
* DecimalField support.
* Bugfix: Fix issue with depth>1 on ModelSerializer.
**Note**: See the [2.3 announcement][2.3-announcement] for full details.
---
## 2.2.x series ## 2.2.x series
### Master ### Master
...@@ -462,6 +478,7 @@ This change will not affect user code, so long as it's following the recommended ...@@ -462,6 +478,7 @@ This change will not affect user code, so long as it's following the recommended
[django-deprecation-policy]: https://docs.djangoproject.com/en/dev/internals/release-process/#internal-release-deprecation-policy [django-deprecation-policy]: https://docs.djangoproject.com/en/dev/internals/release-process/#internal-release-deprecation-policy
[defusedxml-announce]: http://blog.python.org/2013/02/announcing-defusedxml-fixes-for-xml.html [defusedxml-announce]: http://blog.python.org/2013/02/announcing-defusedxml-fixes-for-xml.html
[2.2-announcement]: 2.2-announcement.md [2.2-announcement]: 2.2-announcement.md
[2.3-announcement]: 2.3-announcement.md
[743]: https://github.com/tomchristie/django-rest-framework/pull/743 [743]: https://github.com/tomchristie/django-rest-framework/pull/743
[staticfiles14]: https://docs.djangoproject.com/en/1.4/howto/static-files/#with-a-template-tag [staticfiles14]: https://docs.djangoproject.com/en/1.4/howto/static-files/#with-a-template-tag
[staticfiles13]: https://docs.djangoproject.com/en/1.3/howto/static-files/#with-a-template-tag [staticfiles13]: https://docs.djangoproject.com/en/1.3/howto/static-files/#with-a-template-tag
......
...@@ -92,8 +92,8 @@ Let's take a look at how we can compose our views by using the mixin classes. ...@@ -92,8 +92,8 @@ Let's take a look at how we can compose our views by using the mixin classes.
class SnippetList(mixins.ListModelMixin, class SnippetList(mixins.ListModelMixin,
mixins.CreateModelMixin, mixins.CreateModelMixin,
generics.MultipleObjectAPIView): generics.GenericAPIView):
model = Snippet queryset = Snippet.objects.all()
serializer_class = SnippetSerializer serializer_class = SnippetSerializer
def get(self, request, *args, **kwargs): def get(self, request, *args, **kwargs):
...@@ -102,15 +102,15 @@ Let's take a look at how we can compose our views by using the mixin classes. ...@@ -102,15 +102,15 @@ Let's take a look at how we can compose our views by using the mixin classes.
def post(self, request, *args, **kwargs): def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs) return self.create(request, *args, **kwargs)
We'll take a moment to examine exactly what's happening here. We're building our view using `MultipleObjectAPIView`, and adding in `ListModelMixin` and `CreateModelMixin`. We'll take a moment to examine exactly what's happening here. We're building our view using `GenericAPIView`, and adding in `ListModelMixin` and `CreateModelMixin`.
The base class provides the core functionality, and the mixin classes provide the `.list()` and `.create()` actions. We're then explicitly binding the `get` and `post` methods to the appropriate actions. Simple enough stuff so far. The base class provides the core functionality, and the mixin classes provide the `.list()` and `.create()` actions. We're then explicitly binding the `get` and `post` methods to the appropriate actions. Simple enough stuff so far.
class SnippetDetail(mixins.RetrieveModelMixin, class SnippetDetail(mixins.RetrieveModelMixin,
mixins.UpdateModelMixin, mixins.UpdateModelMixin,
mixins.DestroyModelMixin, mixins.DestroyModelMixin,
generics.SingleObjectAPIView): generics.GenericAPIView):
model = Snippet queryset = Snippet.objects.all()
serializer_class = SnippetSerializer serializer_class = SnippetSerializer
def get(self, request, *args, **kwargs): def get(self, request, *args, **kwargs):
...@@ -122,7 +122,7 @@ The base class provides the core functionality, and the mixin classes provide th ...@@ -122,7 +122,7 @@ The base class provides the core functionality, and the mixin classes provide th
def delete(self, request, *args, **kwargs): def delete(self, request, *args, **kwargs):
return self.destroy(request, *args, **kwargs) return self.destroy(request, *args, **kwargs)
Pretty similar. This time we're using the `SingleObjectAPIView` class to provide the core functionality, and adding in mixins to provide the `.retrieve()`, `.update()` and `.destroy()` actions. Pretty similar. Again we're using the `GenericAPIView` class to provide the core functionality, and adding in mixins to provide the `.retrieve()`, `.update()` and `.destroy()` actions.
## Using generic class based views ## Using generic class based views
...@@ -134,12 +134,12 @@ Using the mixin classes we've rewritten the views to use slightly less code than ...@@ -134,12 +134,12 @@ Using the mixin classes we've rewritten the views to use slightly less code than
class SnippetList(generics.ListCreateAPIView): class SnippetList(generics.ListCreateAPIView):
model = Snippet queryset = Snippet.objects.all()
serializer_class = SnippetSerializer serializer_class = SnippetSerializer
class SnippetDetail(generics.RetrieveUpdateDestroyAPIView): class SnippetDetail(generics.RetrieveUpdateDestroyAPIView):
model = Snippet queryset = Snippet.objects.all()
serializer_class = SnippetSerializer serializer_class = SnippetSerializer
Wow, that's pretty concise. We've gotten a huge amount for free, and our code looks like good, clean, idiomatic Django. Wow, that's pretty concise. We've gotten a huge amount for free, and our code looks like good, clean, idiomatic Django.
......
...@@ -68,12 +68,12 @@ Because `'snippets'` is a *reverse* relationship on the User model, it will not ...@@ -68,12 +68,12 @@ Because `'snippets'` is a *reverse* relationship on the User model, it will not
We'll also add a couple of views. We'd like to just use read-only views for the user representations, so we'll use the `ListAPIView` and `RetrieveAPIView` generic class based views. We'll also add a couple of views. We'd like to just use read-only views for the user representations, so we'll use the `ListAPIView` and `RetrieveAPIView` generic class based views.
class UserList(generics.ListAPIView): class UserList(generics.ListAPIView):
model = User queryset = User.objects.all()
serializer_class = UserSerializer serializer_class = UserSerializer
class UserDetail(generics.RetrieveAPIView): class UserDetail(generics.RetrieveAPIView):
model = User queryset = User.objects.all()
serializer_class = UserSerializer serializer_class = UserSerializer
Finally we need to add those views into the API, by referencing them from the URL conf. Finally we need to add those views into the API, by referencing them from the URL conf.
......
...@@ -34,8 +34,8 @@ Instead of using a concrete generic view, we'll use the base class for represent ...@@ -34,8 +34,8 @@ Instead of using a concrete generic view, we'll use the base class for represent
from rest_framework import renderers from rest_framework import renderers
from rest_framework.response import Response from rest_framework.response import Response
class SnippetHighlight(generics.SingleObjectAPIView): class SnippetHighlight(generics.GenericAPIView):
model = Snippet queryset = Snippet.objects.all()
renderer_classes = (renderers.StaticHTMLRenderer,) renderer_classes = (renderers.StaticHTMLRenderer,)
def get(self, request, *args, **kwargs): def get(self, request, *args, **kwargs):
...@@ -143,34 +143,16 @@ We can change the default list style to use pagination, by modifying our `settin ...@@ -143,34 +143,16 @@ We can change the default list style to use pagination, by modifying our `settin
'PAGINATE_BY': 10 'PAGINATE_BY': 10
} }
Note that settings in REST framework are all namespaced into a single dictionary setting, named 'REST_FRAMEWORK', which helps keep them well seperated from your other project settings. Note that settings in REST framework are all namespaced into a single dictionary setting, named 'REST_FRAMEWORK', which helps keep them well separated from your other project settings.
We could also customize the pagination style if we needed too, but in this case we'll just stick with the default. We could also customize the pagination style if we needed too, but in this case we'll just stick with the default.
## Reviewing our work ## Browsing the API
If we open a browser and navigate to the browsable API, you'll find that you can now work your way around the API simply by following links. If we open a browser and navigate to the browsable API, you'll find that you can now work your way around the API simply by following links.
You'll also be able to see the 'highlight' links on the snippet instances, that will take you to the highlighted code HTML representations. You'll also be able to see the 'highlight' links on the snippet instances, that will take you to the highlighted code HTML representations.
We've now got a complete pastebin Web API, which is fully web browsable, and comes complete with authentication, per-object permissions, and multiple renderer formats. In [part 6][tut-6] of the tutorial we'll look at how we can use ViewSets and Routers to reduce the amount of code we need to build our API.
We've walked through each step of the design process, and seen how if we need to customize anything we can gradually work our way down to simply using regular Django views. [tut-6]: 6-viewsets-and-routers.md
You can review the final [tutorial code][repo] on GitHub, or try out a live example in [the sandbox][sandbox].
## Onwards and upwards
We've reached the end of our tutorial. If you want to get more involved in the REST framework project, here's a few places you can start:
* Contribute on [GitHub][github] by reviewing and submitting issues, and making pull requests.
* Join the [REST framework discussion group][group], and help build the community.
* Follow [the author][twitter] on Twitter and say hi.
**Now go build awesome things.**
[repo]: https://github.com/tomchristie/rest-framework-tutorial
[sandbox]: http://restframework.herokuapp.com/
[github]: https://github.com/tomchristie/django-rest-framework
[group]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework
[twitter]: https://twitter.com/_tomchristie
# Tutorial 6 - ViewSets & Routers
REST framework includes an abstraction for dealing with `ViewSets`, that allows the developer to concentrate on modeling the state and interactions of the API, and leave the URL construction to be handled automatically, based on common conventions.
`ViewSet` classes are almost the same thing as `View` classes, except that they provide operations such as `read`, or `update`, and not method handlers such as `get` or `put`.
A `ViewSet` class is only bound to a set of method handlers at the last moment, when it is instantiated into a set of views, typically by using a `Router` class which handles the complexities of defining the URL conf for you.
## Refactoring to use ViewSets
Let's take our current set of views, and refactor them into view sets.
First of all let's refactor our `UserListView` and `UserDetailView` views into a single `UserViewSet`. We can remove the two views, and replace then with a single class:
class UserViewSet(viewsets.ReadOnlyModelViewSet):
"""
This viewset automatically provides `list` and `detail` actions.
"""
queryset = User.objects.all()
serializer_class = UserSerializer
Here we've used `ReadOnlyModelViewSet` class to automatically provide the default 'read-only' operations. We're still setting the `queryset` and `serializer_class` attributes exactly as we did when we were using regular views, but we no longer need to provide the same information to two separate classes.
Next we're going to replace the `SnippetList`, `SnippetDetail` and `SnippetHighlight` view classes. We can remove the three views, and again replace them with a single class.
from rest_framework import viewsets
from rest_framework.decorators import link
class SnippetViewSet(viewsets.ModelViewSet):
"""
This viewset automatically provides `list`, `create`, `retrieve`,
`update` and `destroy` actions.
Additionally we also provide an extra `highlight` action.
"""
queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly,
IsOwnerOrReadOnly,)
@link(renderer_classes=[renderers.StaticHTMLRenderer])
def highlight(self, request, *args, **kwargs):
snippet = self.get_object()
return Response(snippet.highlighted)
def pre_save(self, obj):
obj.owner = self.request.user
This time we've used the `ModelViewSet` class in order to get the complete set of default read and write operations.
Notice that we've also used the `@link` decorator to create a custom action, named `highlight`. This decorator can be used to add any custom endpoints that don't fit into the standard `create`/`update`/`delete` style.
Custom actions which use the `@link` decorator will respond to `GET` requests. We could have instead used the `@action` decorator if we wanted an action that responded to `POST` requests.
## Binding ViewSets to URLs explicitly
The handler methods only get bound to the actions when we define the URLConf.
To see what's going on under the hood let's first explicitly create a set of views from our ViewSets.
In the `urls.py` file we bind our `ViewSet` classes into a set of concrete views.
from snippets.resources import SnippetResource, UserResource
snippet_list = SnippetViewSet.as_view({
'get': 'list',
'post': 'create'
})
snippet_detail = SnippetViewSet.as_view({
'get': 'retrieve',
'put': 'update',
'patch': 'partial_update',
'delete': 'destroy'
})
snippet_highlight = SnippetViewSet.as_view({
'get': 'highlight'
})
user_list = UserViewSet.as_view({
'get': 'list'
})
user_detail = UserViewSet.as_view({
'get': 'retrieve'
})
Notice how we're creating multiple views from each `ViewSet` class, by binding the http methods to the required action for each view.
Now that we've bound our resources into concrete views, that we can register the views with the URL conf as usual.
urlpatterns = format_suffix_patterns(patterns('snippets.views',
url(r'^$', 'api_root'),
url(r'^snippets/$', snippet_list, name='snippet-list'),
url(r'^snippets/(?P<pk>[0-9]+)/$', snippet_detail, name='snippet-detail'),
url(r'^snippets/(?P<pk>[0-9]+)/highlight/$', snippet_highlight, name='snippet-highlight'),
url(r'^users/$', user_list, name='user-list'),
url(r'^users/(?P<pk>[0-9]+)/$', user_detail, name='user-detail')
))
## Using Routers
Because we're using `ViewSet` classes rather than `View` classes, we actually don't need to design the URL conf ourselves. The conventions for wiring up resources into views and urls can be handled automatically, using a `Router` class. All we need to do is register the appropriate view sets with a router, and let it do the rest.
Here's our re-wired `urls.py` file.
from snippets import views
from rest_framework.routers import DefaultRouter
# Create a router and register our viewsets with it.
router = DefaultRouter()
router.register(r'snippets', views.SnippetViewSet)
router.register(r'users', views.UserViewSet)
# The API URLs are now determined automatically by the router.
# Additionally, we include the login URLs for the browseable API.
urlpatterns = patterns('',
url(r'^', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
)
Registering the viewsets with the router is similar to providing a urlpattern. We include two arguments - the URL prefix for the views, and the viewset itself.
The `DefaultRouter` class we're using also automatically creates the API root view for us, so we can now delete the `api_root` method from our `views` module.
## Trade-offs between views vs viewsets.
Using viewsets can be a really useful abstraction. It helps ensure that URL conventions will be consistent across your API, minimizes the amount of code you need to write, and allows you to concentrate on the interactions and representations your API provides rather than the specifics of the URL conf.
That doesn't mean it's always the right approach to take. There's a similar set of trade-offs to consider as when using class-based views instead of function based views. Using viewsets is less explicit than building your views individually.
## Reviewing our work
With an incredibly small amount of code, we've now got a complete pastebin Web API, which is fully web browseable, and comes complete with authentication, per-object permissions, and multiple renderer formats.
We've walked through each step of the design process, and seen how if we need to customize anything we can gradually work our way down to simply using regular Django views.
You can review the final [tutorial code][repo] on GitHub, or try out a live example in [the sandbox][sandbox].
## Onwards and upwards
We've reached the end of our tutorial. If you want to get more involved in the REST framework project, here's a few places you can start:
* Contribute on [GitHub][github] by reviewing and submitting issues, and making pull requests.
* Join the [REST framework discussion group][group], and help build the community.
* Follow [the author][twitter] on Twitter and say hi.
**Now go build awesome things.**
[repo]: https://github.com/tomchristie/rest-framework-tutorial
[sandbox]: http://restframework.herokuapp.com/
[github]: https://github.com/tomchristie/django-rest-framework
[group]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework
[twitter]: https://twitter.com/_tomchristie
...@@ -8,7 +8,7 @@ Create a new Django project, and start a new app called `quickstart`. Once you' ...@@ -8,7 +8,7 @@ Create a new Django project, and start a new app called `quickstart`. Once you'
First up we're going to define some serializers in `quickstart/serializers.py` that we'll use for our data representations. First up we're going to define some serializers in `quickstart/serializers.py` that we'll use for our data representations.
from django.contrib.auth.models import User, Group, Permission from django.contrib.auth.models import User, Group
from rest_framework import serializers from rest_framework import serializers
...@@ -19,109 +19,68 @@ First up we're going to define some serializers in `quickstart/serializers.py` t ...@@ -19,109 +19,68 @@ First up we're going to define some serializers in `quickstart/serializers.py` t
class GroupSerializer(serializers.HyperlinkedModelSerializer): class GroupSerializer(serializers.HyperlinkedModelSerializer):
permissions = serializers.ManySlugRelatedField(
slug_field='codename',
queryset=Permission.objects.all()
)
class Meta: class Meta:
model = Group model = Group
fields = ('url', 'name', 'permissions') fields = ('url', 'name')
Notice that we're using hyperlinked relations in this case, with `HyperlinkedModelSerializer`. You can also use primary key and various other relationships, but hyperlinking is good RESTful design. Notice that we're using hyperlinked relations in this case, with `HyperlinkedModelSerializer`. You can also use primary key and various other relationships, but hyperlinking is good RESTful design.
We've also overridden the `permission` field on the `GroupSerializer`. In this case we don't want to use a hyperlinked representation, but instead use the list of permission codenames associated with the group, so we've used a `ManySlugRelatedField`, using the `codename` field for the representation.
## Views ## Views
Right, we'd better write some views then. Open `quickstart/views.py` and get typing. Right, we'd better write some views then. Open `quickstart/views.py` and get typing.
from django.contrib.auth.models import User, Group from django.contrib.auth.models import User, Group
from rest_framework import generics from rest_framework import viewsets
from rest_framework.decorators import api_view
from rest_framework.reverse import reverse
from rest_framework.response import Response
from quickstart.serializers import UserSerializer, GroupSerializer from quickstart.serializers import UserSerializer, GroupSerializer
@api_view(['GET']) class UserViewSet(viewsets.ModelViewSet):
def api_root(request, format=None):
"""
The entry endpoint of our API.
"""
return Response({
'users': reverse('user-list', request=request),
'groups': reverse('group-list', request=request),
})
class UserList(generics.ListCreateAPIView):
""" """
API endpoint that represents a list of users. API endpoint that allows users to be viewed or edited.
""" """
model = User queryset = User.objects.all()
serializer_class = UserSerializer serializer_class = UserSerializer
class UserDetail(generics.RetrieveUpdateDestroyAPIView): class GroupViewSet(viewsets.ModelViewSet):
""" """
API endpoint that represents a single user. API endpoint that allows groups to be viewed or edited.
"""
model = User
serializer_class = UserSerializer
class GroupList(generics.ListCreateAPIView):
""" """
API endpoint that represents a list of groups. queryset = Group.objects.all()
"""
model = Group
serializer_class = GroupSerializer serializer_class = GroupSerializer
Rather that write multiple views we're grouping together all the common behavior into classes called `ViewSets`.
class GroupDetail(generics.RetrieveUpdateDestroyAPIView): We can easily break these down into individual views if we need to, but using viewsets keeps the view logic nicely organized as well as being very concise.
"""
API endpoint that represents a single group.
"""
model = Group
serializer_class = GroupSerializer
Let's take a moment to look at what we've done here before we move on. We have one function-based view representing the root of the API, and four class-based views which map to our database models, and specify which serializers should be used for representing that data. Pretty simple stuff.
## URLs ## URLs
Okay, let's wire this baby up. On to `quickstart/urls.py`... Okay, now let's wire up the API URLs. On to `quickstart/urls.py`...
from django.conf.urls import patterns, url, include from django.conf.urls import patterns, url, include
from rest_framework.urlpatterns import format_suffix_patterns from rest_framework import routers
from quickstart.views import UserList, UserDetail, GroupList, GroupDetail from quickstart import views
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)
urlpatterns = patterns('quickstart.views', # Wire up our API using automatic URL routing.
url(r'^$', 'api_root'), # Additionally, we include login URLs for the browseable API.
url(r'^users/$', UserList.as_view(), name='user-list'), urlpatterns = patterns('',
url(r'^users/(?P<pk>\d+)/$', UserDetail.as_view(), name='user-detail'), url(r'^', include(router.urls)),
url(r'^groups/$', GroupList.as_view(), name='group-list'),
url(r'^groups/(?P<pk>\d+)/$', GroupDetail.as_view(), name='group-detail'),
)
# Format suffixes
urlpatterns = format_suffix_patterns(urlpatterns, allowed=['json', 'api'])
# Default login/logout views
urlpatterns += patterns('',
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
) )
There's a few things worth noting here. Because we're using viewsets instead of views, we can automatically generate the URL conf for our API, by simply registering the viewsets with a router class.
Firstly the names `user-detail` and `group-detail` are important. We're using the default hyperlinked relationships without explicitly specifying the view names, so we need to use names of the style `{modelname}-detail` to represent the model instance views.
Secondly, we're modifying the urlpatterns using `format_suffix_patterns`, to append optional `.json` style suffixes to our URLs. Again, if we need more control over the API URLs we can simply drop down to using regular class based views, and writing the URL conf explicitly.
<<<<<<< HEAD
Note that we're also including default login and logout views for use with the browsable API. That's optional, but useful if your API requires authentication and you want to use the browseable API.
=======
Finally, we're including default login and logout views for use with the browsable API. That's optional, but useful if your API requires authentication and you want to use the browsable API. Finally, we're including default login and logout views for use with the browsable API. That's optional, but useful if your API requires authentication and you want to use the browsable API.
>>>>>>> master
## Settings ## Settings
......
...@@ -47,10 +47,13 @@ path_list = [ ...@@ -47,10 +47,13 @@ path_list = [
'tutorial/3-class-based-views.md', 'tutorial/3-class-based-views.md',
'tutorial/4-authentication-and-permissions.md', 'tutorial/4-authentication-and-permissions.md',
'tutorial/5-relationships-and-hyperlinked-apis.md', 'tutorial/5-relationships-and-hyperlinked-apis.md',
'tutorial/6-viewsets-and-routers.md',
'api-guide/requests.md', 'api-guide/requests.md',
'api-guide/responses.md', 'api-guide/responses.md',
'api-guide/views.md', 'api-guide/views.md',
'api-guide/generic-views.md', 'api-guide/generic-views.md',
'api-guide/viewsets.md',
'api-guide/routers.md',
'api-guide/parsers.md', 'api-guide/parsers.md',
'api-guide/renderers.md', 'api-guide/renderers.md',
'api-guide/serializers.md', 'api-guide/serializers.md',
...@@ -74,6 +77,7 @@ path_list = [ ...@@ -74,6 +77,7 @@ path_list = [
'topics/contributing.md', 'topics/contributing.md',
'topics/rest-framework-2-announcement.md', 'topics/rest-framework-2-announcement.md',
'topics/2.2-announcement.md', 'topics/2.2-announcement.md',
'topics/2.3-announcement.md',
'topics/release-notes.md', 'topics/release-notes.md',
'topics/credits.md', 'topics/credits.md',
] ]
...@@ -133,7 +137,7 @@ for (dirpath, dirnames, filenames) in os.walk(docs_dir): ...@@ -133,7 +137,7 @@ for (dirpath, dirnames, filenames) in os.walk(docs_dir):
toc += template + '\n' toc += template + '\n'
if filename == 'index.md': if filename == 'index.md':
main_title = 'Django REST framework - Web Browsable APIs' main_title = 'Django REST framework - APIs made easy'
else: else:
main_title = 'Django REST framework - ' + main_title main_title = 'Django REST framework - ' + main_title
......
""" """
Provides a set of pluggable authentication policies. Provides various authentication policies.
""" """
from __future__ import unicode_literals from __future__ import unicode_literals
import base64 import base64
......
...@@ -88,9 +88,7 @@ else: ...@@ -88,9 +88,7 @@ else:
raise ImportError("User model is not to be found.") raise ImportError("User model is not to be found.")
# First implementation of Django class-based views did not include head method if django.VERSION >= (1, 5):
# in base View class - https://code.djangoproject.com/ticket/15668
if django.VERSION >= (1, 4):
from django.views.generic import View from django.views.generic import View
else: else:
from django.views.generic import View as _View from django.views.generic import View as _View
...@@ -98,6 +96,8 @@ else: ...@@ -98,6 +96,8 @@ else:
from django.utils.functional import update_wrapper from django.utils.functional import update_wrapper
class View(_View): class View(_View):
# 1.3 does not include head method in base View class
# See: https://code.djangoproject.com/ticket/15668
@classonlymethod @classonlymethod
def as_view(cls, **initkwargs): def as_view(cls, **initkwargs):
""" """
...@@ -127,11 +127,15 @@ else: ...@@ -127,11 +127,15 @@ else:
update_wrapper(view, cls.dispatch, assigned=()) update_wrapper(view, cls.dispatch, assigned=())
return view return view
# Taken from @markotibold's attempt at supporting PATCH. # _allowed_methods only present from 1.5 onwards
# https://github.com/markotibold/django-rest-framework/tree/patch def _allowed_methods(self):
http_method_names = set(View.http_method_names) return [m.upper() for m in self.http_method_names if hasattr(self, m)]
http_method_names.add('patch')
View.http_method_names = list(http_method_names) # PATCH method is not implemented by Django
# PATCH method is not implemented by Django
if 'patch' not in View.http_method_names:
View.http_method_names = View.http_method_names + ['patch']
# PUT, DELETE do not require CSRF until 1.4. They should. Make it better. # PUT, DELETE do not require CSRF until 1.4. They should. Make it better.
if django.VERSION >= (1, 4): if django.VERSION >= (1, 4):
......
"""
The most imporant decorator in this module is `@api_view`, which is used
for writing function-based views with REST framework.
There are also various decorators for setting the API policies on function
based views, as well as the `@action` and `@link` decorators, which are
used to annotate methods on viewsets that should be included by routers.
"""
from __future__ import unicode_literals from __future__ import unicode_literals
from rest_framework.compat import six from rest_framework.compat import six
from rest_framework.views import APIView from rest_framework.views import APIView
...@@ -97,3 +105,25 @@ def permission_classes(permission_classes): ...@@ -97,3 +105,25 @@ def permission_classes(permission_classes):
func.permission_classes = permission_classes func.permission_classes = permission_classes
return func return func
return decorator return decorator
def link(**kwargs):
"""
Used to mark a method on a ViewSet that should be routed for GET requests.
"""
def decorator(func):
func.bind_to_method = 'get'
func.kwargs = kwargs
return func
return decorator
def action(**kwargs):
"""
Used to mark a method on a ViewSet that should be routed for POST requests.
"""
def decorator(func):
func.bind_to_method = 'post'
func.kwargs = kwargs
return func
return decorator
"""
Serializer fields perform validation on incoming data.
They are very similar to Django's form fields.
"""
from __future__ import unicode_literals from __future__ import unicode_literals
import copy import copy
import datetime import datetime
from decimal import Decimal, DecimalException
import inspect import inspect
import re import re
import warnings import warnings
...@@ -194,9 +200,9 @@ class WritableField(Field): ...@@ -194,9 +200,9 @@ class WritableField(Field):
# 'blank' is to be deprecated in favor of 'required' # 'blank' is to be deprecated in favor of 'required'
if blank is not None: if blank is not None:
warnings.warn('The `blank` keyword argument is due to deprecated. ' warnings.warn('The `blank` keyword argument is deprecated. '
'Use the `required` keyword argument instead.', 'Use the `required` keyword argument instead.',
PendingDeprecationWarning, stacklevel=2) DeprecationWarning, stacklevel=2)
required = not(blank) required = not(blank)
super(WritableField, self).__init__(source=source) super(WritableField, self).__init__(source=source)
...@@ -721,6 +727,75 @@ class FloatField(WritableField): ...@@ -721,6 +727,75 @@ class FloatField(WritableField):
raise ValidationError(msg) raise ValidationError(msg)
class DecimalField(WritableField):
type_name = 'DecimalField'
form_field_class = forms.DecimalField
default_error_messages = {
'invalid': _('Enter a number.'),
'max_value': _('Ensure this value is less than or equal to %(limit_value)s.'),
'min_value': _('Ensure this value is greater than or equal to %(limit_value)s.'),
'max_digits': _('Ensure that there are no more than %s digits in total.'),
'max_decimal_places': _('Ensure that there are no more than %s decimal places.'),
'max_whole_digits': _('Ensure that there are no more than %s digits before the decimal point.')
}
def __init__(self, max_value=None, min_value=None, max_digits=None, decimal_places=None, *args, **kwargs):
self.max_value, self.min_value = max_value, min_value
self.max_digits, self.decimal_places = max_digits, decimal_places
super(DecimalField, self).__init__(*args, **kwargs)
if max_value is not None:
self.validators.append(validators.MaxValueValidator(max_value))
if min_value is not None:
self.validators.append(validators.MinValueValidator(min_value))
def from_native(self, value):
"""
Validates that the input is a decimal number. Returns a Decimal
instance. Returns None for empty values. Ensures that there are no more
than max_digits in the number, and no more than decimal_places digits
after the decimal point.
"""
if value in validators.EMPTY_VALUES:
return None
value = smart_text(value).strip()
try:
value = Decimal(value)
except DecimalException:
raise ValidationError(self.error_messages['invalid'])
return value
def validate(self, value):
super(DecimalField, self).validate(value)
if value in validators.EMPTY_VALUES:
return
# Check for NaN, Inf and -Inf values. We can't compare directly for NaN,
# since it is never equal to itself. However, NaN is the only value that
# isn't equal to itself, so we can use this to identify NaN
if value != value or value == Decimal("Inf") or value == Decimal("-Inf"):
raise ValidationError(self.error_messages['invalid'])
sign, digittuple, exponent = value.as_tuple()
decimals = abs(exponent)
# digittuple doesn't include any leading zeros.
digits = len(digittuple)
if decimals > digits:
# We have leading zeros up to or past the decimal point. Count
# everything past the decimal point as a digit. We do not count
# 0 before the decimal point as a digit since that would mean
# we would not allow max_digits = decimal_places.
digits = decimals
whole_digits = digits - decimals
if self.max_digits is not None and digits > self.max_digits:
raise ValidationError(self.error_messages['max_digits'] % self.max_digits)
if self.decimal_places is not None and decimals > self.decimal_places:
raise ValidationError(self.error_messages['max_decimal_places'] % self.decimal_places)
if self.max_digits is not None and self.decimal_places is not None and whole_digits > (self.max_digits - self.decimal_places):
raise ValidationError(self.error_messages['max_whole_digits'] % (self.max_digits - self.decimal_places))
return value
class FileField(WritableField): class FileField(WritableField):
use_files = True use_files = True
type_name = 'FileField' type_name = 'FileField'
......
"""
Provides generic filtering backends that can be used to filter the results
returned by list views.
"""
from __future__ import unicode_literals from __future__ import unicode_literals
from django.db import models
from rest_framework.compat import django_filters from rest_framework.compat import django_filters
import operator
FilterSet = django_filters and django_filters.FilterSet or None FilterSet = django_filters and django_filters.FilterSet or None
...@@ -58,3 +65,29 @@ class DjangoFilterBackend(BaseFilterBackend): ...@@ -58,3 +65,29 @@ class DjangoFilterBackend(BaseFilterBackend):
return filter_class(request.QUERY_PARAMS, queryset=queryset).qs return filter_class(request.QUERY_PARAMS, queryset=queryset).qs
return queryset return queryset
class SearchFilter(BaseFilterBackend):
def construct_search(self, field_name):
if field_name.startswith('^'):
return "%s__istartswith" % field_name[1:]
elif field_name.startswith('='):
return "%s__iexact" % field_name[1:]
elif field_name.startswith('@'):
return "%s__search" % field_name[1:]
else:
return "%s__icontains" % field_name
def filter_queryset(self, request, queryset, view):
search_fields = getattr(view, 'search_fields', None)
if not search_fields:
return None
orm_lookups = [self.construct_search(str(search_field))
for search_field in self.search_fields]
for bit in self.query.split():
or_queries = [models.Q(**{orm_lookup: bit})
for orm_lookup in orm_lookups]
queryset = queryset.filter(reduce(operator.or_, or_queries))
return queryset
...@@ -12,7 +12,7 @@ from rest_framework.response import Response ...@@ -12,7 +12,7 @@ from rest_framework.response import Response
from rest_framework.request import clone_request from rest_framework.request import clone_request
def _get_validation_exclusions(obj, pk=None, slug_field=None): def _get_validation_exclusions(obj, pk=None, slug_field=None, lookup_field=None):
""" """
Given a model instance, and an optional pk and slug field, Given a model instance, and an optional pk and slug field,
return the full list of all other field names on that model. return the full list of all other field names on that model.
...@@ -23,14 +23,19 @@ def _get_validation_exclusions(obj, pk=None, slug_field=None): ...@@ -23,14 +23,19 @@ def _get_validation_exclusions(obj, pk=None, slug_field=None):
include = [] include = []
if pk: if pk:
# Pending deprecation
pk_field = obj._meta.pk pk_field = obj._meta.pk
while pk_field.rel: while pk_field.rel:
pk_field = pk_field.rel.to._meta.pk pk_field = pk_field.rel.to._meta.pk
include.append(pk_field.name) include.append(pk_field.name)
if slug_field: if slug_field:
# Pending deprecation
include.append(slug_field) include.append(slug_field)
if lookup_field and lookup_field != 'pk':
include.append(lookup_field)
return [field.name for field in obj._meta.fields if field.name not in include] return [field.name for field in obj._meta.fields if field.name not in include]
...@@ -67,23 +72,18 @@ class ListModelMixin(object): ...@@ -67,23 +72,18 @@ class ListModelMixin(object):
empty_error = "Empty list and '%(class_name)s.allow_empty' is False." empty_error = "Empty list and '%(class_name)s.allow_empty' is False."
def list(self, request, *args, **kwargs): def list(self, request, *args, **kwargs):
queryset = self.get_queryset() self.object_list = self.filter_queryset(self.get_queryset())
self.object_list = self.filter_queryset(queryset)
# Default is to allow empty querysets. This can be altered by setting # Default is to allow empty querysets. This can be altered by setting
# `.allow_empty = False`, to raise 404 errors on empty querysets. # `.allow_empty = False`, to raise 404 errors on empty querysets.
allow_empty = self.get_allow_empty() if not self.allow_empty and not self.object_list:
if not allow_empty and not self.object_list:
class_name = self.__class__.__name__ class_name = self.__class__.__name__
error_msg = self.empty_error % {'class_name': class_name} error_msg = self.empty_error % {'class_name': class_name}
raise Http404(error_msg) raise Http404(error_msg)
# Pagination size is set by the `.paginate_by` attribute, # Switch between paginated or standard style responses
# which may be `None` to disable pagination. page = self.paginate_queryset(self.object_list)
page_size = self.get_paginate_by(self.object_list) if page is not None:
if page_size:
packed = self.paginate_queryset(self.object_list, page_size)
paginator, page, queryset, is_paginated = packed
serializer = self.get_pagination_serializer(page) serializer = self.get_pagination_serializer(page)
else: else:
serializer = self.get_serializer(self.object_list, many=True) serializer = self.get_serializer(self.object_list, many=True)
...@@ -135,14 +135,22 @@ class UpdateModelMixin(object): ...@@ -135,14 +135,22 @@ class UpdateModelMixin(object):
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def partial_update(self, request, *args, **kwargs):
kwargs['partial'] = True
return self.update(request, *args, **kwargs)
def pre_save(self, obj): def pre_save(self, obj):
""" """
Set any attributes on the object that are implicit in the request. Set any attributes on the object that are implicit in the request.
""" """
# pk and/or slug attributes are implicit in the URL. # pk and/or slug attributes are implicit in the URL.
lookup = self.kwargs.get(self.lookup_field, None)
pk = self.kwargs.get(self.pk_url_kwarg, None) pk = self.kwargs.get(self.pk_url_kwarg, None)
slug = self.kwargs.get(self.slug_url_kwarg, None) slug = self.kwargs.get(self.slug_url_kwarg, None)
slug_field = slug and self.get_slug_field() or None slug_field = slug and self.slug_field or None
if lookup:
setattr(obj, self.lookup_field, lookup)
if pk: if pk:
setattr(obj, 'pk', pk) setattr(obj, 'pk', pk)
...@@ -153,7 +161,7 @@ class UpdateModelMixin(object): ...@@ -153,7 +161,7 @@ class UpdateModelMixin(object):
# Ensure we clean the attributes so that we don't eg return integer # Ensure we clean the attributes so that we don't eg return integer
# pk using a string representation, as provided by the url conf kwarg. # pk using a string representation, as provided by the url conf kwarg.
if hasattr(obj, 'full_clean'): if hasattr(obj, 'full_clean'):
exclude = _get_validation_exclusions(obj, pk, slug_field) exclude = _get_validation_exclusions(obj, pk, slug_field, self.lookup_field)
obj.full_clean(exclude) obj.full_clean(exclude)
......
"""
Content negotiation deals with selecting an appropriate renderer given the
incoming request. Typically this will be based on the request's Accept header.
"""
from __future__ import unicode_literals from __future__ import unicode_literals
from django.http import Http404 from django.http import Http404
from rest_framework import exceptions from rest_framework import exceptions
......
"""
Pagination serializers determine the structure of the output that should
be used for paginated responses.
"""
from __future__ import unicode_literals from __future__ import unicode_literals
from rest_framework import serializers from rest_framework import serializers
from rest_framework.templatetags.rest_framework import replace_query_param from rest_framework.templatetags.rest_framework import replace_query_param
# TODO: Support URLconf kwarg-style paging
class NextPageField(serializers.Field): class NextPageField(serializers.Field):
""" """
......
...@@ -25,10 +25,12 @@ class BasePermission(object): ...@@ -25,10 +25,12 @@ class BasePermission(object):
""" """
Return `True` if permission is granted, `False` otherwise. Return `True` if permission is granted, `False` otherwise.
""" """
if len(inspect.getargspec(self.has_permission)[0]) == 4: if len(inspect.getargspec(self.has_permission).args) == 4:
warnings.warn('The `obj` argument in `has_permission` is due to be deprecated. ' warnings.warn(
'The `obj` argument in `has_permission` is deprecated. '
'Use `has_object_permission()` instead for object permissions.', 'Use `has_object_permission()` instead for object permissions.',
PendingDeprecationWarning, stacklevel=2) DeprecationWarning, stacklevel=2
)
return self.has_permission(request, view, obj) return self.has_permission(request, view, obj)
return True return True
...@@ -87,8 +89,8 @@ class DjangoModelPermissions(BasePermission): ...@@ -87,8 +89,8 @@ class DjangoModelPermissions(BasePermission):
It ensures that the user is authenticated, and has the appropriate It ensures that the user is authenticated, and has the appropriate
`add`/`change`/`delete` permissions on the model. `add`/`change`/`delete` permissions on the model.
This permission will only be applied against view classes that This permission can only be applied against view classes that
provide a `.model` attribute, such as the generic class-based views. provide a `.model` or `.queryset` attribute.
""" """
# Map methods into required permission codes. # Map methods into required permission codes.
...@@ -136,6 +138,14 @@ class DjangoModelPermissions(BasePermission): ...@@ -136,6 +138,14 @@ class DjangoModelPermissions(BasePermission):
return False return False
class DjangoModelPermissionsOrAnonReadOnly(DjangoModelPermissions):
"""
Similar to DjangoModelPermissions, except that anonymous users are
allowed read-only access.
"""
authenticated_users_only = False
class TokenHasReadWriteScope(BasePermission): class TokenHasReadWriteScope(BasePermission):
""" """
The request is authenticated as a user and the token used has the right scope The request is authenticated as a user and the token used has the right scope
......
...@@ -24,6 +24,7 @@ from rest_framework.settings import api_settings ...@@ -24,6 +24,7 @@ from rest_framework.settings import api_settings
from rest_framework.request import clone_request from rest_framework.request import clone_request
from rest_framework.utils import encoders from rest_framework.utils import encoders
from rest_framework.utils.breadcrumbs import get_breadcrumbs from rest_framework.utils.breadcrumbs import get_breadcrumbs
from rest_framework.utils.formatting import get_view_name, get_view_description
from rest_framework import exceptions, parsers, status, VERSION from rest_framework import exceptions, parsers, status, VERSION
...@@ -438,16 +439,13 @@ class BrowsableAPIRenderer(BaseRenderer): ...@@ -438,16 +439,13 @@ class BrowsableAPIRenderer(BaseRenderer):
return GenericContentForm() return GenericContentForm()
def get_name(self, view): def get_name(self, view):
try: return get_view_name(view.__class__, getattr(view, 'suffix', None))
return view.get_name()
except AttributeError:
return smart_text(view.__class__.__name__)
def get_description(self, view): def get_description(self, view):
try: return get_view_description(view.__class__, html=True)
return view.get_description(html=True)
except AttributeError: def get_breadcrumbs(self, request):
return smart_text(view.__doc__ or '') return get_breadcrumbs(request.path)
def render(self, data, accepted_media_type=None, renderer_context=None): def render(self, data, accepted_media_type=None, renderer_context=None):
""" """
...@@ -480,7 +478,7 @@ class BrowsableAPIRenderer(BaseRenderer): ...@@ -480,7 +478,7 @@ class BrowsableAPIRenderer(BaseRenderer):
name = self.get_name(view) name = self.get_name(view)
description = self.get_description(view) description = self.get_description(view)
breadcrumb_list = get_breadcrumbs(request.path) breadcrumb_list = self.get_breadcrumbs(request)
template = loader.get_template(self.template) template = loader.get_template(self.template)
context = RequestContext(request, { context = RequestContext(request, {
......
""" """
The :mod:`request` module provides a :class:`Request` class used to wrap the standard `request` The Request class is used as a wrapper around the standard request object.
object received in all the views.
The wrapped request then offers a richer API, in particular : The wrapped request then offers a richer API, in particular :
- content automatically parsed according to `Content-Type` header, - content automatically parsed according to `Content-Type` header,
and available as :meth:`.DATA<Request.DATA>` and available as `request.DATA`
- full support of PUT method, including support for file uploads - full support of PUT method, including support for file uploads
- form overloading of HTTP method, content type and content - form overloading of HTTP method, content type and content
""" """
......
"""
The Response class in REST framework is similiar to HTTPResponse, except that
it is initialized with unrendered data, instead of a pre-rendered string.
The appropriate renderer is called during Django's template response rendering.
"""
from __future__ import unicode_literals from __future__ import unicode_literals
from django.core.handlers.wsgi import STATUS_CODE_TEXT from django.core.handlers.wsgi import STATUS_CODE_TEXT
from django.template.response import SimpleTemplateResponse from django.template.response import SimpleTemplateResponse
......
"""
Routers provide a convenient and consistent way of automatically
determining the URL conf for your API.
They are used by simply instantiating a Router class, and then registering
all the required ViewSets with that router.
For example, you might have a `urls.py` that looks something like this:
router = routers.DefaultRouter()
router.register('users', UserViewSet, 'user')
router.register('accounts', AccountViewSet, 'account')
urlpatterns = router.urls
"""
from __future__ import unicode_literals
from collections import namedtuple
from django.conf.urls import url, patterns
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.reverse import reverse
from rest_framework.urlpatterns import format_suffix_patterns
Route = namedtuple('Route', ['url', 'mapping', 'name', 'initkwargs'])
def replace_methodname(format_string, methodname):
"""
Partially format a format_string, swapping out any
'{methodname}' or '{methodnamehyphen}' components.
"""
methodnamehyphen = methodname.replace('_', '-')
ret = format_string
ret = ret.replace('{methodname}', methodname)
ret = ret.replace('{methodnamehyphen}', methodnamehyphen)
return ret
class BaseRouter(object):
def __init__(self):
self.registry = []
def register(self, prefix, viewset, base_name=None):
if base_name is None:
base_name = self.get_default_base_name(viewset)
self.registry.append((prefix, viewset, base_name))
def get_default_base_name(self, viewset):
"""
If `base_name` is not specified, attempt to automatically determine
it from the viewset.
"""
raise NotImplemented('get_default_base_name must be overridden')
def get_urls(self):
"""
Return a list of URL patterns, given the registered viewsets.
"""
raise NotImplemented('get_urls must be overridden')
@property
def urls(self):
if not hasattr(self, '_urls'):
self._urls = patterns('', *self.get_urls())
return self._urls
class SimpleRouter(BaseRouter):
routes = [
# List route.
Route(
url=r'^{prefix}/$',
mapping={
'get': 'list',
'post': 'create'
},
name='{basename}-list',
initkwargs={'suffix': 'List'}
),
# Detail route.
Route(
url=r'^{prefix}/{lookup}/$',
mapping={
'get': 'retrieve',
'put': 'update',
'patch': 'partial_update',
'delete': 'destroy'
},
name='{basename}-detail',
initkwargs={'suffix': 'Instance'}
),
# Dynamically generated routes.
# Generated using @action or @link decorators on methods of the viewset.
Route(
url=r'^{prefix}/{lookup}/{methodname}/$',
mapping={
'{httpmethod}': '{methodname}',
},
name='{basename}-{methodnamehyphen}',
initkwargs={}
),
]
def get_default_base_name(self, viewset):
"""
If `base_name` is not specified, attempt to automatically determine
it from the viewset.
"""
model_cls = getattr(viewset, 'model', None)
queryset = getattr(viewset, 'queryset', None)
if model_cls is None and queryset is not None:
model_cls = queryset.model
assert model_cls, '`name` not argument not specified, and could ' \
'not automatically determine the name from the viewset, as ' \
'it does not have a `.model` or `.queryset` attribute.'
return model_cls._meta.object_name.lower()
def get_routes(self, viewset):
"""
Augment `self.routes` with any dynamically generated routes.
Returns a list of the Route namedtuple.
"""
# Determine any `@action` or `@link` decorated methods on the viewset
dynamic_routes = {}
for methodname in dir(viewset):
attr = getattr(viewset, methodname)
httpmethod = getattr(attr, 'bind_to_method', None)
if httpmethod:
dynamic_routes[httpmethod] = methodname
ret = []
for route in self.routes:
if route.mapping == {'{httpmethod}': '{methodname}'}:
# Dynamic routes (@link or @action decorator)
for httpmethod, methodname in dynamic_routes.items():
initkwargs = route.initkwargs.copy()
initkwargs.update(getattr(viewset, methodname).kwargs)
ret.append(Route(
url=replace_methodname(route.url, methodname),
mapping={httpmethod: methodname},
name=replace_methodname(route.name, methodname),
initkwargs=initkwargs,
))
else:
# Standard route
ret.append(route)
return ret
def get_method_map(self, viewset, method_map):
"""
Given a viewset, and a mapping of http methods to actions,
return a new mapping which only includes any mappings that
are actually implemented by the viewset.
"""
bound_methods = {}
for method, action in method_map.items():
if hasattr(viewset, action):
bound_methods[method] = action
return bound_methods
def get_lookup_regex(self, viewset):
"""
Given a viewset, return the portion of URL regex that is used
to match against a single instance.
"""
base_regex = '(?P<{lookup_field}>[^/]+)'
lookup_field = getattr(viewset, 'lookup_field', 'pk')
return base_regex.format(lookup_field=lookup_field)
def get_urls(self):
"""
Use the registered viewsets to generate a list of URL patterns.
"""
ret = []
for prefix, viewset, basename in self.registry:
lookup = self.get_lookup_regex(viewset)
routes = self.get_routes(viewset)
for route in routes:
# Only actions which actually exist on the viewset will be bound
mapping = self.get_method_map(viewset, route.mapping)
if not mapping:
continue
# Build the url pattern
regex = route.url.format(prefix=prefix, lookup=lookup)
view = viewset.as_view(mapping, **route.initkwargs)
name = route.name.format(basename=basename)
ret.append(url(regex, view, name=name))
return ret
class DefaultRouter(SimpleRouter):
"""
The default router extends the SimpleRouter, but also adds in a default
API root view, and adds format suffix patterns to the URLs.
"""
include_root_view = True
include_format_suffixes = True
def get_api_root_view(self):
"""
Return a view to use as the API root.
"""
api_root_dict = {}
list_name = self.routes[0].name
for prefix, viewset, basename in self.registry:
api_root_dict[prefix] = list_name.format(basename=basename)
@api_view(('GET',))
def api_root(request, format=None):
ret = {}
for key, url_name in api_root_dict.items():
ret[key] = reverse(url_name, request=request, format=format)
return Response(ret)
return api_root
def get_urls(self):
"""
Generate the list of URL patterns, including a default root view
for the API, and appending `.json` style format suffixes.
"""
urls = []
if self.include_root_view:
root_url = url(r'^$', self.get_api_root_view(), name='api-root')
urls.append(root_url)
default_urls = super(DefaultRouter, self).get_urls()
urls.extend(default_urls)
if self.include_format_suffixes:
urls = format_suffix_patterns(urls)
return urls
...@@ -29,6 +29,7 @@ from rest_framework.compat import six ...@@ -29,6 +29,7 @@ from rest_framework.compat import six
USER_SETTINGS = getattr(settings, 'REST_FRAMEWORK', None) USER_SETTINGS = getattr(settings, 'REST_FRAMEWORK', None)
DEFAULTS = { DEFAULTS = {
# Base API policies
'DEFAULT_RENDERER_CLASSES': ( 'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.JSONRenderer',
'rest_framework.renderers.BrowsableAPIRenderer', 'rest_framework.renderers.BrowsableAPIRenderer',
...@@ -50,11 +51,15 @@ DEFAULTS = { ...@@ -50,11 +51,15 @@ DEFAULTS = {
'DEFAULT_CONTENT_NEGOTIATION_CLASS': 'DEFAULT_CONTENT_NEGOTIATION_CLASS':
'rest_framework.negotiation.DefaultContentNegotiation', 'rest_framework.negotiation.DefaultContentNegotiation',
# Genric view behavior
'DEFAULT_MODEL_SERIALIZER_CLASS': 'DEFAULT_MODEL_SERIALIZER_CLASS':
'rest_framework.serializers.ModelSerializer', 'rest_framework.serializers.ModelSerializer',
'DEFAULT_PAGINATION_SERIALIZER_CLASS': 'DEFAULT_PAGINATION_SERIALIZER_CLASS':
'rest_framework.pagination.PaginationSerializer', 'rest_framework.pagination.PaginationSerializer',
'DEFAULT_FILTER_BACKENDS': (),
# Throttling
'DEFAULT_THROTTLE_RATES': { 'DEFAULT_THROTTLE_RATES': {
'user': None, 'user': None,
'anon': None, 'anon': None,
...@@ -64,9 +69,6 @@ DEFAULTS = { ...@@ -64,9 +69,6 @@ DEFAULTS = {
'PAGINATE_BY': None, 'PAGINATE_BY': None,
'PAGINATE_BY_PARAM': None, 'PAGINATE_BY_PARAM': None,
# Filtering
'FILTER_BACKEND': None,
# Authentication # Authentication
'UNAUTHENTICATED_USER': 'django.contrib.auth.models.AnonymousUser', 'UNAUTHENTICATED_USER': 'django.contrib.auth.models.AnonymousUser',
'UNAUTHENTICATED_TOKEN': None, 'UNAUTHENTICATED_TOKEN': None,
...@@ -95,6 +97,9 @@ DEFAULTS = { ...@@ -95,6 +97,9 @@ DEFAULTS = {
ISO_8601, ISO_8601,
), ),
'TIME_FORMAT': ISO_8601, 'TIME_FORMAT': ISO_8601,
# Pending deprecation
'FILTER_BACKEND': None,
} }
...@@ -108,6 +113,7 @@ IMPORT_STRINGS = ( ...@@ -108,6 +113,7 @@ IMPORT_STRINGS = (
'DEFAULT_CONTENT_NEGOTIATION_CLASS', 'DEFAULT_CONTENT_NEGOTIATION_CLASS',
'DEFAULT_MODEL_SERIALIZER_CLASS', 'DEFAULT_MODEL_SERIALIZER_CLASS',
'DEFAULT_PAGINATION_SERIALIZER_CLASS', 'DEFAULT_PAGINATION_SERIALIZER_CLASS',
'DEFAULT_FILTER_BACKENDS',
'FILTER_BACKEND', 'FILTER_BACKEND',
'UNAUTHENTICATED_USER', 'UNAUTHENTICATED_USER',
'UNAUTHENTICATED_TOKEN', 'UNAUTHENTICATED_TOKEN',
......
...@@ -4,6 +4,7 @@ from __future__ import unicode_literals ...@@ -4,6 +4,7 @@ from __future__ import unicode_literals
from django.test import TestCase from django.test import TestCase
from rest_framework.views import APIView from rest_framework.views import APIView
from rest_framework.compat import apply_markdown from rest_framework.compat import apply_markdown
from rest_framework.utils.formatting import get_view_name, get_view_description
# We check that docstrings get nicely un-indented. # We check that docstrings get nicely un-indented.
DESCRIPTION = """an example docstring DESCRIPTION = """an example docstring
...@@ -49,22 +50,16 @@ MARKED_DOWN_gte_21 = """<h2 id="an-example-docstring">an example docstring</h2> ...@@ -49,22 +50,16 @@ MARKED_DOWN_gte_21 = """<h2 id="an-example-docstring">an example docstring</h2>
class TestViewNamesAndDescriptions(TestCase): class TestViewNamesAndDescriptions(TestCase):
def test_resource_name_uses_classname_by_default(self): def test_view_name_uses_class_name(self):
"""Ensure Resource names are based on the classname by default.""" """
Ensure view names are based on the class name.
"""
class MockView(APIView): class MockView(APIView):
pass pass
self.assertEqual(MockView().get_name(), 'Mock') self.assertEqual(get_view_name(MockView), 'Mock')
def test_resource_name_can_be_set_explicitly(self): def test_view_description_uses_docstring(self):
"""Ensure Resource names can be set using the 'get_name' method.""" """Ensure view descriptions are based on the docstring."""
example = 'Some Other Name'
class MockView(APIView):
def get_name(self):
return example
self.assertEqual(MockView().get_name(), example)
def test_resource_description_uses_docstring_by_default(self):
"""Ensure Resource names are based on the docstring by default."""
class MockView(APIView): class MockView(APIView):
"""an example docstring """an example docstring
==================== ====================
...@@ -81,44 +76,32 @@ class TestViewNamesAndDescriptions(TestCase): ...@@ -81,44 +76,32 @@ class TestViewNamesAndDescriptions(TestCase):
# hash style header #""" # hash style header #"""
self.assertEqual(MockView().get_description(), DESCRIPTION) self.assertEqual(get_view_description(MockView), DESCRIPTION)
def test_resource_description_can_be_set_explicitly(self):
"""Ensure Resource descriptions can be set using the 'get_description' method."""
example = 'Some other description'
class MockView(APIView):
"""docstring"""
def get_description(self):
return example
self.assertEqual(MockView().get_description(), example)
def test_resource_description_supports_unicode(self): def test_view_description_supports_unicode(self):
"""
Unicode in docstrings should be respected.
"""
class MockView(APIView): class MockView(APIView):
"""Проверка""" """Проверка"""
pass pass
self.assertEqual(MockView().get_description(), "Проверка") self.assertEqual(get_view_description(MockView), "Проверка")
def test_resource_description_does_not_require_docstring(self):
"""Ensure that empty docstrings do not affect the Resource's description if it has been set using the 'get_description' method."""
example = 'Some other description'
class MockView(APIView):
def get_description(self):
return example
self.assertEqual(MockView().get_description(), example)
def test_resource_description_can_be_empty(self): def test_view_description_can_be_empty(self):
"""Ensure that if a resource has no doctring or 'description' class attribute, then it's description is the empty string.""" """
Ensure that if a view has no docstring,
then it's description is the empty string.
"""
class MockView(APIView): class MockView(APIView):
pass pass
self.assertEqual(MockView().get_description(), '') self.assertEqual(get_view_description(MockView), '')
def test_markdown(self): def test_markdown(self):
"""Ensure markdown to HTML works as expected""" """
Ensure markdown to HTML works as expected.
"""
if apply_markdown: if apply_markdown:
gte_21_match = apply_markdown(DESCRIPTION) == MARKED_DOWN_gte_21 gte_21_match = apply_markdown(DESCRIPTION) == MARKED_DOWN_gte_21
lt_21_match = apply_markdown(DESCRIPTION) == MARKED_DOWN_lt_21 lt_21_match = apply_markdown(DESCRIPTION) == MARKED_DOWN_lt_21
......
...@@ -3,12 +3,14 @@ General serializer field tests. ...@@ -3,12 +3,14 @@ General serializer field tests.
""" """
from __future__ import unicode_literals from __future__ import unicode_literals
import datetime import datetime
from decimal import Decimal
from django.db import models from django.db import models
from django.test import TestCase from django.test import TestCase
from django.core import validators from django.core import validators
from rest_framework import serializers from rest_framework import serializers
from rest_framework.serializers import Serializer
class TimestampedModel(models.Model): class TimestampedModel(models.Model):
...@@ -481,3 +483,166 @@ class TimeFieldTest(TestCase): ...@@ -481,3 +483,166 @@ class TimeFieldTest(TestCase):
self.assertEqual('04 - 00 [000000]', result_1) self.assertEqual('04 - 00 [000000]', result_1)
self.assertEqual('04 - 59 [000000]', result_2) self.assertEqual('04 - 59 [000000]', result_2)
self.assertEqual('04 - 59 [000200]', result_3) self.assertEqual('04 - 59 [000200]', result_3)
class DecimalFieldTest(TestCase):
"""
Tests for the DecimalField from_native() and to_native() behavior
"""
def test_from_native_string(self):
"""
Make sure from_native() accepts string values
"""
f = serializers.DecimalField()
result_1 = f.from_native('9000')
result_2 = f.from_native('1.00000001')
self.assertEqual(Decimal('9000'), result_1)
self.assertEqual(Decimal('1.00000001'), result_2)
def test_from_native_invalid_string(self):
"""
Make sure from_native() raises ValidationError on passing invalid string
"""
f = serializers.DecimalField()
try:
f.from_native('123.45.6')
except validators.ValidationError as e:
self.assertEqual(e.messages, ["Enter a number."])
else:
self.fail("ValidationError was not properly raised")
def test_from_native_integer(self):
"""
Make sure from_native() accepts integer values
"""
f = serializers.DecimalField()
result = f.from_native(9000)
self.assertEqual(Decimal('9000'), result)
def test_from_native_float(self):
"""
Make sure from_native() accepts float values
"""
f = serializers.DecimalField()
result = f.from_native(1.00000001)
self.assertEqual(Decimal('1.00000001'), result)
def test_from_native_empty(self):
"""
Make sure from_native() returns None on empty param.
"""
f = serializers.DecimalField()
result = f.from_native('')
self.assertEqual(result, None)
def test_from_native_none(self):
"""
Make sure from_native() returns None on None param.
"""
f = serializers.DecimalField()
result = f.from_native(None)
self.assertEqual(result, None)
def test_to_native(self):
"""
Make sure to_native() returns Decimal as string.
"""
f = serializers.DecimalField()
result_1 = f.to_native(Decimal('9000'))
result_2 = f.to_native(Decimal('1.00000001'))
self.assertEqual(Decimal('9000'), result_1)
self.assertEqual(Decimal('1.00000001'), result_2)
def test_to_native_none(self):
"""
Make sure from_native() returns None on None param.
"""
f = serializers.DecimalField(required=False)
self.assertEqual(None, f.to_native(None))
def test_valid_serialization(self):
"""
Make sure the serializer works correctly
"""
class DecimalSerializer(Serializer):
decimal_field = serializers.DecimalField(max_value=9010,
min_value=9000,
max_digits=6,
decimal_places=2)
self.assertTrue(DecimalSerializer(data={'decimal_field': '9001'}).is_valid())
self.assertTrue(DecimalSerializer(data={'decimal_field': '9001.2'}).is_valid())
self.assertTrue(DecimalSerializer(data={'decimal_field': '9001.23'}).is_valid())
self.assertFalse(DecimalSerializer(data={'decimal_field': '8000'}).is_valid())
self.assertFalse(DecimalSerializer(data={'decimal_field': '9900'}).is_valid())
self.assertFalse(DecimalSerializer(data={'decimal_field': '9001.234'}).is_valid())
def test_raise_max_value(self):
"""
Make sure max_value violations raises ValidationError
"""
class DecimalSerializer(Serializer):
decimal_field = serializers.DecimalField(max_value=100)
s = DecimalSerializer(data={'decimal_field': '123'})
self.assertFalse(s.is_valid())
self.assertEqual(s.errors, {'decimal_field': ['Ensure this value is less than or equal to 100.']})
def test_raise_min_value(self):
"""
Make sure min_value violations raises ValidationError
"""
class DecimalSerializer(Serializer):
decimal_field = serializers.DecimalField(min_value=100)
s = DecimalSerializer(data={'decimal_field': '99'})
self.assertFalse(s.is_valid())
self.assertEqual(s.errors, {'decimal_field': ['Ensure this value is greater than or equal to 100.']})
def test_raise_max_digits(self):
"""
Make sure max_digits violations raises ValidationError
"""
class DecimalSerializer(Serializer):
decimal_field = serializers.DecimalField(max_digits=5)
s = DecimalSerializer(data={'decimal_field': '123.456'})
self.assertFalse(s.is_valid())
self.assertEqual(s.errors, {'decimal_field': ['Ensure that there are no more than 5 digits in total.']})
def test_raise_max_decimal_places(self):
"""
Make sure max_decimal_places violations raises ValidationError
"""
class DecimalSerializer(Serializer):
decimal_field = serializers.DecimalField(decimal_places=3)
s = DecimalSerializer(data={'decimal_field': '123.4567'})
self.assertFalse(s.is_valid())
self.assertEqual(s.errors, {'decimal_field': ['Ensure that there are no more than 3 decimal places.']})
def test_raise_max_whole_digits(self):
"""
Make sure max_whole_digits violations raises ValidationError
"""
class DecimalSerializer(Serializer):
decimal_field = serializers.DecimalField(max_digits=4, decimal_places=3)
s = DecimalSerializer(data={'decimal_field': '12345.6'})
self.assertFalse(s.is_valid())
self.assertEqual(s.errors, {'decimal_field': ['Ensure that there are no more than 4 digits in total.']})
\ No newline at end of file
...@@ -26,42 +26,44 @@ urlpatterns = patterns('', ...@@ -26,42 +26,44 @@ urlpatterns = patterns('',
) )
# ManyToMany
class ManyToManyTargetSerializer(serializers.HyperlinkedModelSerializer): class ManyToManyTargetSerializer(serializers.HyperlinkedModelSerializer):
sources = serializers.HyperlinkedRelatedField(many=True, view_name='manytomanysource-detail')
class Meta: class Meta:
model = ManyToManyTarget model = ManyToManyTarget
fields = ('url', 'name', 'sources')
class ManyToManySourceSerializer(serializers.HyperlinkedModelSerializer): class ManyToManySourceSerializer(serializers.HyperlinkedModelSerializer):
class Meta: class Meta:
model = ManyToManySource model = ManyToManySource
fields = ('url', 'name', 'targets')
# ForeignKey
class ForeignKeyTargetSerializer(serializers.HyperlinkedModelSerializer): class ForeignKeyTargetSerializer(serializers.HyperlinkedModelSerializer):
sources = serializers.HyperlinkedRelatedField(many=True, view_name='foreignkeysource-detail')
class Meta: class Meta:
model = ForeignKeyTarget model = ForeignKeyTarget
fields = ('url', 'name', 'sources')
class ForeignKeySourceSerializer(serializers.HyperlinkedModelSerializer): class ForeignKeySourceSerializer(serializers.HyperlinkedModelSerializer):
class Meta: class Meta:
model = ForeignKeySource model = ForeignKeySource
fields = ('url', 'name', 'target')
# Nullable ForeignKey # Nullable ForeignKey
class NullableForeignKeySourceSerializer(serializers.HyperlinkedModelSerializer): class NullableForeignKeySourceSerializer(serializers.HyperlinkedModelSerializer):
class Meta: class Meta:
model = NullableForeignKeySource model = NullableForeignKeySource
fields = ('url', 'name', 'target')
# OneToOne # Nullable OneToOne
class NullableOneToOneTargetSerializer(serializers.HyperlinkedModelSerializer): class NullableOneToOneTargetSerializer(serializers.HyperlinkedModelSerializer):
nullable_source = serializers.HyperlinkedRelatedField(view_name='nullableonetoonesource-detail')
class Meta: class Meta:
model = OneToOneTarget model = OneToOneTarget
fields = ('url', 'name', 'nullable_source')
# TODO: Add test that .data cannot be accessed prior to .is_valid # TODO: Add test that .data cannot be accessed prior to .is_valid
......
...@@ -6,38 +6,30 @@ from rest_framework.tests.models import ForeignKeyTarget, ForeignKeySource, Null ...@@ -6,38 +6,30 @@ from rest_framework.tests.models import ForeignKeyTarget, ForeignKeySource, Null
class ForeignKeySourceSerializer(serializers.ModelSerializer): class ForeignKeySourceSerializer(serializers.ModelSerializer):
class Meta: class Meta:
depth = 1
model = ForeignKeySource
class FlatForeignKeySourceSerializer(serializers.ModelSerializer):
class Meta:
model = ForeignKeySource model = ForeignKeySource
fields = ('id', 'name', 'target')
depth = 1
class ForeignKeyTargetSerializer(serializers.ModelSerializer): class ForeignKeyTargetSerializer(serializers.ModelSerializer):
sources = FlatForeignKeySourceSerializer(many=True)
class Meta: class Meta:
model = ForeignKeyTarget model = ForeignKeyTarget
fields = ('id', 'name', 'sources')
depth = 1
class NullableForeignKeySourceSerializer(serializers.ModelSerializer): class NullableForeignKeySourceSerializer(serializers.ModelSerializer):
class Meta: class Meta:
depth = 1
model = NullableForeignKeySource model = NullableForeignKeySource
fields = ('id', 'name', 'target')
depth = 1
class NullableOneToOneSourceSerializer(serializers.ModelSerializer):
class Meta:
model = NullableOneToOneSource
class NullableOneToOneTargetSerializer(serializers.ModelSerializer): class NullableOneToOneTargetSerializer(serializers.ModelSerializer):
nullable_source = NullableOneToOneSourceSerializer()
class Meta: class Meta:
model = OneToOneTarget model = OneToOneTarget
fields = ('id', 'name', 'nullable_source')
depth = 1
class ReverseForeignKeyTests(TestCase): class ReverseForeignKeyTests(TestCase):
......
...@@ -5,41 +5,44 @@ from rest_framework.tests.models import ManyToManyTarget, ManyToManySource, Fore ...@@ -5,41 +5,44 @@ from rest_framework.tests.models import ManyToManyTarget, ManyToManySource, Fore
from rest_framework.compat import six from rest_framework.compat import six
# ManyToMany
class ManyToManyTargetSerializer(serializers.ModelSerializer): class ManyToManyTargetSerializer(serializers.ModelSerializer):
sources = serializers.PrimaryKeyRelatedField(many=True)
class Meta: class Meta:
model = ManyToManyTarget model = ManyToManyTarget
fields = ('id', 'name', 'sources')
class ManyToManySourceSerializer(serializers.ModelSerializer): class ManyToManySourceSerializer(serializers.ModelSerializer):
class Meta: class Meta:
model = ManyToManySource model = ManyToManySource
fields = ('id', 'name', 'targets')
# ForeignKey
class ForeignKeyTargetSerializer(serializers.ModelSerializer): class ForeignKeyTargetSerializer(serializers.ModelSerializer):
sources = serializers.PrimaryKeyRelatedField(many=True)
class Meta: class Meta:
model = ForeignKeyTarget model = ForeignKeyTarget
fields = ('id', 'name', 'sources')
class ForeignKeySourceSerializer(serializers.ModelSerializer): class ForeignKeySourceSerializer(serializers.ModelSerializer):
class Meta: class Meta:
model = ForeignKeySource model = ForeignKeySource
fields = ('id', 'name', 'target')
# Nullable ForeignKey
class NullableForeignKeySourceSerializer(serializers.ModelSerializer): class NullableForeignKeySourceSerializer(serializers.ModelSerializer):
class Meta: class Meta:
model = NullableForeignKeySource model = NullableForeignKeySource
fields = ('id', 'name', 'target')
# OneToOne # Nullable OneToOne
class NullableOneToOneTargetSerializer(serializers.ModelSerializer): class NullableOneToOneTargetSerializer(serializers.ModelSerializer):
nullable_source = serializers.PrimaryKeyRelatedField()
class Meta: class Meta:
model = OneToOneTarget model = OneToOneTarget
fields = ('id', 'name', 'nullable_source')
# TODO: Add test that .data cannot be accessed prior to .is_valid # TODO: Add test that .data cannot be accessed prior to .is_valid
......
...@@ -357,7 +357,6 @@ class CustomValidationTests(TestCase): ...@@ -357,7 +357,6 @@ class CustomValidationTests(TestCase):
def validate_email(self, attrs, source): def validate_email(self, attrs, source):
value = attrs[source] value = attrs[source]
return attrs return attrs
def validate_content(self, attrs, source): def validate_content(self, attrs, source):
...@@ -738,6 +737,43 @@ class ManyRelatedTests(TestCase): ...@@ -738,6 +737,43 @@ class ManyRelatedTests(TestCase):
self.assertEqual(serializer.data, expected) self.assertEqual(serializer.data, expected)
def test_include_reverse_relations(self):
post = BlogPost.objects.create(title="Test blog post")
post.blogpostcomment_set.create(text="I hate this blog post")
post.blogpostcomment_set.create(text="I love this blog post")
class BlogPostSerializer(serializers.ModelSerializer):
class Meta:
model = BlogPost
fields = ('id', 'title', 'blogpostcomment_set')
serializer = BlogPostSerializer(instance=post)
expected = {
'id': 1, 'title': 'Test blog post', 'blogpostcomment_set': [1, 2]
}
self.assertEqual(serializer.data, expected)
def test_depth_include_reverse_relations(self):
post = BlogPost.objects.create(title="Test blog post")
post.blogpostcomment_set.create(text="I hate this blog post")
post.blogpostcomment_set.create(text="I love this blog post")
class BlogPostSerializer(serializers.ModelSerializer):
class Meta:
model = BlogPost
fields = ('id', 'title', 'blogpostcomment_set')
depth = 1
serializer = BlogPostSerializer(instance=post)
expected = {
'id': 1, 'title': 'Test blog post',
'blogpostcomment_set': [
{'id': 1, 'text': 'I hate this blog post', 'blog_post': 1},
{'id': 2, 'text': 'I love this blog post', 'blog_post': 1}
]
}
self.assertEqual(serializer.data, expected)
def test_callable_source(self): def test_callable_source(self):
post = BlogPost.objects.create(title="Test blog post") post = BlogPost.objects.create(title="Test blog post")
post.blogpostcomment_set.create(text="I love this blog post") post.blogpostcomment_set.create(text="I love this blog post")
...@@ -1073,7 +1109,7 @@ class DeserializeListTestCase(TestCase): ...@@ -1073,7 +1109,7 @@ class DeserializeListTestCase(TestCase):
def test_no_errors(self): def test_no_errors(self):
data = [self.data.copy() for x in range(0, 3)] data = [self.data.copy() for x in range(0, 3)]
serializer = CommentSerializer(data=data) serializer = CommentSerializer(data=data, many=True)
self.assertTrue(serializer.is_valid()) self.assertTrue(serializer.is_valid())
self.assertTrue(isinstance(serializer.object, list)) self.assertTrue(isinstance(serializer.object, list))
self.assertTrue( self.assertTrue(
...@@ -1085,7 +1121,7 @@ class DeserializeListTestCase(TestCase): ...@@ -1085,7 +1121,7 @@ class DeserializeListTestCase(TestCase):
invalid_item['email'] = '' invalid_item['email'] = ''
data = [self.data.copy(), invalid_item, self.data.copy()] data = [self.data.copy(), invalid_item, self.data.copy()]
serializer = CommentSerializer(data=data) serializer = CommentSerializer(data=data, many=True)
self.assertFalse(serializer.is_valid()) self.assertFalse(serializer.is_valid())
expected = [{}, {'email': ['This field is required.']}, {}] expected = [{}, {'email': ['This field is required.']}, {}]
self.assertEqual(serializer.errors, expected) self.assertEqual(serializer.errors, expected)
...@@ -109,7 +109,7 @@ class WritableNestedSerializerBasicTests(TestCase): ...@@ -109,7 +109,7 @@ class WritableNestedSerializerBasicTests(TestCase):
} }
] ]
serializer = self.AlbumSerializer(data=data) serializer = self.AlbumSerializer(data=data, many=True)
self.assertEqual(serializer.is_valid(), False) self.assertEqual(serializer.is_valid(), False)
self.assertEqual(serializer.errors, expected_errors) self.assertEqual(serializer.errors, expected_errors)
...@@ -241,6 +241,6 @@ class WritableNestedSerializerObjectTests(TestCase): ...@@ -241,6 +241,6 @@ class WritableNestedSerializerObjectTests(TestCase):
) )
] ]
serializer = self.AlbumSerializer(data=data) serializer = self.AlbumSerializer(data=data, many=True)
self.assertEqual(serializer.is_valid(), True) self.assertEqual(serializer.is_valid(), True)
self.assertEqual(serializer.object, expected_object) self.assertEqual(serializer.object, expected_object)
"""
Provides various throttling policies.
"""
from __future__ import unicode_literals from __future__ import unicode_literals
from django.core.cache import cache from django.core.cache import cache
from rest_framework import exceptions from rest_framework import exceptions
...@@ -28,9 +31,8 @@ class SimpleRateThrottle(BaseThrottle): ...@@ -28,9 +31,8 @@ class SimpleRateThrottle(BaseThrottle):
A simple cache implementation, that only requires `.get_cache_key()` A simple cache implementation, that only requires `.get_cache_key()`
to be overridden. to be overridden.
The rate (requests / seconds) is set by a :attr:`throttle` attribute The rate (requests / seconds) is set by a `throttle` attribute on the View
on the :class:`.View` class. The attribute is a string of the form 'number of class. The attribute is a string of the form 'number_of_requests/period'.
requests/period'.
Period should be one of: ('s', 'sec', 'm', 'min', 'h', 'hour', 'd', 'day') Period should be one of: ('s', 'sec', 'm', 'min', 'h', 'hour', 'd', 'day')
......
from __future__ import unicode_literals from __future__ import unicode_literals
from django.core.urlresolvers import resolve, get_script_prefix from django.core.urlresolvers import resolve, get_script_prefix
from rest_framework.utils.formatting import get_view_name
def get_breadcrumbs(url): def get_breadcrumbs(url):
"""Given a url returns a list of breadcrumbs, which are each a tuple of (name, url).""" """
Given a url returns a list of breadcrumbs, which are each a
tuple of (name, url).
"""
from rest_framework.views import APIView from rest_framework.views import APIView
def breadcrumbs_recursive(url, breadcrumbs_list, prefix, seen): def breadcrumbs_recursive(url, breadcrumbs_list, prefix, seen):
"""Add tuples of (name, url) to the breadcrumbs list, progressively chomping off parts of the url.""" """
Add tuples of (name, url) to the breadcrumbs list,
progressively chomping off parts of the url.
"""
try: try:
(view, unused_args, unused_kwargs) = resolve(url) (view, unused_args, unused_kwargs) = resolve(url)
except Exception: except Exception:
pass pass
else: else:
# Check if this is a REST framework view, and if so add it to the breadcrumbs # Check if this is a REST framework view,
if isinstance(getattr(view, 'cls_instance', None), APIView): # and if so add it to the breadcrumbs
if issubclass(getattr(view, 'cls', None), APIView):
# Don't list the same view twice in a row. # Don't list the same view twice in a row.
# Probably an optional trailing slash. # Probably an optional trailing slash.
if not seen or seen[-1] != view: if not seen or seen[-1] != view:
breadcrumbs_list.insert(0, (view.cls_instance.get_name(), prefix + url)) suffix = getattr(view, 'suffix', None)
name = get_view_name(view.cls, suffix)
breadcrumbs_list.insert(0, (name, prefix + url))
seen.append(view) seen.append(view)
if url == '': if url == '':
...@@ -28,11 +38,15 @@ def get_breadcrumbs(url): ...@@ -28,11 +38,15 @@ def get_breadcrumbs(url):
return breadcrumbs_list return breadcrumbs_list
elif url.endswith('/'): elif url.endswith('/'):
# Drop trailing slash off the end and continue to try to resolve more breadcrumbs # Drop trailing slash off the end and continue to try to
return breadcrumbs_recursive(url.rstrip('/'), breadcrumbs_list, prefix, seen) # resolve more breadcrumbs
url = url.rstrip('/')
# Drop trailing non-slash off the end and continue to try to resolve more breadcrumbs return breadcrumbs_recursive(url, breadcrumbs_list, prefix, seen)
return breadcrumbs_recursive(url[:url.rfind('/') + 1], breadcrumbs_list, prefix, seen)
# Drop trailing non-slash off the end and continue to try to
# resolve more breadcrumbs
url = url[:url.rfind('/') + 1]
return breadcrumbs_recursive(url, breadcrumbs_list, prefix, seen)
prefix = get_script_prefix().rstrip('/') prefix = get_script_prefix().rstrip('/')
url = url[len(prefix):] url = url[len(prefix):]
......
"""
Utility functions to return a formatted name and description for a given view.
"""
from __future__ import unicode_literals
from django.utils.html import escape
from django.utils.safestring import mark_safe
from rest_framework.compat import apply_markdown
import re
def _remove_trailing_string(content, trailing):
"""
Strip trailing component `trailing` from `content` if it exists.
Used when generating names from view classes.
"""
if content.endswith(trailing) and content != trailing:
return content[:-len(trailing)]
return content
def _remove_leading_indent(content):
"""
Remove leading indent from a block of text.
Used when generating descriptions from docstrings.
"""
whitespace_counts = [len(line) - len(line.lstrip(' '))
for line in content.splitlines()[1:] if line.lstrip()]
# unindent the content if needed
if whitespace_counts:
whitespace_pattern = '^' + (' ' * min(whitespace_counts))
content = re.sub(re.compile(whitespace_pattern, re.MULTILINE), '', content)
content = content.strip('\n')
return content
def _camelcase_to_spaces(content):
"""
Translate 'CamelCaseNames' to 'Camel Case Names'.
Used when generating names from view classes.
"""
camelcase_boundry = '(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))'
content = re.sub(camelcase_boundry, ' \\1', content).strip()
return ' '.join(content.split('_')).title()
def get_view_name(cls, suffix=None):
"""
Return a formatted name for an `APIView` class or `@api_view` function.
"""
name = cls.__name__
name = _remove_trailing_string(name, 'View')
name = _remove_trailing_string(name, 'ViewSet')
name = _camelcase_to_spaces(name)
if suffix:
name += ' ' + suffix
return name
def get_view_description(cls, html=False):
"""
Return a description for an `APIView` class or `@api_view` function.
"""
description = cls.__doc__ or ''
description = _remove_leading_indent(description)
if html:
return markup_description(description)
return description
def markup_description(description):
"""
Apply HTML markup to the given description.
"""
if apply_markdown:
description = apply_markdown(description)
else:
description = escape(description).replace('\n', '<br />')
return mark_safe(description)
""" """
Provides an APIView class that is used as the base of all class-based views. Provides an APIView class that is the base of all views in REST framework.
""" """
from __future__ import unicode_literals from __future__ import unicode_literals
from django.core.exceptions import PermissionDenied from django.core.exceptions import PermissionDenied
from django.http import Http404, HttpResponse from django.http import Http404, HttpResponse
from django.utils.html import escape
from django.utils.safestring import mark_safe
from django.views.decorators.csrf import csrf_exempt from django.views.decorators.csrf import csrf_exempt
from rest_framework import status, exceptions from rest_framework import status, exceptions
from rest_framework.compat import View, apply_markdown from rest_framework.compat import View
from rest_framework.response import Response from rest_framework.response import Response
from rest_framework.request import Request from rest_framework.request import Request
from rest_framework.settings import api_settings from rest_framework.settings import api_settings
import re from rest_framework.utils.formatting import get_view_name, get_view_description
def _remove_trailing_string(content, trailing):
"""
Strip trailing component `trailing` from `content` if it exists.
Used when generating names from view classes.
"""
if content.endswith(trailing) and content != trailing:
return content[:-len(trailing)]
return content
def _remove_leading_indent(content):
"""
Remove leading indent from a block of text.
Used when generating descriptions from docstrings.
"""
whitespace_counts = [len(line) - len(line.lstrip(' '))
for line in content.splitlines()[1:] if line.lstrip()]
# unindent the content if needed
if whitespace_counts:
whitespace_pattern = '^' + (' ' * min(whitespace_counts))
content = re.sub(re.compile(whitespace_pattern, re.MULTILINE), '', content)
content = content.strip('\n')
return content
def _camelcase_to_spaces(content):
"""
Translate 'CamelCaseNames' to 'Camel Case Names'.
Used when generating names from view classes.
"""
camelcase_boundry = '(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))'
content = re.sub(camelcase_boundry, ' \\1', content).strip()
return ' '.join(content.split('_')).title()
class APIView(View): class APIView(View):
...@@ -64,22 +26,21 @@ class APIView(View): ...@@ -64,22 +26,21 @@ class APIView(View):
@classmethod @classmethod
def as_view(cls, **initkwargs): def as_view(cls, **initkwargs):
""" """
Override the default :meth:`as_view` to store an instance of the view Store the original class on the view function.
as an attribute on the callable function. This allows us to discover
information about the view when we do URL reverse lookups. This allows us to discover information about the view when we do URL
reverse lookups. Used for breadcrumb generation.
""" """
# TODO: deprecate?
view = super(APIView, cls).as_view(**initkwargs) view = super(APIView, cls).as_view(**initkwargs)
view.cls_instance = cls(**initkwargs) view.cls = cls
return view return view
@property @property
def allowed_methods(self): def allowed_methods(self):
""" """
Return the list of allowed HTTP methods, uppercased. Wrap Django's private `_allowed_methods` interface in a public property.
""" """
return [method.upper() for method in self.http_method_names return self._allowed_methods()
if hasattr(self, method)]
@property @property
def default_response_headers(self): def default_response_headers(self):
...@@ -90,43 +51,10 @@ class APIView(View): ...@@ -90,43 +51,10 @@ class APIView(View):
'Vary': 'Accept' 'Vary': 'Accept'
} }
def get_name(self):
"""
Return the resource or view class name for use as this view's name.
Override to customize.
"""
# TODO: deprecate?
name = self.__class__.__name__
name = _remove_trailing_string(name, 'View')
return _camelcase_to_spaces(name)
def get_description(self, html=False):
"""
Return the resource or view docstring for use as this view's description.
Override to customize.
"""
# TODO: deprecate?
description = self.__doc__ or ''
description = _remove_leading_indent(description)
if html:
return self.markup_description(description)
return description
def markup_description(self, description):
"""
Apply HTML markup to the description of this view.
"""
# TODO: deprecate?
if apply_markdown:
description = apply_markdown(description)
else:
description = escape(description).replace('\n', '<br />')
return mark_safe(description)
def metadata(self, request): def metadata(self, request):
return { return {
'name': self.get_name(), 'name': get_view_name(self.__class__),
'description': self.get_description(), 'description': get_view_description(self.__class__),
'renders': [renderer.media_type for renderer in self.renderer_classes], 'renders': [renderer.media_type for renderer in self.renderer_classes],
'parses': [parser.media_type for parser in self.parser_classes], 'parses': [parser.media_type for parser in self.parser_classes],
} }
...@@ -140,7 +68,8 @@ class APIView(View): ...@@ -140,7 +68,8 @@ class APIView(View):
def http_method_not_allowed(self, request, *args, **kwargs): def http_method_not_allowed(self, request, *args, **kwargs):
""" """
Called if `request.method` does not correspond to a handler method. If `request.method` does not correspond to a handler method,
determine what kind of exception to raise.
""" """
raise exceptions.MethodNotAllowed(request.method) raise exceptions.MethodNotAllowed(request.method)
......
"""
ViewSets are essentially just a type of class based view, that doesn't provide
any method handlers, such as `get()`, `post()`, etc... but instead has actions,
such as `list()`, `retrieve()`, `create()`, etc...
Actions are only bound to methods at the point of instantiating the views.
user_list = UserViewSet.as_view({'get': 'list'})
user_detail = UserViewSet.as_view({'get': 'retrieve'})
Typically, rather than instantiate views from viewsets directly, you'll
regsiter the viewset with a router and let the URL conf be determined
automatically.
router = DefaultRouter()
router.register(r'users', UserViewSet, 'user')
urlpatterns = router.urls
"""
from __future__ import unicode_literals
from functools import update_wrapper
from django.utils.decorators import classonlymethod
from rest_framework import views, generics, mixins
class ViewSetMixin(object):
"""
This is the magic.
Overrides `.as_view()` so that it takes an `actions` keyword that performs
the binding of HTTP methods to actions on the Resource.
For example, to create a concrete view binding the 'GET' and 'POST' methods
to the 'list' and 'create' actions...
view = MyViewSet.as_view({'get': 'list', 'post': 'create'})
"""
@classonlymethod
def as_view(cls, actions=None, **initkwargs):
"""
Because of the way class based views create a closure around the
instantiated view, we need to totally reimplement `.as_view`,
and slightly modify the view function that is created and returned.
"""
# The suffix initkwarg is reserved for identifing the viewset type
# eg. 'List' or 'Instance'.
cls.suffix = None
# sanitize keyword arguments
for key in initkwargs:
if key in cls.http_method_names:
raise TypeError("You tried to pass in the %s method name as a "
"keyword argument to %s(). Don't do that."
% (key, cls.__name__))
if not hasattr(cls, key):
raise TypeError("%s() received an invalid keyword %r" % (
cls.__name__, key))
def view(request, *args, **kwargs):
self = cls(**initkwargs)
# We also store the mapping of request methods to actions,
# so that we can later set the action attribute.
# eg. `self.action = 'list'` on an incoming GET request.
self.action_map = actions
# Bind methods to actions
# This is the bit that's different to a standard view
for method, action in actions.items():
handler = getattr(self, action)
setattr(self, method, handler)
# Patch this in as it's otherwise only present from 1.5 onwards
if hasattr(self, 'get') and not hasattr(self, 'head'):
self.head = self.get
# And continue as usual
return self.dispatch(request, *args, **kwargs)
# take name and docstring from class
update_wrapper(view, cls, updated=())
# and possible attributes set by decorators
# like csrf_exempt from dispatch
update_wrapper(view, cls.dispatch, assigned=())
# We need to set these on the view function, so that breadcrumb
# generation can pick out these bits of information from a
# resolved URL.
view.cls = cls
view.suffix = initkwargs.get('suffix', None)
return view
def initialize_request(self, request, *args, **kargs):
"""
Set the `.action` attribute on the view,
depending on the request method.
"""
request = super(ViewSetMixin, self).initialize_request(request, *args, **kargs)
self.action = self.action_map.get(request.method.lower())
return request
class ViewSet(ViewSetMixin, views.APIView):
"""
The base ViewSet class does not provide any actions by default.
"""
pass
class ReadOnlyModelViewSet(mixins.RetrieveModelMixin,
mixins.ListModelMixin,
ViewSetMixin,
generics.GenericAPIView):
"""
A viewset that provides default `list()` and `retrieve()` actions.
"""
pass
class ModelViewSet(mixins.CreateModelMixin,
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
mixins.ListModelMixin,
ViewSetMixin,
generics.GenericAPIView):
"""
A viewset that provides default `create()`, `retrieve()`, `update()`,
`partial_update()`, `destroy()` and `list()` actions.
"""
pass
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment