diff options
46 files changed, 1874 insertions, 519 deletions
diff --git a/docs/api-guide/filtering.md b/docs/api-guide/filtering.md index ed946368..805d82f8 100644 --- a/docs/api-guide/filtering.md +++ b/docs/api-guide/filtering.md @@ -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 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. @@ -21,7 +21,6 @@ You can do so by filtering based on the value of `request.user`. For example: class PurchaseList(generics.ListAPIView) - model = Purchase serializer_class = PurchaseSerializer def get_queryset(self): @@ -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: class PurchaseList(generics.ListAPIView) - model = Purchase serializer_class = PurchaseSerializer def get_queryset(self): @@ -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: class PurchaseList(generics.ListAPIView) - model = Purchase serializer_class = PurchaseSerializer def get_queryset(self): @@ -100,7 +97,7 @@ You must also set the filter backend to `DjangoFilterBackend` in your settings: 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. class ProductList(generics.ListAPIView): - model = Product + queryset = Product.objects.all() serializer_class = ProductSerializer filter_fields = ('category', 'in_stock') @@ -120,7 +117,7 @@ For more advanced filtering requirements you can specify a `FilterSet` class tha fields = ['category', 'in_stock', 'min_price', 'max_price'] class ProductList(generics.ListAPIView): - model = Product + queryset = Product.objects.all() serializer_class = ProductSerializer filter_class = ProductFilter @@ -183,4 +180,4 @@ For example: [cite]: https://docs.djangoproject.com/en/dev/topics/db/queries/#retrieving-specific-objects-with-filters [django-filter]: https://github.com/alex/django-filter [django-filter-docs]: https://django-filter.readthedocs.org/en/latest/index.html -[nullbooleanselect]: https://github.com/django/django/blob/master/django/forms/widgets.py
\ No newline at end of file +[nullbooleanselect]: https://github.com/django/django/blob/master/django/forms/widgets.py diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md index cef9a9d4..4a24b7c7 100755 --- a/docs/api-guide/generic-views.md +++ b/docs/api-guide/generic-views.md @@ -18,7 +18,7 @@ If the generic views don't suit the needs of your API, you can drop down to usin Typically when using the generic views, you'll override the view, and set several class attributes. class UserList(generics.ListCreateAPIView): - model = User + queryset = User.objects.all() serializer_class = UserSerializer permission_classes = (IsAdminUser,) paginate_by = 100 @@ -26,17 +26,16 @@ Typically when using the generic views, you'll override the view, and set severa For more complex cases you might also want to override various methods on the view class. For example. class UserList(generics.ListCreateAPIView): - model = User + queryset = User.objects.all() serializer_class = UserSerializer permission_classes = (IsAdminUser,) - def get_paginate_by(self, queryset): + def get_paginate_by(self): """ Use smaller pagination for HTML representations. """ - page_size_param = self.request.QUERY_PARAMS.get('page_size') - if page_size_param: - return int(page_size_param) + self.request.accepted_renderer.format == 'html': + return 20 return 100 For very simple cases you might want to pass through any class attributes using the `.as_view()` method. For example, your URLconf might include something the following entry. @@ -47,6 +46,114 @@ For very simple cases you might want to pass through any class attributes using # API Reference +## GenericAPIView + +This class extends REST framework's `APIView` class, adding commonly required behavior for standard list and detail views. + +Each of the concrete generic views provided is built by combining `GenericAPIView`, with one or more mixin classes. + +### Attributes + +**Basic settings**: + +The following attributes control the basic view behavior. + +* `queryset` - The queryset that should be used for returning objects from this view. Typically, you must either set this attribute, or override the `get_queryset()` method. +* `serializer_class` - The serializer class that should be used for validating and deserializing input, and for serializing output. Typically, you must either set this attribute, or override the `get_serializer_class()` method. +* `lookup_field` - The field that should be used to lookup individual model instances. Defaults to `'pk'`. The URL conf should include a keyword argument corresponding to this value. More complex lookup styles can be supported by overriding the `get_object()` method. + +**Pagination**: + +The following attibutes are used to control pagination when used with list views. + +* `paginate_by` - The size of pages to use with paginated data. If set to `None` then pagination is turned off. If unset this uses the same value as the `PAGINATE_BY` setting, which defaults to `None`. +* `paginate_by_param` - The name of a query parameter, which can be used by the client to overide the default page size to use for pagination. If unset this uses the same value as the `PAGINATE_BY_PARAM` setting, which defaults to `None`. +* `pagination_serializer_class` - The pagination serializer class to use when determining the style of paginated responses. Defaults to the same value as the `DEFAULT_PAGINATION_SERIALIZER_CLASS` setting. +* `page_kwarg` - The name of a URL kwarg or URL query parameter which can be used by the client to control which page is requested. Defaults to `'page'`. + +**Other**: + +* `filter_backend` - The filter backend class that should be used for filtering the queryset. Defaults to the same value as the `FILTER_BACKEND` setting. +* `allow_empty` - Determines if an empty list should successfully display zero results, or return a 404 response. Defaults to `True`, meaning empty lists will return sucessful `200 OK` responses, with zero results. +* `model` - This shortcut may be used instead of setting either (or both) of the `queryset`/`serializer_class` attributes, although using the explicit style is generally preferred. If used instead of `serializer_class`, then then `DEFAULT_MODEL_SERIALIZER_CLASS` setting will determine the base serializer class. + +### Methods + +**Base methods**: + +#### `get_queryset(self)` + +Returns the queryset that should be used for list views, and that should be used as the base for lookups in detail views. Defaults to returning the queryset specified by the `queryset` attribute, or the default queryset for the model if the `model` shortcut is being used. + +May be overridden to provide dynamic behavior such as returning a queryset that is specific to the user making the request. + +For example: + + def get_queryset(self): + return self.user.accounts.all() + +#### `get_object(self)` + +Returns an object instance that should be used for detail views. Defaults to using the `lookup_field` parameter to filter the base queryset. + +May be overridden to provide more complex behavior such as object lookups based on more than one URL kwarg. + +For example: + + def get_object(self): + queryset = self.get_queryset() + filter = {} + for field in self.multiple_lookup_fields: + filter[field] = self.kwargs[field] + return get_object_or_404(queryset, **filter) + +#### `get_serializer_class(self)` + +Returns the class that should be used for the serializer. Defaults to returning the `serializer_class` attribute, or dynamically generating a serializer class if the `model` shortcut is being used. + +May be override to provide dynamic behavior such as using different serializers for read and write operations, or providing different serializers to different types of uesr. + +For example: + + def get_serializer_class(self): + if self.request.user.is_staff: + return FullAccountSerializer + return BasicAccountSerializer + +#### `get_paginate_by(self)` + +Returna the page size to use with pagination. By default this uses the `paginate_by` attribute, and may be overridden by the cient if the `paginate_by_param` attribute is set. + +You may want to override this method to provide more complex behavior such as modifying page sizes based on the media type of the response. + +For example: + + def get_paginate_by(self): + self.request.accepted_renderer.format == 'html': + return 20 + return 100 + +**Save hooks**: + +The following methods are provided as placeholder interfaces. They contain empty implementations and are not called directly by `GenericAPIView`, but they are overridden and used by some of the mixin classes. + +* `pre_save(self, obj)` - A hook that is called before saving an object. +* `post_save(self, obj, created=False)` - A hook that is called after saving an object. + +**Other methods**: + +You won't typically need to override the following methods, although you might need to call into them if you're writing custom views using `GenericAPIView`. + +* `get_serializer_context(self)` - Returns a dictionary containing any extra context that should be supplied to the serializer. Defaults to including `'request'`, `'view'` and `'format'` keys. +* `get_serializer(self, instance=None, data=None, files=None, many=False, partial=False)` - Returns a serializer instance. +* `get_pagination_serializer(self, page)` - Returns a serializer instance to use with paginated data. +* `paginate_queryset(self, queryset)` - Paginate a queryset if required, either returning a page object, or `None` if pagination is not configured for this view. +* `filter_queryset(self, queryset)` - Given a queryset, filter it with whichever filter backend is in use, returning a new queryset. + +--- + +# Concrete View Classes + The following classes are the concrete generic views. If you're using generic views this is normally the level you'll be working at unless you need heavily customized behavior. ## CreateAPIView @@ -63,7 +170,7 @@ Used for **read-only** endpoints to represent a **collection of model instances* Provides a `get` method handler. -Extends: [MultipleObjectAPIView], [ListModelMixin] +Extends: [GenericAPIView], [ListModelMixin] ## RetrieveAPIView @@ -71,7 +178,7 @@ Used for **read-only** endpoints to represent a **single model instance**. Provides a `get` method handler. -Extends: [SingleObjectAPIView], [RetrieveModelMixin] +Extends: [GenericAPIView], [RetrieveModelMixin] ## DestroyAPIView @@ -79,7 +186,7 @@ Used for **delete-only** endpoints for a **single model instance**. Provides a `delete` method handler. -Extends: [SingleObjectAPIView], [DestroyModelMixin] +Extends: [GenericAPIView], [DestroyModelMixin] ## UpdateAPIView @@ -87,7 +194,7 @@ Used for **update-only** endpoints for a **single model instance**. Provides `put` and `patch` method handlers. -Extends: [SingleObjectAPIView], [UpdateModelMixin] +Extends: [GenericAPIView], [UpdateModelMixin] ## ListCreateAPIView @@ -95,7 +202,7 @@ Used for **read-write** endpoints to represent a **collection of model instances Provides `get` and `post` method handlers. -Extends: [MultipleObjectAPIView], [ListModelMixin], [CreateModelMixin] +Extends: [GenericAPIView], [ListModelMixin], [CreateModelMixin] ## RetrieveUpdateAPIView @@ -103,7 +210,7 @@ Used for **read or update** endpoints to represent a **single model instance**. Provides `get`, `put` and `patch` method handlers. -Extends: [SingleObjectAPIView], [RetrieveModelMixin], [UpdateModelMixin] +Extends: [GenericAPIView], [RetrieveModelMixin], [UpdateModelMixin] ## RetrieveDestroyAPIView @@ -111,7 +218,7 @@ Used for **read or delete** endpoints to represent a **single model instance**. Provides `get` and `delete` method handlers. -Extends: [SingleObjectAPIView], [RetrieveModelMixin], [DestroyModelMixin] +Extends: [GenericAPIView], [RetrieveModelMixin], [DestroyModelMixin] ## RetrieveUpdateDestroyAPIView @@ -119,62 +226,13 @@ Used for **read-write-delete** endpoints to represent a **single model instance* Provides `get`, `put`, `patch` and `delete` method handlers. -Extends: [SingleObjectAPIView], [RetrieveModelMixin], [UpdateModelMixin], [DestroyModelMixin] - ---- - -# Base views - -Each of the generic views provided is built by combining one of the base views below, with one or more mixin classes. - -## GenericAPIView - -Extends REST framework's `APIView` class, adding support for serialization of model instances and model querysets. - -**Methods**: - -* `get_serializer_context(self)` - Returns a dictionary containing any extra context that should be supplied to the serializer. Defaults to including `'request'`, `'view'` and `'format'` keys. -* `get_serializer_class(self)` - Returns the class that should be used for the serializer. -* `get_serializer(self, instance=None, data=None, files=None, many=False, partial=False)` - Returns a serializer instance. -* `pre_save(self, obj)` - A hook that is called before saving an object. -* `post_save(self, obj, created=False)` - A hook that is called after saving an object. - - -**Attributes**: - -* `model` - The model that should be used for this view. Used as a fallback for determining the serializer if `serializer_class` is not set, and as a fallback for determining the queryset if `queryset` is not set. Otherwise not required. -* `serializer_class` - The serializer class that should be used for validating and deserializing input, and for serializing output. If unset, this defaults to creating a serializer class using `self.model`, with the `DEFAULT_MODEL_SERIALIZER_CLASS` setting as the base serializer class. - -## MultipleObjectAPIView - -Provides a base view for acting on a single object, by combining REST framework's `APIView`, and Django's [MultipleObjectMixin]. - -**See also:** ccbv.co.uk documentation for [MultipleObjectMixin][multiple-object-mixin-classy]. - -**Attributes**: - -* `queryset` - The queryset that should be used for returning objects from this view. If unset, defaults to the default queryset manager for `self.model`. -* `paginate_by` - The size of pages to use with paginated data. If set to `None` then pagination is turned off. If unset this uses the same value as the `PAGINATE_BY` setting, which defaults to `None`. -* `paginate_by_param` - The name of a query parameter, which can be used by the client to overide the default page size to use for pagination. If unset this uses the same value as the `PAGINATE_BY_PARAM` setting, which defaults to `None`. - -## SingleObjectAPIView - -Provides a base view for acting on a single object, by combining REST framework's `APIView`, and Django's [SingleObjectMixin]. - -**See also:** ccbv.co.uk documentation for [SingleObjectMixin][single-object-mixin-classy]. - -**Attributes**: - -* `queryset` - The queryset that should be used when retrieving an object from this view. If unset, defaults to the default queryset manager for `self.model`. -* `pk_kwarg` - The URL kwarg that should be used to look up objects by primary key. Defaults to `'pk'`. [Can only be set to non-default on Django 1.4+] -* `slug_url_kwarg` - The URL kwarg that should be used to look up objects by a slug. Defaults to `'slug'`. [Can only be set to non-default on Django 1.4+] -* `slug_field` - The field on the model that should be used to look up objects by a slug. If used, this should typically be set to a field with `unique=True`. Defaults to `'slug'`. +Extends: [GenericAPIView], [RetrieveModelMixin], [UpdateModelMixin], [DestroyModelMixin] --- # Mixins -The mixin classes provide the actions that are used to provide the basic view behaviour. Note that the mixin classes provide action methods rather than defining the handler methods such as `.get()` and `.post()` directly. This allows for more flexible composition of behaviour. +The mixin classes provide the actions that are used to provide the basic view behavior. Note that the mixin classes provide action methods rather than defining the handler methods such as `.get()` and `.post()` directly. This allows for more flexible composition of behavior. ## ListModelMixin @@ -182,7 +240,7 @@ Provides a `.list(request, *args, **kwargs)` method, that implements listing a q If the queryset is populated, this returns a `200 OK` response, with a serialized representation of the queryset as the body of the response. The response data may optionally be paginated. -If the queryset is empty this returns a `200 OK` reponse, unless the `.allow_empty` attribute on the view is set to `False`, in which case it will return a `404 Not Found`. +If the queryset is empty this returns a `200 OK` response, unless the `.allow_empty` attribute on the view is set to `False`, in which case it will return a `404 Not Found`. Should be mixed in with [MultipleObjectAPIView]. @@ -208,14 +266,14 @@ Should be mixed in with [SingleObjectAPIView]. Provides a `.update(request, *args, **kwargs)` method, that implements updating and saving an existing model instance. +Also provides a `.partial_update(request, *args, **kwargs)` method, which is similar to the `update` method, except that all fields for the update will be optional. This allows support for HTTP `PATCH` requests. + If an object is updated this returns a `200 OK` response, with a serialized representation of the object as the body of the response. If an object is created, for example when making a `DELETE` request followed by a `PUT` request to the same URL, this returns a `201 Created` response, with a serialized representation of the object as the body of the response. If the request data provided for updating the object was invalid, a `400 Bad Request` response will be returned, with the error details as the body of the response. -A boolean `partial` keyword argument may be supplied to the `.update()` method. If `partial` is set to `True`, all fields for the update will be optional. This allows support for HTTP `PATCH` requests. - Should be mixed in with [SingleObjectAPIView]. ## DestroyModelMixin @@ -227,14 +285,8 @@ If an object is deleted this returns a `204 No Content` response, otherwise it w Should be mixed in with [SingleObjectAPIView]. [cite]: https://docs.djangoproject.com/en/dev/ref/class-based-views/#base-vs-generic-views -[MultipleObjectMixin]: https://docs.djangoproject.com/en/dev/ref/class-based-views/mixins-multiple-object/ -[SingleObjectMixin]: https://docs.djangoproject.com/en/dev/ref/class-based-views/mixins-single-object/ -[multiple-object-mixin-classy]: http://ccbv.co.uk/projects/Django/1.4/django.views.generic.list/MultipleObjectMixin/ -[single-object-mixin-classy]: http://ccbv.co.uk/projects/Django/1.4/django.views.generic.detail/SingleObjectMixin/ [GenericAPIView]: #genericapiview -[SingleObjectAPIView]: #singleobjectapiview -[MultipleObjectAPIView]: #multipleobjectapiview [ListModelMixin]: #listmodelmixin [CreateModelMixin]: #createmodelmixin [RetrieveModelMixin]: #retrievemodelmixin diff --git a/docs/api-guide/pagination.md b/docs/api-guide/pagination.md index 13d4760a..912ce41b 100644 --- a/docs/api-guide/pagination.md +++ b/docs/api-guide/pagination.md @@ -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. class PaginatedListView(ListAPIView): - model = ExampleModel + queryset = ExampleModel.objects.all() + serializer_class = ExampleModelSerializer paginate_by = 10 paginate_by_param = 'page_size' diff --git a/docs/api-guide/renderers.md b/docs/api-guide/renderers.md index 3c8396aa..e2fc36ca 100644 --- a/docs/api-guide/renderers.md +++ b/docs/api-guide/renderers.md @@ -127,7 +127,7 @@ An example of a view that uses `TemplateHTMLRenderer`: """ A view that returns a templated HTML representations of a given user. """ - model = Users + queryset = User.objects.all() renderer_classes = (TemplateHTMLRenderer,) def get(self, request, *args, **kwargs) diff --git a/docs/api-guide/routers.md b/docs/api-guide/routers.md new file mode 100644 index 00000000..2fda5373 --- /dev/null +++ b/docs/api-guide/routers.md @@ -0,0 +1,122 @@ +<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. +> +> — [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, 'user') + router.register(r'accounts', AccountViewSet, 'account') + urlpatterns = router.urls + +There are three arguments to the `register()` method: + +* `prefix` - The URL prefix to use for this set of routes. +* `viewset` - The viewset class. +* `basename` - The base to use for the URL names that are created. + +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> + +## AutoRouter + +The AutoRouter class is similar to the `DefaultRouter` class, except that it doesn't require you to register any viewsets, but instead automatically creates routes for all installed models. + +It can be useful for prototyping, although for anything more advanced you'll want to drop down to using one of the other router classes, and registering viewsets explicitly. + +The following code shows how you can automatically include a complete API for your application with just a few lines of code, using the `AutoRouter` class: + + from django.conf.urls import patterns, url, include + from rest_framework.routers import AutoRouter + + urlpatterns = patterns('', + url(r'^api/', include(AutoRouter().urls)), + url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) + ) + +# 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()` 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. + +[cite]: http://guides.rubyonrails.org/routing.html
\ No newline at end of file diff --git a/docs/api-guide/viewsets.md b/docs/api-guide/viewsets.md new file mode 100644 index 00000000..36a4dbd5 --- /dev/null +++ b/docs/api-guide/viewsets.md @@ -0,0 +1,212 @@ +<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. +> +> — [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, 'user') + 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 diff --git a/docs/css/default.css b/docs/css/default.css index 173d70e0..998efa27 100644 --- a/docs/css/default.css +++ b/docs/css/default.css @@ -288,3 +288,13 @@ footer a:hover { @media (max-width: 650px) { .repo-link.btn-inverse {display: none;} } + +td, th { + padding: 0.25em; + background-color: #f7f7f9; + border-color: #e1e1e8; +} + +table { + border-color: white; +} diff --git a/docs/index.md b/docs/index.md index 4c2720c8..e2dd9fba 100644 --- a/docs/index.md +++ b/docs/index.md @@ -73,6 +73,54 @@ If you're intending to use the browseable API you'll probably also want to add R 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. + + from django.conf.urls.defaults import url, patterns, include + from django.contrib.auth.models import User, Group + from rest_framework import serializers, viewsets, routers + + + # Serializers control the representations your API exposes. + class UserSerializer(serializers.HyperlinkedModelSerializer): + class Meta: + model = User + fields = ('url', 'email', 'is_staff', 'groups') + + + class GroupSerializer(serializers.HyperlinkedModelSerializer): + class Meta: + model = Group + fields = ('url', 'name') + + + # ViewSets define the view behavior. + class UserViewSet(viewsets.ModelViewSet): + queryset = User.objects.all() + serializer_class = UserSerializer + + + class GroupViewSet(viewsets.ModelViewSet): + queryset = Group.objects.all() + serializer_class = GroupSerializer + + + # Routers provide a convienient way of automatically managing your URLs. + router = routers.DefaultRouter() + router.register(r'users', UserViewSet, 'user') + router.register(r'groups', GroupViewSet, 'group') + + + # Wire up our API URLs, letting the router do the hard work. + # 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 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 +134,7 @@ The tutorial will walk you through the building blocks that make up REST framewo * [3 - Class based views][tut-3] * [4 - Authentication & permissions][tut-4] * [5 - Relationships & hyperlinked APIs][tut-5] +* [6 - Viewsets & routers][tut-6] ## API Guide @@ -95,6 +144,8 @@ The API guide is your complete reference manual to all the functionality provide * [Responses][response] * [Views][views] * [Generic views][generic-views] +* [Viewsets][viewsets] +* [Routers][routers] * [Parsers][parsers] * [Renderers][renderers] * [Serializers][serializers] @@ -122,6 +173,7 @@ General guides to using REST framework. * [REST, Hypermedia & HATEOAS][rest-hypermedia-hateoas] * [2.0 Announcement][rest-framework-2-announcement] * [2.2 Announcement][2.2-announcement] +* [2.3 Announcement][2.3-announcement] * [Release Notes][release-notes] * [Credits][credits] @@ -197,11 +249,14 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. [tut-3]: tutorial/3-class-based-views.md [tut-4]: tutorial/4-authentication-and-permissions.md [tut-5]: tutorial/5-relationships-and-hyperlinked-apis.md +[tut-6]: tutorial/6-viewsets-and-routers.md [request]: api-guide/requests.md [response]: api-guide/responses.md [views]: api-guide/views.md [generic-views]: api-guide/generic-views.md +[viewsets]: api-guide/viewsets.md +[routers]: api-guide/routers.md [parsers]: api-guide/parsers.md [renderers]: api-guide/renderers.md [serializers]: api-guide/serializers.md @@ -226,6 +281,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. [contributing]: topics/contributing.md [rest-framework-2-announcement]: topics/rest-framework-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 [credits]: topics/credits.md diff --git a/docs/template.html b/docs/template.html index 7e929762..53656e7d 100644 --- a/docs/template.html +++ b/docs/template.html @@ -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/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/6-viewsets-and-routers{{ suffix }}">6 - Viewsets and routers</a></li> </ul> </li> <li class="dropdown"> @@ -71,6 +72,8 @@ <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/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/renderers{{ suffix }}">Renderers</a></li> <li><a href="{{ base_url }}/api-guide/serializers{{ suffix }}">Serializers</a></li> @@ -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-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.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/credits{{ suffix }}">Credits</a></li> </ul> diff --git a/docs/topics/2.3-announcement.md b/docs/topics/2.3-announcement.md new file mode 100644 index 00000000..554728ae --- /dev/null +++ b/docs/topics/2.3-announcement.md @@ -0,0 +1,164 @@ +# REST framework 2.3 announcement + +REST framework 2.3 is geared towards making it easier and quicker to build your Web APIs. + +## ViewSets & Routers + +**TODO** + +## Easier Serializers + +REST framework lets you be totally explict regarding how you want to represent relationships, allowing you to choose between styles such as hyperlinking or primary key relationships. + +The ability to specify exactly how you want to represent relationships is powerful, but it also introduces complexity. In order to keep things more simple, REST framework now allows you to include reverse relationships simply by including the field name in the `fields` metadata of the serializer class. + +For example, in REST framework 2.2, reverse relationships needed to be included explicitly on a serializer class. + + class BlogSerializer(serializers.ModelSerializer): + comments = serializers.PrimaryKeyRelatedField(many=True) + + class Meta: + model = Blog + fields = ('id', 'title', 'created', 'comments') + +As of 2.3, you can simply include the field name, and the appropriate serializer field will automatically be used for the relationship. + + class BlogSerializer(serializers.ModelSerializer): + """ + Don't need to specify the 'comments' field explicitly anymore. + """ + class Meta: + model = Blog + fields = ('id', 'title', 'created', 'comments') + +Similarly, you can now easily include the primary key in hyperlinked relationships, simply by adding the field name to the metadata. + + class BlogSerializer(serializers.HyperlinkedModelSerializer): + """ + This is a hyperlinked serializer, which default to using + a field named 'url' as the primary identifier. + Note that we can now easily also add in the 'id' field. + """ + class Meta: + model = Blog + fields = ('url', 'id', 'title', 'created', 'comments') + +## Simpler views + +This release rationalises the API and implementation of the generic views, dropping the dependancy on Django's `SingleObjectMixin` and `MultipleObjectMixin` classes, removing a number of unneeded attributes, and generally making the implementation more obvious and easy to work with. + +This improvement is reflected in improved documentation for the `GenericAPIView` base class, and should make it easier to determine how to override methods on the base class if you need to write customized subclasses. + +--- + +# API Changes + +## Simplified generic view classes + +The functionality provided by `SingleObjectAPIView` and `MultipleObjectAPIView` base classes has now been moved into the base class `GenericAPIView`. The implementation of this base class is simple enough that providing subclasses for the base classes of detail and list views is somewhat unnecessary. + +Additionally the base generic view no longer inherits from Django's `SingleObjectMixin` or `MultipleObjectMixin` classes, simplifying the implementation, and meaning you don't need to cross-reference across to Django's codebase. + +Using the `SingleObjectAPIView` and `MultipleObjectAPIView` base classes continues to be supported, but will raise a `PendingDeprecationWarning`. You should instead simply use `GenericAPIView` as the base for any generic view subclasses. + +### Removed attributes + +The following attributes and methods, were previously present as part of Django's generic view implementations, but were unneeded and unusedand have now been entirely removed. + +* context_object_name +* get_context_data() +* get_context_object_name() + +The following attributes and methods, which were previously present as part of Django's generic view implementations have also been entirely removed. + +* paginator_class +* get_paginator() +* get_allow_empty() +* get_slug_field() + +There may be cases when removing these bits of API might mean you need to write a little more code if your view has highly customized behavior, but generally we believe that providing a coarser-grained API will make the views easier to work with, and is the right trade-off to make for the vast majority of cases. + +Note that the listed attributes and methods have never been a documented part of the REST framework API, and as such are not covered by the deprecation policy. + +### Simplified methods + +The `get_object` and `get_paginate_by` methods no longer take an optional queryset argument. This makes overridden these methods more obvious, and a little more simple. + +Using an optional queryset with these methods continues to be supported, but will raise a `PendingDeprecationWarning`. + +The `paginate_queryset` method no longer takes a `page_size` argument, or returns a four-tuple of pagination information. Instead it simply takes a queryset argument, and either returns a `page` object with an appropraite page size, or returns `None`, if pagination is not configured for the view. + +Using the `page_size` argument is still supported and will trigger the old-style return type, but will raise a `PendingDeprecationWarning`. + +### Deprecated attributes + +The following attributes are used to control queryset lookup, and have all been moved into a pending deprecation state. + +* pk_url_kwarg = 'pk' +* slug_url_kwarg = 'slug' +* slug_field = 'slug' + +Their usage is replaced with a single attribute: + +* lookup_field = 'pk' + +This attribute is used both as the regex keyword argument in the URL conf, and as the model field to filter against when looking up a model instance. To use non-pk based lookup, simply set the `lookup_field` argument to an alternative field, and ensure that the keyword argument in the url conf matches the field name. + +For example, a view with 'username' based lookup might look like this: + + class UserDetail(generics.RetrieveAPIView): + lookup_field = 'username' + queryset = User.objects.all() + serializer_class = UserSerializer + +And would have the following entry in the urlconf: + + url(r'^users/(?P<username>\w+)/$', UserDetail.as_view()), + + +Usage of the old-style attributes continues to be supported, but will raise a `PendingDeprecationWarning`. + +## DecimalField + +2.3 introduces a `DecimalField` serializer field, which returns `Decimal` instances. + +For most cases APIs using model fields will behave as previously, however if you are using a custom renderer, not provided by REST framework, then you may now need to add support for rendering `Decimal` instances to your renderer implmentation. + +--- + +# Other notes + +## Explict view attributes + +The usage of `model` attribute in generic Views is still supported, but it's usage is being discouraged in favour of using explict `queryset` and `serializer_class` attributes. + +For example, the following is now the recommended style for using generic views: + + class AccountListView(generics.RetrieveAPIView): + queryset = MyModel.objects.all() + serializer_class = MyModelSerializer + +Using explict `queryset` and `serializer_class` attributes makes the functioning of the view more clear than using the shortcut `model` attribute. + +It also makes it the usage of overridden `get_queryset()` or `get_serializer_class()` methods more obvious. + + class AccountListView(generics.RetrieveAPIView): + serializer_class = MyModelSerializer + + def get_queryset(self): + """ + Determine the queryset dynamically, depending on the + user making the request. + + Note that overriding this method follows on more obviously now + that an explicit `queryset` attribute is the usual view style. + """ + return self.user.accounts + +## Django 1.3 support + +The 2.3 release series will be the last series to provide compatiblity with Django 1.3. + +## What comes next? + +The plan for the next few months is to concentrate on addressing outstanding tickets. 2.4 is likely to deal with relatively small refinements to the existing API. diff --git a/docs/topics/migration.md b/docs/topics/migration.md deleted file mode 100644 index 25fc9074..00000000 --- a/docs/topics/migration.md +++ /dev/null @@ -1,89 +0,0 @@ -# 2.0 Migration Guide - -> Move fast and break things -> -> — 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/ diff --git a/docs/topics/release-notes.md b/docs/topics/release-notes.md index 68a1426a..8094cc4a 100644 --- a/docs/topics/release-notes.md +++ b/docs/topics/release-notes.md @@ -38,11 +38,29 @@ 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. +* DecimalField support. + +**Note**: See the [2.3 announcement][2.3-announcement] for full details. + +--- + ## 2.2.x series -### Master +### 2.2.7 + +**Date**: 17th April 2013 -* DecimalField support +* Loud failure when view does not return a `Response` or `HttpResponse`. +* Bugfix: Fix for Django 1.3 compatiblity. +* Bugfix: Allow overridden `get_object()` to work correctly. ### 2.2.6 @@ -454,6 +472,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 [defusedxml-announce]: http://blog.python.org/2013/02/announcing-defusedxml-fixes-for-xml.html [2.2-announcement]: 2.2-announcement.md +[2.3-announcement]: 2.3-announcement.md [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 [staticfiles13]: https://docs.djangoproject.com/en/1.3/howto/static-files/#with-a-template-tag diff --git a/docs/tutorial/3-class-based-views.md b/docs/tutorial/3-class-based-views.md index e05017c5..70cf2c54 100644 --- a/docs/tutorial/3-class-based-views.md +++ b/docs/tutorial/3-class-based-views.md @@ -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, mixins.CreateModelMixin, - generics.MultipleObjectAPIView): - model = Snippet + generics.GenericAPIView): + queryset = Snippet.objects.all() serializer_class = SnippetSerializer 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. def post(self, 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. class SnippetDetail(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, - generics.SingleObjectAPIView): - model = Snippet + generics.GenericAPIView): + queryset = Snippet.objects.all() serializer_class = SnippetSerializer def get(self, request, *args, **kwargs): @@ -122,7 +122,7 @@ The base class provides the core functionality, and the mixin classes provide th def delete(self, 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 @@ -134,12 +134,12 @@ Using the mixin classes we've rewritten the views to use slightly less code than class SnippetList(generics.ListCreateAPIView): - model = Snippet + queryset = Snippet.objects.all() serializer_class = SnippetSerializer class SnippetDetail(generics.RetrieveUpdateDestroyAPIView): - model = Snippet + queryset = Snippet.objects.all() 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. diff --git a/docs/tutorial/4-authentication-and-permissions.md b/docs/tutorial/4-authentication-and-permissions.md index 878672bb..d3ee8e79 100644 --- a/docs/tutorial/4-authentication-and-permissions.md +++ b/docs/tutorial/4-authentication-and-permissions.md @@ -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. class UserList(generics.ListAPIView): - model = User + queryset = User.objects.all() serializer_class = UserSerializer class UserDetail(generics.RetrieveAPIView): - model = User + queryset = User.objects.all() serializer_class = UserSerializer Finally we need to add those views into the API, by referencing them from the URL conf. diff --git a/docs/tutorial/5-relationships-and-hyperlinked-apis.md b/docs/tutorial/5-relationships-and-hyperlinked-apis.md index 27a10840..c9c37547 100644 --- a/docs/tutorial/5-relationships-and-hyperlinked-apis.md +++ b/docs/tutorial/5-relationships-and-hyperlinked-apis.md @@ -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.response import Response - class SnippetHighlight(generics.SingleObjectAPIView): - model = Snippet + class SnippetHighlight(generics.GenericAPIView): + queryset = Snippet.objects.all() renderer_classes = (renderers.StaticHTMLRenderer,) def get(self, request, *args, **kwargs): @@ -143,34 +143,16 @@ We can change the default list style to use pagination, by modifying our `settin '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. -## Reviewing our work +## Browsing the API If we open a browser and navigate to the browseable 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. -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. +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. - -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 +[tut-6]: 6-viewsets-and-routers.md diff --git a/docs/tutorial/6-viewsets-and-routers.md b/docs/tutorial/6-viewsets-and-routers.md new file mode 100644 index 00000000..876d89ac --- /dev/null +++ b/docs/tutorial/6-viewsets-and-routers.md @@ -0,0 +1,151 @@ +# 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, 'snippet') + router.register(r'users', views.UserViewSet, 'user') + + # 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 three arguments - the URL prefix for the views, the viewset itself, and the base name that should be used for constructing the URL names, such as `snippet-list`. + +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 view sets 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
\ No newline at end of file @@ -47,10 +47,13 @@ path_list = [ 'tutorial/3-class-based-views.md', 'tutorial/4-authentication-and-permissions.md', 'tutorial/5-relationships-and-hyperlinked-apis.md', + 'tutorial/6-viewsets-and-routers.md', 'api-guide/requests.md', 'api-guide/responses.md', 'api-guide/views.md', 'api-guide/generic-views.md', + 'api-guide/viewsets.md', + 'api-guide/routers.md', 'api-guide/parsers.md', 'api-guide/renderers.md', 'api-guide/serializers.md', @@ -74,6 +77,7 @@ path_list = [ 'topics/contributing.md', 'topics/rest-framework-2-announcement.md', 'topics/2.2-announcement.md', + 'topics/2.3-announcement.md', 'topics/release-notes.md', 'topics/credits.md', ] diff --git a/rest_framework/__init__.py b/rest_framework/__init__.py index 7ac12058..856badc6 100644 --- a/rest_framework/__init__.py +++ b/rest_framework/__init__.py @@ -1,4 +1,4 @@ -__version__ = '2.2.6' +__version__ = '2.2.7' VERSION = __version__ # synonym diff --git a/rest_framework/authentication.py b/rest_framework/authentication.py index 1eebb5b9..9caca788 100644 --- a/rest_framework/authentication.py +++ b/rest_framework/authentication.py @@ -1,5 +1,5 @@ """ -Provides a set of pluggable authentication policies. +Provides various authentication policies. """ from __future__ import unicode_literals import base64 diff --git a/rest_framework/compat.py b/rest_framework/compat.py index 067e9018..3828555b 100644 --- a/rest_framework/compat.py +++ b/rest_framework/compat.py @@ -87,9 +87,7 @@ else: raise ImportError("User model is not to be found.") -# First implementation of Django class-based views did not include head method -# in base View class - https://code.djangoproject.com/ticket/15668 -if django.VERSION >= (1, 4): +if django.VERSION >= (1, 5): from django.views.generic import View else: from django.views.generic import View as _View @@ -97,6 +95,8 @@ else: from django.utils.functional import update_wrapper class View(_View): + # 1.3 does not include head method in base View class + # See: https://code.djangoproject.com/ticket/15668 @classonlymethod def as_view(cls, **initkwargs): """ @@ -126,11 +126,15 @@ else: update_wrapper(view, cls.dispatch, assigned=()) return view -# Taken from @markotibold's attempt at supporting PATCH. -# https://github.com/markotibold/django-rest-framework/tree/patch -http_method_names = set(View.http_method_names) -http_method_names.add('patch') -View.http_method_names = list(http_method_names) # PATCH method is not implemented by Django + # _allowed_methods only present from 1.5 onwards + def _allowed_methods(self): + return [m.upper() for m in self.http_method_names if hasattr(self, m)] + + +# 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. if django.VERSION >= (1, 4): diff --git a/rest_framework/decorators.py b/rest_framework/decorators.py index 8250cd3b..81e585e1 100644 --- a/rest_framework/decorators.py +++ b/rest_framework/decorators.py @@ -1,3 +1,11 @@ +""" +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 rest_framework.compat import six from rest_framework.views import APIView @@ -97,3 +105,25 @@ def permission_classes(permission_classes): func.permission_classes = permission_classes return func 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 diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 926195be..38fe025d 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -1,3 +1,8 @@ +""" +Serializer fields perform validation on incoming data. + +They are very similar to Django's form fields. +""" from __future__ import unicode_literals import copy diff --git a/rest_framework/filters.py b/rest_framework/filters.py index 413fa0d2..5e1cdbac 100644 --- a/rest_framework/filters.py +++ b/rest_framework/filters.py @@ -1,3 +1,7 @@ +""" +Provides generic filtering backends that can be used to filter the results +returned by list views. +""" from __future__ import unicode_literals from rest_framework.compat import django_filters diff --git a/rest_framework/generics.py b/rest_framework/generics.py index f9133c73..a18584d4 100644 --- a/rest_framework/generics.py +++ b/rest_framework/generics.py @@ -4,30 +4,55 @@ Generic views that provide commonly needed behaviour. from __future__ import unicode_literals from rest_framework import views, mixins from rest_framework.settings import api_settings -from django.views.generic.detail import SingleObjectMixin -from django.views.generic.list import MultipleObjectMixin +from django.core.exceptions import ImproperlyConfigured +from django.core.paginator import Paginator, InvalidPage +from django.http import Http404 +from django.shortcuts import get_object_or_404 +from django.utils.translation import ugettext as _ -### Base classes for the generic views ### - class GenericAPIView(views.APIView): """ Base class for all other generic views. """ - model = None + # You'll need to either set these attributes, + # or override `get_queryset`/`get_serializer_class`. + queryset = None serializer_class = None - model_serializer_class = api_settings.DEFAULT_MODEL_SERIALIZER_CLASS + + # If you want to use object lookups other than pk, set this attribute. + lookup_field = 'pk' + + # Pagination settings + paginate_by = api_settings.PAGINATE_BY + paginate_by_param = api_settings.PAGINATE_BY_PARAM + pagination_serializer_class = api_settings.DEFAULT_PAGINATION_SERIALIZER_CLASS + page_kwarg = 'page' + + # The filter backend class to use for queryset filtering filter_backend = api_settings.FILTER_BACKEND - def filter_queryset(self, queryset): - """ - Given a queryset, filter it with whichever filter backend is in use. - """ - if not self.filter_backend: - return queryset - backend = self.filter_backend() - return backend.filter_queryset(self.request, queryset, self) + # Determines if the view will return 200 or 404 responses for empty lists. + allow_empty = True + + # This shortcut may be used instead of setting either (or both) + # of the `queryset`/`serializer_class` attributes, although using + # the explicit style is generally preferred. + model = None + + # If the `model` shortcut is used instead of `serializer_class`, then the + # serializer class will be constructed using this class as the base. + model_serializer_class = api_settings.DEFAULT_MODEL_SERIALIZER_CLASS + + _paginator_class = Paginator + + ###################################### + # These are pending deprecation... + + pk_url_kwarg = 'pk' + slug_url_kwarg = 'slug' + slug_field = 'slug' def get_serializer_context(self): """ @@ -39,24 +64,6 @@ class GenericAPIView(views.APIView): 'view': self } - def get_serializer_class(self): - """ - Return the class to use for the serializer. - - Defaults to using `self.serializer_class`, falls back to constructing a - model serializer class using `self.model_serializer_class`, with - `self.model` as the model. - """ - serializer_class = self.serializer_class - - if serializer_class is None: - class DefaultSerializer(self.model_serializer_class): - class Meta: - model = self.model - serializer_class = DefaultSerializer - - return serializer_class - def get_serializer(self, instance=None, data=None, files=None, many=False, partial=False): """ @@ -68,31 +75,7 @@ class GenericAPIView(views.APIView): return serializer_class(instance, data=data, files=files, many=many, partial=partial, context=context) - def pre_save(self, obj): - """ - Placeholder method for calling before saving an object. - May be used eg. to set attributes on the object that are implicit - in either the request, or the url. - """ - pass - - def post_save(self, obj, created=False): - """ - Placeholder method for calling after saving an object. - """ - pass - - -class MultipleObjectAPIView(MultipleObjectMixin, GenericAPIView): - """ - Base class for generic views onto a queryset. - """ - - paginate_by = api_settings.PAGINATE_BY - paginate_by_param = api_settings.PAGINATE_BY_PARAM - pagination_serializer_class = api_settings.DEFAULT_PAGINATION_SERIALIZER_CLASS - - def get_pagination_serializer(self, page=None): + def get_pagination_serializer(self, page): """ Return a serializer instance to use with paginated data. """ @@ -104,41 +87,191 @@ class MultipleObjectAPIView(MultipleObjectMixin, GenericAPIView): context = self.get_serializer_context() return pagination_serializer_class(instance=page, context=context) - def get_paginate_by(self, queryset): + def paginate_queryset(self, queryset, page_size=None): + """ + Paginate a queryset if required, either returning a page object, + or `None` if pagination is not configured for this view. + """ + deprecated_style = False + if page_size is not None: + # TODO: Deperecation warning + deprecated_style = True + else: + # Determine the required page size. + # If pagination is not configured, simply return None. + page_size = self.get_paginate_by() + if not page_size: + return None + + paginator = self._paginator_class(queryset, page_size, + allow_empty_first_page=self.allow_empty) + page_kwarg = self.kwargs.get(self.page_kwarg) + page_query_param = self.request.QUERY_PARAMS.get(self.page_kwarg) + page = page_kwarg or page_query_param or 1 + try: + page_number = int(page) + except ValueError: + if page == 'last': + page_number = paginator.num_pages + else: + raise Http404(_("Page is not 'last', nor can it be converted to an int.")) + try: + page = paginator.page(page_number) + except InvalidPage as e: + raise Http404(_('Invalid page (%(page_number)s): %(message)s') % { + 'page_number': page_number, + 'message': str(e) + }) + + if deprecated_style: + return (paginator, page, page.object_list, page.has_other_pages()) + return page + + def filter_queryset(self, queryset): + """ + Given a queryset, filter it with whichever filter backend is in use. + + You are unlikely to want to override this method, although you may need + to call it either from a list view, or from a custom `get_object` + method if you want to apply the configured filtering backend to the + default queryset. + """ + if not self.filter_backend: + return queryset + backend = self.filter_backend() + return backend.filter_queryset(self.request, queryset, self) + + ######################## + ### The following methods provide default implementations + ### that you may want to override for more complex cases. + + def get_paginate_by(self, queryset=None): """ Return the size of pages to use with pagination. + + If `PAGINATE_BY_PARAM` is set it will attempt to get the page size + from a named query parameter in the url, eg. ?page_size=100 + + Otherwise defaults to using `self.paginate_by`. """ + if queryset is not None: + pass # TODO: Deprecation warning + if self.paginate_by_param: query_params = self.request.QUERY_PARAMS try: return int(query_params[self.paginate_by_param]) except (KeyError, ValueError): pass + return self.paginate_by + def get_serializer_class(self): + """ + Return the class to use for the serializer. + Defaults to using `self.serializer_class`. -class SingleObjectAPIView(SingleObjectMixin, GenericAPIView): - """ - Base class for generic views onto a model instance. - """ + You may want to override this if you need to provide different + serializations depending on the incoming request. - pk_url_kwarg = 'pk' # Not provided in Django 1.3 - slug_url_kwarg = 'slug' # Not provided in Django 1.3 - slug_field = 'slug' + (Eg. admins get full serialization, others get basic serilization) + """ + serializer_class = self.serializer_class + if serializer_class is not None: + return serializer_class + + class DefaultSerializer(self.model_serializer_class): + class Meta: + model = self.model + return DefaultSerializer + + def get_queryset(self): + """ + Get the list of items for this view. + This must be an iterable, and may be a queryset. + Defaults to using `self.queryset`. + + You may want to override this if you need to provide different + querysets depending on the incoming request. + + (Eg. return a list of items that is specific to the user) + """ + if self.queryset is not None: + return self.queryset._clone() + + if self.model is not None: + return self.model._default_manager.all() + + raise ImproperlyConfigured("'%s' must define 'queryset' or 'model'" + % self.__class__.__name__) def get_object(self, queryset=None): """ - Override default to add support for object-level permissions. + Returns the object the view is displaying. + + You may want to override this if you need to provide non-standard + queryset lookups. Eg if objects are referenced using multiple + keyword arguments in the url conf. """ - queryset = self.filter_queryset(self.get_queryset()) - obj = super(SingleObjectAPIView, self).get_object(queryset) + # Determine the base queryset to use. + if queryset is None: + queryset = self.filter_queryset(self.get_queryset()) + else: + pass # Deprecation warning + + # Perform the lookup filtering. + pk = self.kwargs.get(self.pk_url_kwarg, None) + slug = self.kwargs.get(self.slug_url_kwarg, None) + lookup = self.kwargs.get(self.lookup_field, None) + + if lookup is not None: + filter_kwargs = {self.lookup_field: lookup} + elif pk is not None: + # TODO: Deprecation warning + filter_kwargs = {'pk': pk} + elif slug is not None: + # TODO: Deprecation warning + filter_kwargs = {self.slug_field: slug} + else: + # TODO: Fix error message + raise AttributeError("Generic detail view %s must be called with " + "either an object pk or a slug." + % self.__class__.__name__) + + obj = get_object_or_404(queryset, **filter_kwargs) + + # May raise a permission denied self.check_object_permissions(self.request, obj) + return obj + ######################## + ### The following are placeholder methods, + ### and are intended to be overridden. + ### + ### The are not called by GenericAPIView directly, + ### but are used by the mixin methods. -### Concrete view classes that provide method handlers ### -### by composing the mixin classes with a base view. ### + def pre_save(self, obj): + """ + Placeholder method for calling before saving an object. + May be used to set attributes on the object that are implicit + in either the request, or the url. + """ + pass + + def post_save(self, obj, created=False): + """ + Placeholder method for calling after saving an object. + """ + pass + + +########################################################## +### Concrete view classes that provide method handlers ### +### by composing the mixin classes with the base view. ### +########################################################## class CreateAPIView(mixins.CreateModelMixin, GenericAPIView): @@ -151,7 +284,7 @@ class CreateAPIView(mixins.CreateModelMixin, class ListAPIView(mixins.ListModelMixin, - MultipleObjectAPIView): + GenericAPIView): """ Concrete view for listing a queryset. """ @@ -160,7 +293,7 @@ class ListAPIView(mixins.ListModelMixin, class RetrieveAPIView(mixins.RetrieveModelMixin, - SingleObjectAPIView): + GenericAPIView): """ Concrete view for retrieving a model instance. """ @@ -169,7 +302,7 @@ class RetrieveAPIView(mixins.RetrieveModelMixin, class DestroyAPIView(mixins.DestroyModelMixin, - SingleObjectAPIView): + GenericAPIView): """ Concrete view for deleting a model instance. @@ -179,7 +312,7 @@ class DestroyAPIView(mixins.DestroyModelMixin, class UpdateAPIView(mixins.UpdateModelMixin, - SingleObjectAPIView): + GenericAPIView): """ Concrete view for updating a model instance. @@ -188,13 +321,12 @@ class UpdateAPIView(mixins.UpdateModelMixin, return self.update(request, *args, **kwargs) def patch(self, request, *args, **kwargs): - kwargs['partial'] = True - return self.update(request, *args, **kwargs) + return self.partial_update(request, *args, **kwargs) class ListCreateAPIView(mixins.ListModelMixin, mixins.CreateModelMixin, - MultipleObjectAPIView): + GenericAPIView): """ Concrete view for listing a queryset or creating a model instance. """ @@ -207,7 +339,7 @@ class ListCreateAPIView(mixins.ListModelMixin, class RetrieveUpdateAPIView(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, - SingleObjectAPIView): + GenericAPIView): """ Concrete view for retrieving, updating a model instance. """ @@ -218,13 +350,12 @@ class RetrieveUpdateAPIView(mixins.RetrieveModelMixin, return self.update(request, *args, **kwargs) def patch(self, request, *args, **kwargs): - kwargs['partial'] = True - return self.update(request, *args, **kwargs) + return self.partial_update(request, *args, **kwargs) class RetrieveDestroyAPIView(mixins.RetrieveModelMixin, mixins.DestroyModelMixin, - SingleObjectAPIView): + GenericAPIView): """ Concrete view for retrieving or deleting a model instance. """ @@ -238,7 +369,7 @@ class RetrieveDestroyAPIView(mixins.RetrieveModelMixin, class RetrieveUpdateDestroyAPIView(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, - SingleObjectAPIView): + GenericAPIView): """ Concrete view for retrieving, updating or deleting a model instance. """ @@ -249,8 +380,19 @@ class RetrieveUpdateDestroyAPIView(mixins.RetrieveModelMixin, return self.update(request, *args, **kwargs) def patch(self, request, *args, **kwargs): - kwargs['partial'] = True - return self.update(request, *args, **kwargs) + return self.partial_update(request, *args, **kwargs) def delete(self, request, *args, **kwargs): return self.destroy(request, *args, **kwargs) + + +########################## +### Deprecated classes ### +########################## + +class MultipleObjectAPIView(GenericAPIView): + pass + + +class SingleObjectAPIView(GenericAPIView): + pass diff --git a/rest_framework/mixins.py b/rest_framework/mixins.py index 3bd7d6df..ec751e24 100644 --- a/rest_framework/mixins.py +++ b/rest_framework/mixins.py @@ -67,23 +67,18 @@ class ListModelMixin(object): empty_error = "Empty list and '%(class_name)s.allow_empty' is False." def list(self, request, *args, **kwargs): - queryset = self.get_queryset() - self.object_list = self.filter_queryset(queryset) + self.object_list = self.filter_queryset(self.get_queryset()) # Default is to allow empty querysets. This can be altered by setting # `.allow_empty = False`, to raise 404 errors on empty querysets. - allow_empty = self.get_allow_empty() - if not allow_empty and not self.object_list: + if not self.allow_empty and not self.object_list: class_name = self.__class__.__name__ error_msg = self.empty_error % {'class_name': class_name} raise Http404(error_msg) - # Pagination size is set by the `.paginate_by` attribute, - # which may be `None` to disable pagination. - page_size = self.get_paginate_by(self.object_list) - if page_size: - packed = self.paginate_queryset(self.object_list, page_size) - paginator, page, queryset, is_paginated = packed + # Switch between paginated or standard style responses + page = self.paginate_queryset(self.object_list) + if page is not None: serializer = self.get_pagination_serializer(page) else: serializer = self.get_serializer(self.object_list, many=True) @@ -135,6 +130,10 @@ class UpdateModelMixin(object): 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): """ Set any attributes on the object that are implicit in the request. @@ -142,7 +141,7 @@ class UpdateModelMixin(object): # pk and/or slug attributes are implicit in the URL. pk = self.kwargs.get(self.pk_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 pk: setattr(obj, 'pk', pk) diff --git a/rest_framework/negotiation.py b/rest_framework/negotiation.py index 0694d35f..4d205c0e 100644 --- a/rest_framework/negotiation.py +++ b/rest_framework/negotiation.py @@ -1,3 +1,7 @@ +""" +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 django.http import Http404 from rest_framework import exceptions diff --git a/rest_framework/pagination.py b/rest_framework/pagination.py index 03a7a30f..d51ea929 100644 --- a/rest_framework/pagination.py +++ b/rest_framework/pagination.py @@ -1,9 +1,11 @@ +""" +Pagination serializers determine the structure of the output that should +be used for paginated responses. +""" from __future__ import unicode_literals from rest_framework import serializers from rest_framework.templatetags.rest_framework import replace_query_param -# TODO: Support URLconf kwarg-style paging - class NextPageField(serializers.Field): """ diff --git a/rest_framework/permissions.py b/rest_framework/permissions.py index ae895f39..2aa45c71 100644 --- a/rest_framework/permissions.py +++ b/rest_framework/permissions.py @@ -25,7 +25,7 @@ class BasePermission(object): """ 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. ' 'Use `has_object_permission()` instead for object permissions.', PendingDeprecationWarning, stacklevel=2) diff --git a/rest_framework/relations.py b/rest_framework/relations.py index 2a10e9af..6bda7418 100644 --- a/rest_framework/relations.py +++ b/rest_framework/relations.py @@ -1,3 +1,9 @@ +""" +Serializer fields that deal with relationships. + +These fields allow you to specify the style that should be used to represent +model relationships, including hyperlinks, primary keys, or slugs. +""" from __future__ import unicode_literals from django.core.exceptions import ObjectDoesNotExist, ValidationError from django.core.urlresolvers import resolve, get_script_prefix, NoReverseMatch diff --git a/rest_framework/renderers.py b/rest_framework/renderers.py index 4c15e0db..752306ad 100644 --- a/rest_framework/renderers.py +++ b/rest_framework/renderers.py @@ -24,6 +24,7 @@ from rest_framework.settings import api_settings from rest_framework.request import clone_request from rest_framework.utils import encoders 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 @@ -438,16 +439,10 @@ class BrowsableAPIRenderer(BaseRenderer): return GenericContentForm() def get_name(self, view): - try: - return view.get_name() - except AttributeError: - return smart_text(view.__class__.__name__) + return get_view_name(view.__class__) def get_description(self, view): - try: - return view.get_description(html=True) - except AttributeError: - return smart_text(view.__doc__ or '') + return get_view_description(view.__class__, html=True) def render(self, data, accepted_media_type=None, renderer_context=None): """ diff --git a/rest_framework/request.py b/rest_framework/request.py index ffbbab33..a434659c 100644 --- a/rest_framework/request.py +++ b/rest_framework/request.py @@ -1,11 +1,10 @@ """ -The :mod:`request` module provides a :class:`Request` class used to wrap the standard `request` -object received in all the views. +The Request class is used as a wrapper around the standard request object. The wrapped request then offers a richer API, in particular : - 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 - form overloading of HTTP method, content type and content """ diff --git a/rest_framework/response.py b/rest_framework/response.py index 5e1bf46e..26e4ab37 100644 --- a/rest_framework/response.py +++ b/rest_framework/response.py @@ -1,3 +1,9 @@ +""" +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 django.core.handlers.wsgi import STATUS_CODE_TEXT from django.template.response import SimpleTemplateResponse diff --git a/rest_framework/routers.py b/rest_framework/routers.py new file mode 100644 index 00000000..b7052218 --- /dev/null +++ b/rest_framework/routers.py @@ -0,0 +1,236 @@ +""" +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 django.conf.urls import url, patterns +from django.db import models +from rest_framework.decorators import api_view +from rest_framework.response import Response +from rest_framework.reverse import reverse +from rest_framework.viewsets import ModelViewSet +from rest_framework.urlpatterns import format_suffix_patterns + + +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, basename): + self.registry.append((prefix, viewset, basename)) + + def get_urls(self): + 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. + ( + r'^{prefix}/$', + { + 'get': 'list', + 'post': 'create' + }, + '{basename}-list' + ), + # Detail route. + ( + r'^{prefix}/{lookup}/$', + { + 'get': 'retrieve', + 'put': 'update', + 'patch': 'partial_update', + 'delete': 'destroy' + }, + '{basename}-detail' + ), + # Dynamically generated routes. + # Generated using @action or @link decorators on methods of the viewset. + ( + r'^{prefix}/{lookup}/{methodname}/$', + { + '{httpmethod}': '{methodname}', + }, + '{basename}-{methodnamehyphen}' + ), + ] + + def get_routes(self, viewset): + """ + Augment `self.routes` with any dynamically generated routes. + + Returns a list of 4-tuples, of the form: + `(url_format, method_map, name_format, extra_kwargs)` + """ + + # 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 url_format, method_map, name_format in self.routes: + if method_map == {'{httpmethod}': '{methodname}'}: + # Dynamic routes (@link or @action decorator) + for httpmethod, methodname in dynamic_routes.items(): + extra_kwargs = getattr(viewset, methodname).kwargs + ret.append(( + replace_methodname(url_format, methodname), + {httpmethod: methodname}, + replace_methodname(name_format, methodname), + extra_kwargs + )) + else: + # Standard route + extra_kwargs = {} + ret.append((url_format, method_map, name_format, extra_kwargs)) + + 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 url_format, method_map, name_format, extra_kwargs in routes: + + # Only actions which actually exist on the viewset will be bound + method_map = self.get_method_map(viewset, method_map) + if not method_map: + continue + + # Build the url pattern + regex = url_format.format(prefix=prefix, lookup=lookup) + view = viewset.as_view(method_map, **extra_kwargs) + name = name_format.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][-1] + 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 + + +class AutoRouter(DefaultRouter): + """ + A router class that doesn't require you to register any viewsets, + but instead automatically creates routes for all installed models. + + Useful for quick and dirty prototyping. + """ + def __init__(self): + super(AutoRouter, self).__init__() + for model in models.get_models(): + prefix = model._meta.verbose_name_plural.replace(' ', '_') + basename = model._meta.object_name.lower() + classname = model.__name__ + + DynamicViewSet = type( + classname, + (ModelViewSet,), + {} + ) + DynamicViewSet.model = model + + self.register(prefix, DynamicViewSet, basename) diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index cbc6586d..3d956e4d 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -1,3 +1,15 @@ +""" +Serializers and ModelSerializers are similar to Forms and ModelForms. +Unlike forms, they are not constrained to dealing with HTML output, and +form encoded input. + +Serialization in REST framework is a two-phase process: + +1. Serializers marshal between complex types like model instances, and +python primatives. +2. The process of marshalling between python primatives and request and +response content is handled by parsers and renderers. +""" from __future__ import unicode_literals import copy import datetime @@ -569,36 +581,73 @@ class ModelSerializer(Serializer): assert cls is not None, \ "Serializer class '%s' is missing 'model' Meta option" % self.__class__.__name__ opts = get_concrete_model(cls)._meta - pk_field = opts.pk + ret = SortedDict() + nested = bool(self.opts.depth) - # If model is a child via multitable inheritance, use parent's pk + # Deal with adding the primary key field + pk_field = opts.pk while pk_field.rel and pk_field.rel.parent_link: + # If model is a child via multitable inheritance, use parent's pk pk_field = pk_field.rel.to._meta.pk - fields = [pk_field] - fields += [field for field in opts.fields if field.serialize] - fields += [field for field in opts.many_to_many if field.serialize] + field = self.get_pk_field(pk_field) + if field: + ret[pk_field.name] = field - ret = SortedDict() - nested = bool(self.opts.depth) - is_pk = True # First field in the list is the pk - - for model_field in fields: - if is_pk: - field = self.get_pk_field(model_field) - is_pk = False - elif model_field.rel and nested: - field = self.get_nested_field(model_field) - elif model_field.rel: + # Deal with forward relationships + forward_rels = [field for field in opts.fields if field.serialize] + forward_rels += [field for field in opts.many_to_many if field.serialize] + + for model_field in forward_rels: + if model_field.rel: to_many = isinstance(model_field, models.fields.related.ManyToManyField) - field = self.get_related_field(model_field, to_many=to_many) + related_model = model_field.rel.to + + if model_field.rel and nested: + if len(inspect.getargspec(self.get_nested_field).args) == 2: + # TODO: deprecation warning + field = self.get_nested_field(model_field) + else: + field = self.get_nested_field(model_field, related_model, to_many) + elif model_field.rel: + if len(inspect.getargspec(self.get_nested_field).args) == 3: + # TODO: deprecation warning + field = self.get_related_field(model_field, to_many=to_many) + else: + field = self.get_related_field(model_field, related_model, to_many) else: field = self.get_field(model_field) if field: ret[model_field.name] = field + # Deal with reverse relationships + if not self.opts.fields: + reverse_rels = [] + else: + # Reverse relationships are only included if they are explicitly + # present in the `fields` option on the serializer + reverse_rels = opts.get_all_related_objects() + reverse_rels += opts.get_all_related_many_to_many_objects() + + for relation in reverse_rels: + accessor_name = relation.get_accessor_name() + if accessor_name not in self.opts.fields: + continue + related_model = relation.model + to_many = relation.field.rel.multiple + + if nested: + field = self.get_nested_field(None, related_model, to_many) + else: + field = self.get_related_field(None, related_model, to_many) + + if field: + ret[accessor_name] = field + + # Add the `read_only` flag to any fields that have bee specified + # in the `read_only_fields` option for field_name in self.opts.read_only_fields: assert field_name in ret, \ "read_only_fields on '%s' included invalid item '%s'" % \ @@ -613,27 +662,30 @@ class ModelSerializer(Serializer): """ return self.get_field(model_field) - def get_nested_field(self, model_field): + def get_nested_field(self, model_field, related_model, to_many): """ Creates a default instance of a nested relational field. """ class NestedModelSerializer(ModelSerializer): class Meta: - model = model_field.rel.to - return NestedModelSerializer() + model = related_model + return NestedModelSerializer(many=to_many) - def get_related_field(self, model_field, to_many=False): + def get_related_field(self, model_field, related_model, to_many): """ Creates a default instance of a flat relational field. """ # TODO: filter queryset using: # .using(db).complex_filter(self.rel.limit_choices_to) + kwargs = { - 'required': not(model_field.null or model_field.blank), - 'queryset': model_field.rel.to._default_manager, + 'queryset': related_model._default_manager, 'many': to_many } + if model_field: + kwargs['required'] = not(model_field.null or model_field.blank) + return PrimaryKeyRelatedField(**kwargs) def get_field(self, model_field): @@ -798,21 +850,24 @@ class HyperlinkedModelSerializer(ModelSerializer): return self._default_view_name % format_kwargs def get_pk_field(self, model_field): - return None + if self.opts.fields and model_field.name in self.opts.fields: + return self.get_field(model_field) - def get_related_field(self, model_field, to_many): + def get_related_field(self, model_field, related_model, to_many): """ Creates a default instance of a flat relational field. """ # TODO: filter queryset using: # .using(db).complex_filter(self.rel.limit_choices_to) - rel = model_field.rel.to kwargs = { - 'required': not(model_field.null or model_field.blank), - 'queryset': rel._default_manager, - 'view_name': self._get_default_view_name(rel), + 'queryset': related_model._default_manager, + 'view_name': self._get_default_view_name(related_model), 'many': to_many } + + if model_field: + kwargs['required'] = not(model_field.null or model_field.blank) + return HyperlinkedRelatedField(**kwargs) def get_identity(self, data): diff --git a/rest_framework/tests/description.py b/rest_framework/tests/description.py index 5b3315bc..52c1a34c 100644 --- a/rest_framework/tests/description.py +++ b/rest_framework/tests/description.py @@ -4,6 +4,7 @@ from __future__ import unicode_literals from django.test import TestCase from rest_framework.views import APIView 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. DESCRIPTION = """an example docstring @@ -49,22 +50,16 @@ MARKED_DOWN_gte_21 = """<h2 id="an-example-docstring">an example docstring</h2> class TestViewNamesAndDescriptions(TestCase): - def test_resource_name_uses_classname_by_default(self): - """Ensure Resource names are based on the classname by default.""" + def test_view_name_uses_class_name(self): + """ + Ensure view names are based on the class name. + """ class MockView(APIView): pass - self.assertEqual(MockView().get_name(), 'Mock') + self.assertEqual(get_view_name(MockView), 'Mock') - def test_resource_name_can_be_set_explicitly(self): - """Ensure Resource names can be set using the 'get_name' method.""" - 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.""" + def test_view_description_uses_docstring(self): + """Ensure view descriptions are based on the docstring.""" class MockView(APIView): """an example docstring ==================== @@ -81,44 +76,32 @@ class TestViewNamesAndDescriptions(TestCase): # hash style header #""" - self.assertEqual(MockView().get_description(), 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) + self.assertEqual(get_view_description(MockView), DESCRIPTION) - def test_resource_description_supports_unicode(self): + def test_view_description_supports_unicode(self): + """ + Unicode in docstrings should be respected. + """ class MockView(APIView): """Проверка""" pass - self.assertEqual(MockView().get_description(), "Проверка") - - - 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) + self.assertEqual(get_view_description(MockView), "Проверка") - def test_resource_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.""" + def test_view_description_can_be_empty(self): + """ + Ensure that if a view has no docstring, + then it's description is the empty string. + """ class MockView(APIView): pass - self.assertEqual(MockView().get_description(), '') + self.assertEqual(get_view_description(MockView), '') def test_markdown(self): - """Ensure markdown to HTML works as expected""" + """ + Ensure markdown to HTML works as expected. + """ if apply_markdown: gte_21_match = apply_markdown(DESCRIPTION) == MARKED_DOWN_gte_21 lt_21_match = apply_markdown(DESCRIPTION) == MARKED_DOWN_lt_21 diff --git a/rest_framework/tests/filterset.py b/rest_framework/tests/filterset.py index 1a71558c..1e53a5cd 100644 --- a/rest_framework/tests/filterset.py +++ b/rest_framework/tests/filterset.py @@ -61,7 +61,7 @@ if django_filters: class CommonFilteringTestCase(TestCase): def _serialize_object(self, obj): return {'id': obj.id, 'text': obj.text, 'decimal': obj.decimal, 'date': obj.date} - + def setUp(self): """ Create 10 FilterableItem instances. @@ -190,7 +190,7 @@ class IntegrationTestDetailFiltering(CommonFilteringTestCase): Integration tests for filtered detail views. """ urls = 'rest_framework.tests.filterset' - + def _get_url(self, item): return reverse('detail-view', kwargs=dict(pk=item.pk)) @@ -221,7 +221,7 @@ class IntegrationTestDetailFiltering(CommonFilteringTestCase): response = self.client.get('{url}?decimal={param}'.format(url=self._get_url(low_item), param=search_decimal)) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data, low_item_data) - + # Tests that multiple filters works. search_decimal = Decimal('5.25') search_date = datetime.date(2012, 10, 2) diff --git a/rest_framework/tests/generics.py b/rest_framework/tests/generics.py index f564890c..4a13389a 100644 --- a/rest_framework/tests/generics.py +++ b/rest_framework/tests/generics.py @@ -1,5 +1,6 @@ from __future__ import unicode_literals from django.db import models +from django.shortcuts import get_object_or_404 from django.test import TestCase from rest_framework import generics, serializers, status from rest_framework.tests.utils import RequestFactory @@ -302,6 +303,47 @@ class TestInstanceView(TestCase): self.assertEqual(new_obj.text, 'foobar') +class TestOverriddenGetObject(TestCase): + """ + Test cases for a RetrieveUpdateDestroyAPIView that does NOT use the + queryset/model mechanism but instead overrides get_object() + """ + def setUp(self): + """ + Create 3 BasicModel intances. + """ + items = ['foo', 'bar', 'baz'] + for item in items: + BasicModel(text=item).save() + self.objects = BasicModel.objects + self.data = [ + {'id': obj.id, 'text': obj.text} + for obj in self.objects.all() + ] + + class OverriddenGetObjectView(generics.RetrieveUpdateDestroyAPIView): + """ + Example detail view for override of get_object(). + """ + model = BasicModel + + def get_object(self): + pk = int(self.kwargs['pk']) + return get_object_or_404(BasicModel.objects.all(), id=pk) + + self.view = OverriddenGetObjectView.as_view() + + def test_overridden_get_object_view(self): + """ + GET requests to RetrieveUpdateDestroyAPIView should return a single object. + """ + request = factory.get('/1') + with self.assertNumQueries(1): + response = self.view(request, pk=1).render() + self.assertEqual(response.status_code, status.HTTP_200_OK) + self.assertEqual(response.data, self.data[0]) + + # Regression test for #285 class CommentSerializer(serializers.ModelSerializer): diff --git a/rest_framework/tests/relations_hyperlink.py b/rest_framework/tests/relations_hyperlink.py index b5702a48..b1eed9a7 100644 --- a/rest_framework/tests/relations_hyperlink.py +++ b/rest_framework/tests/relations_hyperlink.py @@ -26,42 +26,44 @@ urlpatterns = patterns('', ) +# ManyToMany class ManyToManyTargetSerializer(serializers.HyperlinkedModelSerializer): - sources = serializers.HyperlinkedRelatedField(many=True, view_name='manytomanysource-detail') - class Meta: model = ManyToManyTarget + fields = ('url', 'name', 'sources') class ManyToManySourceSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = ManyToManySource + fields = ('url', 'name', 'targets') +# ForeignKey class ForeignKeyTargetSerializer(serializers.HyperlinkedModelSerializer): - sources = serializers.HyperlinkedRelatedField(many=True, view_name='foreignkeysource-detail') - class Meta: model = ForeignKeyTarget + fields = ('url', 'name', 'sources') class ForeignKeySourceSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = ForeignKeySource + fields = ('url', 'name', 'target') # Nullable ForeignKey class NullableForeignKeySourceSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = NullableForeignKeySource + fields = ('url', 'name', 'target') -# OneToOne +# Nullable OneToOne class NullableOneToOneTargetSerializer(serializers.HyperlinkedModelSerializer): - nullable_source = serializers.HyperlinkedRelatedField(view_name='nullableonetoonesource-detail') - class Meta: model = OneToOneTarget + fields = ('url', 'name', 'nullable_source') # TODO: Add test that .data cannot be accessed prior to .is_valid diff --git a/rest_framework/tests/relations_nested.py b/rest_framework/tests/relations_nested.py index a125ba65..f6d006b3 100644 --- a/rest_framework/tests/relations_nested.py +++ b/rest_framework/tests/relations_nested.py @@ -6,38 +6,30 @@ from rest_framework.tests.models import ForeignKeyTarget, ForeignKeySource, Null class ForeignKeySourceSerializer(serializers.ModelSerializer): class Meta: - depth = 1 - model = ForeignKeySource - - -class FlatForeignKeySourceSerializer(serializers.ModelSerializer): - class Meta: model = ForeignKeySource + fields = ('id', 'name', 'target') + depth = 1 class ForeignKeyTargetSerializer(serializers.ModelSerializer): - sources = FlatForeignKeySourceSerializer(many=True) - class Meta: model = ForeignKeyTarget + fields = ('id', 'name', 'sources') + depth = 1 class NullableForeignKeySourceSerializer(serializers.ModelSerializer): class Meta: - depth = 1 model = NullableForeignKeySource - - -class NullableOneToOneSourceSerializer(serializers.ModelSerializer): - class Meta: - model = NullableOneToOneSource + fields = ('id', 'name', 'target') + depth = 1 class NullableOneToOneTargetSerializer(serializers.ModelSerializer): - nullable_source = NullableOneToOneSourceSerializer() - class Meta: model = OneToOneTarget + fields = ('id', 'name', 'nullable_source') + depth = 1 class ReverseForeignKeyTests(TestCase): diff --git a/rest_framework/tests/relations_pk.py b/rest_framework/tests/relations_pk.py index f08e1808..5ce8b567 100644 --- a/rest_framework/tests/relations_pk.py +++ b/rest_framework/tests/relations_pk.py @@ -5,41 +5,44 @@ from rest_framework.tests.models import ManyToManyTarget, ManyToManySource, Fore from rest_framework.compat import six +# ManyToMany class ManyToManyTargetSerializer(serializers.ModelSerializer): - sources = serializers.PrimaryKeyRelatedField(many=True) - class Meta: model = ManyToManyTarget + fields = ('id', 'name', 'sources') class ManyToManySourceSerializer(serializers.ModelSerializer): class Meta: model = ManyToManySource + fields = ('id', 'name', 'targets') +# ForeignKey class ForeignKeyTargetSerializer(serializers.ModelSerializer): - sources = serializers.PrimaryKeyRelatedField(many=True) - class Meta: model = ForeignKeyTarget + fields = ('id', 'name', 'sources') class ForeignKeySourceSerializer(serializers.ModelSerializer): class Meta: model = ForeignKeySource + fields = ('id', 'name', 'target') +# Nullable ForeignKey class NullableForeignKeySourceSerializer(serializers.ModelSerializer): class Meta: model = NullableForeignKeySource + fields = ('id', 'name', 'target') -# OneToOne +# Nullable OneToOne class NullableOneToOneTargetSerializer(serializers.ModelSerializer): - nullable_source = serializers.PrimaryKeyRelatedField() - class Meta: model = OneToOneTarget + fields = ('id', 'name', 'nullable_source') # TODO: Add test that .data cannot be accessed prior to .is_valid diff --git a/rest_framework/tests/serializer.py b/rest_framework/tests/serializer.py index 05217f35..3a94fad5 100644 --- a/rest_framework/tests/serializer.py +++ b/rest_framework/tests/serializer.py @@ -738,6 +738,43 @@ class ManyRelatedTests(TestCase): 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): post = BlogPost.objects.create(title="Test blog post") post.blogpostcomment_set.create(text="I love this blog post") diff --git a/rest_framework/throttling.py b/rest_framework/throttling.py index 810cad63..93ea9816 100644 --- a/rest_framework/throttling.py +++ b/rest_framework/throttling.py @@ -1,3 +1,6 @@ +""" +Provides various throttling policies. +""" from __future__ import unicode_literals from django.core.cache import cache from rest_framework import exceptions @@ -28,9 +31,8 @@ class SimpleRateThrottle(BaseThrottle): A simple cache implementation, that only requires `.get_cache_key()` to be overridden. - The rate (requests / seconds) is set by a :attr:`throttle` attribute - on the :class:`.View` class. The attribute is a string of the form 'number of - requests/period'. + The rate (requests / seconds) is set by a `throttle` attribute on the View + class. The attribute is a string of the form 'number_of_requests/period'. Period should be one of: ('s', 'sec', 'm', 'min', 'h', 'hour', 'd', 'day') diff --git a/rest_framework/utils/breadcrumbs.py b/rest_framework/utils/breadcrumbs.py index af21ac79..18b3b207 100644 --- a/rest_framework/utils/breadcrumbs.py +++ b/rest_framework/utils/breadcrumbs.py @@ -1,5 +1,6 @@ from __future__ import unicode_literals from django.core.urlresolvers import resolve, get_script_prefix +from rest_framework.utils.formatting import get_view_name def get_breadcrumbs(url): @@ -16,11 +17,11 @@ def get_breadcrumbs(url): pass else: # Check if this is a REST framework view, and if so add it to the breadcrumbs - if isinstance(getattr(view, 'cls_instance', None), APIView): + if issubclass(getattr(view, 'cls', None), APIView): # Don't list the same view twice in a row. # Probably an optional trailing slash. if not seen or seen[-1] != view: - breadcrumbs_list.insert(0, (view.cls_instance.get_name(), prefix + url)) + breadcrumbs_list.insert(0, (get_view_name(view.cls), prefix + url)) seen.append(view) if url == '': diff --git a/rest_framework/utils/formatting.py b/rest_framework/utils/formatting.py new file mode 100644 index 00000000..79566db1 --- /dev/null +++ b/rest_framework/utils/formatting.py @@ -0,0 +1,77 @@ +""" +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): + """ + 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') + return _camelcase_to_spaces(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) diff --git a/rest_framework/views.py b/rest_framework/views.py index 81cbdcbb..555fa2f4 100644 --- a/rest_framework/views.py +++ b/rest_framework/views.py @@ -1,54 +1,16 @@ """ -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 django.core.exceptions import PermissionDenied -from django.http import Http404 -from django.utils.html import escape -from django.utils.safestring import mark_safe +from django.http import Http404, HttpResponse from django.views.decorators.csrf import csrf_exempt 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.request import Request from rest_framework.settings import api_settings -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() +from rest_framework.utils.formatting import get_view_name, get_view_description class APIView(View): @@ -64,22 +26,21 @@ class APIView(View): @classmethod def as_view(cls, **initkwargs): """ - Override the default :meth:`as_view` to store an instance of the view - as an attribute on the callable function. This allows us to discover - information about the view when we do URL reverse lookups. + Store the original class on the view function. + + 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.cls_instance = cls(**initkwargs) + view.cls = cls return view @property 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 - if hasattr(self, method)] + return self._allowed_methods() @property def default_response_headers(self): @@ -90,43 +51,10 @@ class APIView(View): '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): return { - 'name': self.get_name(), - 'description': self.get_description(), + 'name': get_view_name(self.__class__), + 'description': get_view_description(self.__class__), 'renders': [renderer.media_type for renderer in self.renderer_classes], 'parses': [parser.media_type for parser in self.parser_classes], } @@ -140,7 +68,8 @@ class APIView(View): 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) @@ -327,6 +256,12 @@ class APIView(View): """ Returns the final response object. """ + # Make the error obvious if a proper response is not returned + assert isinstance(response, HttpResponse), ( + 'Expected a `Response` to be returned from the view, ' + 'but received a `%s`' % type(response) + ) + if isinstance(response, Response): if not getattr(request, 'accepted_renderer', None): neg = self.perform_content_negotiation(request, force=True) diff --git a/rest_framework/viewsets.py b/rest_framework/viewsets.py new file mode 100644 index 00000000..9133fd44 --- /dev/null +++ b/rest_framework/viewsets.py @@ -0,0 +1,109 @@ +""" +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 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, name_suffix=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. + """ + # 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) + + # 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=()) + + view.cls = cls + return view + + +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 |
