Merge branch 'master' into unauthenticated_response

Conflicts:
	docs/api-guide/authentication.md
This commit is contained in:
Tom Christie 2013-01-22 09:11:38 +00:00
commit b7ab2aee46
31 changed files with 757 additions and 106 deletions

View File

@ -81,6 +81,17 @@ To run the tests.
# Changelog # Changelog
### 2.1.16
**Date**: 14th Jan 2013
* Deprecate django.utils.simplejson in favor of Python 2.6's built-in json module.
* Bugfix: `auto_now`, `auto_now_add` and other `editable=False` fields now default to read-only.
* Bugfix: PK fields now only default to read-only if they are an AutoField or if `editable=False`.
* Bugfix: Validation errors instead of exceptions when serializers receive incorrect types.
* Bugfix: Validation errors instead of exceptions when related fields receive incorrect types.
* Bugfix: Handle ObjectDoesNotExist exception when serializing null reverse one-to-one
### 2.1.15 ### 2.1.15
**Date**: 3rd Jan 2013 **Date**: 3rd Jan 2013
@ -283,5 +294,4 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
[urlobject]: https://github.com/zacharyvoase/urlobject [urlobject]: https://github.com/zacharyvoase/urlobject
[markdown]: http://pypi.python.org/pypi/Markdown/ [markdown]: http://pypi.python.org/pypi/Markdown/
[pyyaml]: http://pypi.python.org/pypi/PyYAML [pyyaml]: http://pypi.python.org/pypi/PyYAML
[django-filter]: https://github.com/alex/django-filter [django-filter]: http://pypi.python.org/pypi/django-filter

View File

@ -60,7 +60,7 @@ Or, if you're using the `@api_view` decorator with function based views.
@api_view(['GET']) @api_view(['GET'])
@authentication_classes((SessionAuthentication, BasicAuthentication)) @authentication_classes((SessionAuthentication, BasicAuthentication))
@permissions_classes((IsAuthenticated,)) @permission_classes((IsAuthenticated,))
def example_view(request, format=None): def example_view(request, format=None):
content = { content = {
'user': unicode(request.user), # `django.contrib.auth.User` instance. 'user': unicode(request.user), # `django.contrib.auth.User` instance.
@ -81,6 +81,15 @@ The kind of response that will be used depends on the authentication scheme. Al
Note that when a request may successfully authenticate, but still be denied permission to perform the request, in which case a `403 Permission Denied` response will always be used, regardless of the authentication scheme. Note that when a request may successfully authenticate, but still be denied permission to perform the request, in which case a `403 Permission Denied` response will always be used, regardless of the authentication scheme.
## Apache mod_wsgi specific configuration
Note that if deploying to [Apache using mod_wsgi][mod_wsgi_official], the authorization header is not passed through to a WSGI application by default, as it is assumed that authentication will be handled by Apache, rather than at an application level.
If you are deploying to Apache, and using any non-session based authentication, you will need to explicitly configure mod_wsgi to pass the required headers through to the application. This can be done by specifying the `WSGIPassAuthorization` directive in the appropriate context and setting it to `'On'`.
# this can go in either server config, virtual host, directory or .htaccess
WSGIPassAuthorization On
--- ---
# API Reference # API Reference
@ -120,7 +129,7 @@ For clients to authenticate, the token key should be included in the `Authorizat
If successfully authenticated, `TokenAuthentication` provides the following credentials. If successfully authenticated, `TokenAuthentication` provides the following credentials.
* `request.user` will be a Django `User` instance. * `request.user` will be a Django `User` instance.
* `request.auth` will be a `rest_framework.tokenauth.models.BasicToken` instance. * `request.auth` will be a `rest_framework.authtoken.models.BasicToken` instance.
Unauthenticated responses that are denied permission will result in an `HTTP 401 Unauthorized` response with an appropriate WWW-Authenticate header. For example: Unauthenticated responses that are denied permission will result in an `HTTP 401 Unauthorized` response with an appropriate WWW-Authenticate header. For example:
@ -168,7 +177,7 @@ If successfully authenticated, `SessionAuthentication` provides the following cr
Unauthenticated responses that are denied permission will result in an `HTTP 403 Forbidden` response. Unauthenticated responses that are denied permission will result in an `HTTP 403 Forbidden` response.
--- If you're using an AJAX style API with SessionAuthentication, you'll need to make sure you include a valid CSRF token for any "unsafe" HTTP method calls, such as `PUT`, `POST` or `DELETE` requests. See the [Django CSRF documentation][csrf-ajax] for more details.
# Custom authentication # Custom authentication
@ -192,3 +201,5 @@ If the `.authentication_header()` method is not overridden, the authentication s
[oauth]: http://oauth.net/2/ [oauth]: http://oauth.net/2/
[permission]: permissions.md [permission]: permissions.md
[throttling]: throttling.md [throttling]: throttling.md
[csrf-ajax]: https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax
[mod_wsgi_official]: http://code.google.com/p/modwsgi/wiki/ConfigurationDirectives#WSGIPassAuthorization

View File

@ -97,6 +97,8 @@ You can also set the pagination style on a per-view basis, using the `ListAPIVie
paginate_by = 10 paginate_by = 10
paginate_by_param = 'page_size' paginate_by_param = 'page_size'
Note that using a `paginate_by` value of `None` will turn off pagination for the view.
For more complex requirements such as serialization that differs depending on the requested media type you can override the `.get_paginate_by()` and `.get_pagination_serializer_class()` methods. For more complex requirements such as serialization that differs depending on the requested media type you can override the `.get_paginate_by()` and `.get_pagination_serializer_class()` methods.
--- ---

View File

@ -14,6 +14,16 @@ REST framework includes a number of built in Parser classes, that allow you to a
The set of valid parsers for a view is always defined as a list of classes. When either `request.DATA` or `request.FILES` is accessed, REST framework will examine the `Content-Type` header on the incoming request, and determine which parser to use to parse the request content. The set of valid parsers for a view is always defined as a list of classes. When either `request.DATA` or `request.FILES` is accessed, REST framework will examine the `Content-Type` header on the incoming request, and determine which parser to use to parse the request content.
---
**Note**: When developing client applications always remember to make sure you're setting the `Content-Type` header when sending data in an HTTP request.
If you don't set the content type, most clients will default to using `'application/x-www-form-urlencoded'`, which may not be what you wanted.
As an example, if you are sending `json` encoded data using jQuery with the [.ajax() method][jquery-ajax], you should make sure to include the `contentType: 'application/json'` setting.
---
## Setting the parsers ## Setting the parsers
The default set of parsers may be set globally, using the `DEFAULT_PARSER_CLASSES` setting. For example, the following settings would allow requests with `YAML` content. The default set of parsers may be set globally, using the `DEFAULT_PARSER_CLASSES` setting. For example, the following settings would allow requests with `YAML` content.
@ -167,8 +177,9 @@ The following third party packages are also available.
## MessagePack ## MessagePack
[MessagePack][messagepack] is a fast, efficient binary serialization format. [Juan Riaza][juanriaza] maintains the `djangorestframework-msgpack` package which provides MessagePack renderer and parser support for REST framework. Documentation is [available here][djangorestframework-msgpack]. [MessagePack][messagepack] is a fast, efficient binary serialization format. [Juan Riaza][juanriaza] maintains the [djangorestframework-msgpack][djangorestframework-msgpack] package which provides MessagePack renderer and parser support for REST framework.
[jquery-ajax]: http://api.jquery.com/jQuery.ajax/
[cite]: https://groups.google.com/d/topic/django-developers/dxI4qVzrBY4/discussion [cite]: https://groups.google.com/d/topic/django-developers/dxI4qVzrBY4/discussion
[messagepack]: https://github.com/juanriaza/django-rest-framework-msgpack [messagepack]: https://github.com/juanriaza/django-rest-framework-msgpack
[juanriaza]: https://github.com/juanriaza [juanriaza]: https://github.com/juanriaza

View File

@ -279,7 +279,11 @@ The following third party packages are also available.
## MessagePack ## MessagePack
[MessagePack][messagepack] is a fast, efficient binary serialization format. [Juan Riaza][juanriaza] maintains the `djangorestframework-msgpack` package which provides MessagePack renderer and parser support for REST framework. Documentation is [available here][djangorestframework-msgpack]. [MessagePack][messagepack] is a fast, efficient binary serialization format. [Juan Riaza][juanriaza] maintains the [djangorestframework-msgpack][djangorestframework-msgpack] package which provides MessagePack renderer and parser support for REST framework.
## CSV
Comma-separated values are a plain-text tabular data format, that can be easily imported into spreadsheet applications. [Mjumbe Poe][mjumbewu] maintains the [djangorestframework-csv][djangorestframework-csv] package which provides CSV renderer support for REST framework.
[cite]: https://docs.djangoproject.com/en/dev/ref/template-response/#the-rendering-process [cite]: https://docs.djangoproject.com/en/dev/ref/template-response/#the-rendering-process
[conneg]: content-negotiation.md [conneg]: content-negotiation.md
@ -290,6 +294,8 @@ The following third party packages are also available.
[application/vnd.github+json]: http://developer.github.com/v3/media/ [application/vnd.github+json]: http://developer.github.com/v3/media/
[application/vnd.collection+json]: http://www.amundsen.com/media-types/collection/ [application/vnd.collection+json]: http://www.amundsen.com/media-types/collection/
[django-error-views]: https://docs.djangoproject.com/en/dev/topics/http/views/#customizing-error-views [django-error-views]: https://docs.djangoproject.com/en/dev/topics/http/views/#customizing-error-views
[messagepack]: https://github.com/juanriaza/django-rest-framework-msgpack [messagepack]: http://msgpack.org/
[juanriaza]: https://github.com/juanriaza [juanriaza]: https://github.com/juanriaza
[djangorestframework-msgpack]: https://github.com/juanriaza/django-rest-framework-msgpack [mjumbewu]: https://github.com/mjumbewu
[djangorestframework-msgpack]: https://github.com/juanriaza/django-rest-framework-msgpack
[djangorestframework-csv]: https://github.com/mjumbewu/django-rest-framework-csv

View File

@ -65,7 +65,7 @@ Default:
( (
'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.UserBasicAuthentication' 'rest_framework.authentication.BasicAuthentication'
) )
## DEFAULT_PERMISSION_CLASSES ## DEFAULT_PERMISSION_CLASSES

View File

@ -132,9 +132,9 @@ Run the tests:
## Support ## Support
For support please see the [REST framework discussion group][group], or try the `#restframework` channel on `irc.freenode.net`. For support please see the [REST framework discussion group][group], try the `#restframework` channel on `irc.freenode.net`, or raise a question on [Stack Overflow][stack-overflow], making sure to include the ['django-rest-framework'][django-rest-framework-tag] tag.
Paid support is also available from [DabApps], and can include work on REST framework core, or support with building your REST framework API. Please contact [Tom Christie][email] if you'd like to discuss commercial support options. [Paid support is available][paid-support] from [DabApps][dabapps], and can include work on REST framework core, or support with building your REST framework API. Please [contact DabApps][contact-dabapps] if you'd like to discuss commercial support options.
## License ## License
@ -166,7 +166,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
[urlobject]: https://github.com/zacharyvoase/urlobject [urlobject]: https://github.com/zacharyvoase/urlobject
[markdown]: http://pypi.python.org/pypi/Markdown/ [markdown]: http://pypi.python.org/pypi/Markdown/
[yaml]: http://pypi.python.org/pypi/PyYAML [yaml]: http://pypi.python.org/pypi/PyYAML
[django-filter]: https://github.com/alex/django-filter [django-filter]: http://pypi.python.org/pypi/django-filter
[0.4]: https://github.com/tomchristie/django-rest-framework/tree/0.4.X [0.4]: https://github.com/tomchristie/django-rest-framework/tree/0.4.X
[image]: img/quickstart.png [image]: img/quickstart.png
[sandbox]: http://restframework.herokuapp.com/ [sandbox]: http://restframework.herokuapp.com/
@ -209,5 +209,9 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
[credits]: topics/credits.md [credits]: topics/credits.md
[group]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework [group]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework
[DabApps]: http://dabapps.com [stack-overflow]: http://stackoverflow.com/
[email]: mailto:tom@tomchristie.com [django-rest-framework-tag]: http://stackoverflow.com/questions/tagged/django-rest-framework
[django-tag]: http://stackoverflow.com/questions/tagged/django
[paid-support]: http://dabapps.com/services/build/api-development/
[dabapps]: http://dabapps.com
[contact-dabapps]: http://dabapps.com/contact/

View File

@ -88,6 +88,13 @@ The following people have helped make REST framework great.
* Juan Riaza - [juanriaza] * Juan Riaza - [juanriaza]
* Michael Mior - [michaelmior] * Michael Mior - [michaelmior]
* Marc Tamlyn - [mjtamlyn] * Marc Tamlyn - [mjtamlyn]
* Richard Wackerbarth - [wackerbarth]
* Johannes Spielmann - [shezi]
* James Cleveland - [radiosilence]
* Steve Gregory - [steve-gregory]
* Federico Capoano - [nemesisdesign]
* Bruno Renié - [brutasse]
* Kevin Stone - [kevinastone]
Many thanks to everyone who's contributed to the project. Many thanks to everyone who's contributed to the project.
@ -211,3 +218,10 @@ You can also contact [@_tomchristie][twitter] directly on twitter.
[juanriaza]: https://github.com/juanriaza [juanriaza]: https://github.com/juanriaza
[michaelmior]: https://github.com/michaelmior [michaelmior]: https://github.com/michaelmior
[mjtamlyn]: https://github.com/mjtamlyn [mjtamlyn]: https://github.com/mjtamlyn
[wackerbarth]: https://github.com/wackerbarth
[shezi]: https://github.com/shezi
[radiosilence]: https://github.com/radiosilence
[steve-gregory]: https://github.com/steve-gregory
[nemesisdesign]: https://github.com/nemesisdesign
[brutasse]: https://github.com/brutasse
[kevinastone]: https://github.com/kevinastone

View File

@ -18,9 +18,23 @@ Major version numbers (x.0.0) are reserved for project milestones. No major poi
### Master ### Master
* Deprecate django.utils.simplejson in favor of Python 2.6's built-in json module. * Support json encoding of timedelta objects.
* `format_suffix_patterns()` now supports `include` style URL patterns.
* Bugfix: Return proper validation errors when incorrect types supplied for relational fields.
* Bugfix: Support nullable FKs with `SlugRelatedField`.
### 2.1.16
**Date**: 14th Jan 2013
* Deprecate `django.utils.simplejson` in favor of Python 2.6's built-in json module.
* Bugfix: `auto_now`, `auto_now_add` and other `editable=False` fields now default to read-only.
* Bugfix: PK fields now only default to read-only if they are an AutoField or if `editable=False`.
* Bugfix: Validation errors instead of exceptions when serializers receive incorrect types. * Bugfix: Validation errors instead of exceptions when serializers receive incorrect types.
* Bugfix: Validation errors instead of exceptions when related fields receive incorrect types. * Bugfix: Validation errors instead of exceptions when related fields receive incorrect types.
* Bugfix: Handle ObjectDoesNotExist exception when serializing null reverse one-to-one
**Note**: Prior to 2.1.16, The Decimals would render in JSON using floating point if `simplejson` was installed, but otherwise render using string notation. Now that use of `simplejson` has been deprecated, Decimals will consistently render using string notation. See [#582] for more details.
### 2.1.15 ### 2.1.15
@ -314,3 +328,4 @@ This change will not affect user code, so long as it's following the recommended
[staticfiles13]: https://docs.djangoproject.com/en/1.3/howto/static-files/#with-a-template-tag [staticfiles13]: https://docs.djangoproject.com/en/1.3/howto/static-files/#with-a-template-tag
[2.1.0-notes]: https://groups.google.com/d/topic/django-rest-framework/Vv2M0CMY9bg/discussion [2.1.0-notes]: https://groups.google.com/d/topic/django-rest-framework/Vv2M0CMY9bg/discussion
[announcement]: rest-framework-2-announcement.md [announcement]: rest-framework-2-announcement.md
[#582]: https://github.com/tomchristie/django-rest-framework/issues/582

View File

@ -8,7 +8,7 @@ The tutorial is fairly in-depth, so you should probably get a cookie and a cup o
--- ---
**Note**: The final code for this tutorial is available in the [tomchristie/rest-framework-tutorial][repo] repository on GitHub. There is also a sandbox version for testing, [available here][sandbox]. **Note**: The code for this tutorial is available in the [tomchristie/rest-framework-tutorial][repo] repository on GitHub. As pieces of code are introduced, they are committed to this repository. The completed implementation is also online as a sandbox version for testing, [available here][sandbox].
--- ---
@ -60,7 +60,7 @@ We'll also need to add our new `snippets` app and the `rest_framework` app to `I
INSTALLED_APPS = ( INSTALLED_APPS = (
... ...
'rest_framework', 'rest_framework',
'snippets' 'snippets',
) )
We also need to wire up the root urlconf, in the `tutorial/urls.py` file, to include our snippet app's URLs. We also need to wire up the root urlconf, in the `tutorial/urls.py` file, to include our snippet app's URLs.
@ -73,14 +73,15 @@ Okay, we're ready to roll.
## Creating a model to work with ## Creating a model to work with
For the purposes of this tutorial we're going to start by creating a simple `Snippet` model that is used to store code snippets. Go ahead and edit the `snippets` app's `models.py` file. For the purposes of this tutorial we're going to start by creating a simple `Snippet` model that is used to store code snippets. Go ahead and edit the `snippets` app's `models.py` file. Note: Good programming practices include comments. Although you will find them in our repository version of this tutorial code, we have omitted them here to focus on the code itself.
from django.db import models from django.db import models
from pygments.lexers import get_all_lexers from pygments.lexers import get_all_lexers
from pygments.styles import get_all_styles from pygments.styles import get_all_styles
LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in get_all_lexers()]) LEXERS = [item for item in get_all_lexers() if item[1]]
STYLE_CHOICES = sorted((item, item) for item in list(get_all_styles())) LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS])
STYLE_CHOICES = sorted((item, item) for item in get_all_styles())
class Snippet(models.Model): class Snippet(models.Model):
@ -108,7 +109,7 @@ The first thing we need to get started on our Web API is provide a way of serial
from django.forms import widgets from django.forms import widgets
from rest_framework import serializers from rest_framework import serializers
from snippets import models from snippets.models import Snippet
class SnippetSerializer(serializers.Serializer): class SnippetSerializer(serializers.Serializer):
@ -137,7 +138,7 @@ The first thing we need to get started on our Web API is provide a way of serial
return instance return instance
# Create new instance # Create new instance
return models.Snippet(**attrs) return Snippet(**attrs)
The first part of serializer class defines the fields that get serialized/deserialized. The `restore_object` method defines how fully fledged instances get created when deserializing data. The first part of serializer class defines the fields that get serialized/deserialized. The `restore_object` method defines how fully fledged instances get created when deserializing data.
@ -202,8 +203,6 @@ Open the file `snippets/serializers.py` again, and edit the `SnippetSerializer`
model = Snippet model = Snippet
fields = ('id', 'title', 'code', 'linenos', 'language', 'style') fields = ('id', 'title', 'code', 'linenos', 'language', 'style')
## Writing regular Django views using our Serializer ## Writing regular Django views using our Serializer
Let's see how we can write some API views using our new Serializer class. Let's see how we can write some API views using our new Serializer class.
@ -229,7 +228,6 @@ Edit the `snippet/views.py` file, and add the following.
kwargs['content_type'] = 'application/json' kwargs['content_type'] = 'application/json'
super(JSONResponse, self).__init__(content, **kwargs) super(JSONResponse, self).__init__(content, **kwargs)
The root of our API is going to be a view that supports listing all the existing snippets, or creating a new snippet. The root of our API is going to be a view that supports listing all the existing snippets, or creating a new snippet.
@csrf_exempt @csrf_exempt
@ -288,16 +286,45 @@ Finally we need to wire these views up. Create the `snippets/urls.py` file:
urlpatterns = patterns('snippets.views', urlpatterns = patterns('snippets.views',
url(r'^snippets/$', 'snippet_list'), url(r'^snippets/$', 'snippet_list'),
url(r'^snippets/(?P<pk>[0-9]+)/$', 'snippet_detail') url(r'^snippets/(?P<pk>[0-9]+)/$', 'snippet_detail'),
) )
It's worth noting that there are a couple of edge cases we're not dealing with properly at the moment. If we send malformed `json`, or if a request is made with a method that the view doesn't handle, then we'll end up with a 500 "server error" response. Still, this'll do for now. It's worth noting that there are a couple of edge cases we're not dealing with properly at the moment. If we send malformed `json`, or if a request is made with a method that the view doesn't handle, then we'll end up with a 500 "server error" response. Still, this'll do for now.
## Testing our first attempt at a Web API ## Testing our first attempt at a Web API
**TODO: Describe using runserver and making example requests from console** Now we can start up a sample server that serves our snippets.
**TODO: Describe opening in a web browser and viewing json output** Quit out of the shell
quit()
and start up Django's development server
python manage.py runserver
Validating models...
0 errors found
Django version 1.4.3, using settings 'tutorial.settings'
Development server is running at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
In another terminal window, we can test the server.
We can get a list of all of the snippets (we only have one at the moment)
curl http://127.0.0.1:8000/snippets/
[{"id": 1, "title": "", "code": "print \"hello, world\"\n", "linenos": false, "language": "python", "style": "friendly"}]
or we can get a particular snippet by referencing its id
curl http://127.0.0.1:8000/snippets/1/
{"id": 1, "title": "", "code": "print \"hello, world\"\n", "linenos": false, "language": "python", "style": "friendly"}
Similarly, you can have the same json displayed by referencing these URLs from your favorite web browser.
## Where are we now ## Where are we now

View File

@ -31,7 +31,6 @@ These wrappers provide a few bits of functionality such as making sure you recei
The wrappers also provide behaviour such as returning `405 Method Not Allowed` responses when appropriate, and handling any `ParseError` exception that occurs when accessing `request.DATA` with malformed input. The wrappers also provide behaviour such as returning `405 Method Not Allowed` responses when appropriate, and handling any `ParseError` exception that occurs when accessing `request.DATA` with malformed input.
## Pulling it all together ## Pulling it all together
Okay, let's go ahead and start using these new components to write a few views. Okay, let's go ahead and start using these new components to write a few views.
@ -63,7 +62,6 @@ We don't need our `JSONResponse` class anymore, so go ahead and delete that. On
else: else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Our instance view is an improvement over the previous example. It's a little more concise, and the code now feels very similar to if we were working with the Forms API. We're also using named status codes, which makes the response meanings more obvious. Our instance view is an improvement over the previous example. It's a little more concise, and the code now feels very similar to if we were working with the Forms API. We're also using named status codes, which makes the response meanings more obvious.
Here is the view for an individual snippet. Here is the view for an individual snippet.
@ -117,7 +115,7 @@ Now update the `urls.py` file slightly, to append a set of `format_suffix_patter
urlpatterns = patterns('snippets.views', urlpatterns = patterns('snippets.views',
url(r'^snippets/$', 'snippet_list'), url(r'^snippets/$', 'snippet_list'),
url(r'^snippets/(?P<pk>[0-9]+)$', 'snippet_detail') url(r'^snippets/(?P<pk>[0-9]+)$', 'snippet_detail'),
) )
urlpatterns = format_suffix_patterns(urlpatterns) urlpatterns = format_suffix_patterns(urlpatterns)
@ -138,7 +136,6 @@ Because the API chooses a return format based on what the client asks for, it wi
See the [browsable api][browseable-api] topic for more information about the browsable API feature and how to customize it. See the [browsable api][browseable-api] topic for more information about the browsable API feature and how to customize it.
## What's next? ## What's next?
In [tutorial part 3][tut-3], we'll start using class based views, and see how generic views reduce the amount of code we need to write. In [tutorial part 3][tut-3], we'll start using class based views, and see how generic views reduce the amount of code we need to write.

View File

@ -70,7 +70,7 @@ We'll also need to refactor our URLconf slightly now we're using class based vie
urlpatterns = patterns('', urlpatterns = patterns('',
url(r'^snippets/$', views.SnippetList.as_view()), url(r'^snippets/$', views.SnippetList.as_view()),
url(r'^snippets/(?P<pk>[0-9]+)/$', views.SnippetDetail.as_view()) url(r'^snippets/(?P<pk>[0-9]+)/$', views.SnippetDetail.as_view()),
) )
urlpatterns = format_suffix_patterns(urlpatterns) urlpatterns = format_suffix_patterns(urlpatterns)

View File

@ -29,7 +29,7 @@ And now we can add a `.save()` method to our model class:
def save(self, *args, **kwargs): def save(self, *args, **kwargs):
""" """
Use the `pygments` library to create an highlighted HTML Use the `pygments` library to create a highlighted HTML
representation of the code snippet. representation of the code snippet.
""" """
lexer = get_lexer_by_name(self.language) lexer = get_lexer_by_name(self.language)
@ -54,6 +54,8 @@ You might also want to create a few different users, to use for testing the API.
Now that we've got some users to work with, we'd better add representations of those users to our API. Creating a new serializer is easy: Now that we've got some users to work with, we'd better add representations of those users to our API. Creating a new serializer is easy:
from django.contrib.auth.models import User
class UserSerializer(serializers.ModelSerializer): class UserSerializer(serializers.ModelSerializer):
snippets = serializers.ManyPrimaryKeyRelatedField() snippets = serializers.ManyPrimaryKeyRelatedField()
@ -77,7 +79,7 @@ We'll also add a couple of views. We'd like to just use read-only views for the
Finally we need to add those views into the API, by referencing them from the URL conf. Finally we need to add those views into the API, by referencing them from the URL conf.
url(r'^users/$', views.UserList.as_view()), url(r'^users/$', views.UserList.as_view()),
url(r'^users/(?P<pk>[0-9]+)/$', views.UserInstance.as_view()) url(r'^users/(?P<pk>[0-9]+)/$', views.UserInstance.as_view()),
## Associating Snippets with Users ## Associating Snippets with Users
@ -134,7 +136,7 @@ And, at the end of the file, add a pattern to include the login and logout views
urlpatterns += patterns('', urlpatterns += patterns('',
url(r'^api-auth/', include('rest_framework.urls', url(r'^api-auth/', include('rest_framework.urls',
namespace='rest_framework')) namespace='rest_framework')),
) )
The `r'^api-auth/'` part of pattern can actually be whatever URL you want to use. The only restriction is that the included urls must use the `'rest_framework'` namespace. The `r'^api-auth/'` part of pattern can actually be whatever URL you want to use. The only restriction is that the included urls must use the `'rest_framework'` namespace.
@ -188,4 +190,4 @@ We've now got a fairly fine-grained set of permissions on our Web API, and end p
In [part 5][tut-5] of the tutorial we'll look at how we can tie everything together by creating an HTML endpoint for our hightlighted snippets, and improve the cohesion of our API by using hyperlinking for the relationships within the system. In [part 5][tut-5] of the tutorial we'll look at how we can tie everything together by creating an HTML endpoint for our hightlighted snippets, and improve the cohesion of our API by using hyperlinking for the relationships within the system.
[tut-5]: 5-relationships-and-hyperlinked-apis.md [tut-5]: 5-relationships-and-hyperlinked-apis.md

View File

@ -15,8 +15,8 @@ Right now we have endpoints for 'snippets' and 'users', but we don't have a sing
@api_view(('GET',)) @api_view(('GET',))
def api_root(request, format=None): def api_root(request, format=None):
return Response({ return Response({
'users': reverse('user-list', request=request), 'users': reverse('user-list', request=request, format=format),
'snippets': reverse('snippet-list', request=request) 'snippets': reverse('snippet-list', request=request, format=format)
}) })
Notice that we're using REST framework's `reverse` function in order to return fully-qualified URLs. Notice that we're using REST framework's `reverse` function in order to return fully-qualified URLs.
@ -116,7 +116,7 @@ After adding all those names into our URLconf, our final `'urls.py'` file should
url(r'^snippets/(?P<pk>[0-9]+)/$', url(r'^snippets/(?P<pk>[0-9]+)/$',
views.SnippetDetail.as_view(), views.SnippetDetail.as_view(),
name='snippet-detail'), name='snippet-detail'),
url(r'^snippets/(?P<pk>[0-9]+)/highlight/$' url(r'^snippets/(?P<pk>[0-9]+)/highlight/$',
views.SnippetHighlight.as_view(), views.SnippetHighlight.as_view(),
name='snippet-highlight'), name='snippet-highlight'),
url(r'^users/$', url(r'^users/$',
@ -130,7 +130,7 @@ After adding all those names into our URLconf, our final `'urls.py'` file should
# Login and logout views for the browsable API # Login and logout views for the browsable API
urlpatterns += patterns('', urlpatterns += patterns('',
url(r'^api-auth/', include('rest_framework.urls', url(r'^api-auth/', include('rest_framework.urls',
namespace='rest_framework')) namespace='rest_framework')),
) )
## Adding pagination ## Adding pagination

View File

@ -1,3 +1,3 @@
__version__ = '2.1.15' __version__ = '2.1.16'
VERSION = __version__ # synonym VERSION = __version__ # synonym

View File

@ -12,10 +12,11 @@ class ObtainAuthToken(APIView):
permission_classes = () permission_classes = ()
parser_classes = (parsers.FormParser, parsers.MultiPartParser, parsers.JSONParser,) parser_classes = (parsers.FormParser, parsers.MultiPartParser, parsers.JSONParser,)
renderer_classes = (renderers.JSONRenderer,) renderer_classes = (renderers.JSONRenderer,)
serializer_class = AuthTokenSerializer
model = Token model = Token
def post(self, request): def post(self, request):
serializer = AuthTokenSerializer(data=request.DATA) serializer = self.serializer_class(data=request.DATA)
if serializer.is_valid(): if serializer.is_valid():
token, created = Token.objects.get_or_create(user=serializer.object['user']) token, created = Token.objects.get_or_create(user=serializer.object['user'])
return Response({'token': token.key}) return Response({'token': token.key})

View File

@ -1,4 +1,5 @@
from rest_framework.views import APIView from rest_framework.views import APIView
import types
def api_view(http_method_names): def api_view(http_method_names):
@ -23,6 +24,14 @@ def api_view(http_method_names):
# pass # pass
# WrappedAPIView.__doc__ = func.doc <--- Not possible to do this # WrappedAPIView.__doc__ = func.doc <--- Not possible to do this
# api_view applied without (method_names)
assert not(isinstance(http_method_names, types.FunctionType)), \
'@api_view missing list of allowed HTTP methods'
# api_view applied with eg. string instead of list of strings
assert isinstance(http_method_names, (list, tuple)), \
'@api_view expected a list of strings, recieved %s' % type(http_method_names).__name__
allowed_methods = set(http_method_names) | set(('options',)) allowed_methods = set(http_method_names) | set(('options',))
WrappedAPIView.http_method_names = [method.lower() for method in allowed_methods] WrappedAPIView.http_method_names = [method.lower() for method in allowed_methods]

View File

@ -101,7 +101,13 @@ class RelatedField(WritableField):
### Regular serializer stuff... ### Regular serializer stuff...
def field_to_native(self, obj, field_name): def field_to_native(self, obj, field_name):
value = getattr(obj, self.source or field_name) try:
value = getattr(obj, self.source or field_name)
except ObjectDoesNotExist:
return None
if value is None:
return None
return self.to_native(value) return self.to_native(value)
def field_from_native(self, data, files, field_name, into): def field_from_native(self, data, files, field_name, into):
@ -171,7 +177,7 @@ class PrimaryKeyRelatedField(RelatedField):
default_error_messages = { default_error_messages = {
'does_not_exist': _("Invalid pk '%s' - object does not exist."), 'does_not_exist': _("Invalid pk '%s' - object does not exist."),
'invalid': _('Invalid value.'), 'incorrect_type': _('Incorrect type. Expected pk value, received %s.'),
} }
# TODO: Remove these field hacks... # TODO: Remove these field hacks...
@ -202,7 +208,8 @@ class PrimaryKeyRelatedField(RelatedField):
msg = self.error_messages['does_not_exist'] % smart_unicode(data) msg = self.error_messages['does_not_exist'] % smart_unicode(data)
raise ValidationError(msg) raise ValidationError(msg)
except (TypeError, ValueError): except (TypeError, ValueError):
msg = self.error_messages['invalid'] received = type(data).__name__
msg = self.error_messages['incorrect_type'] % received
raise ValidationError(msg) raise ValidationError(msg)
def field_to_native(self, obj, field_name): def field_to_native(self, obj, field_name):
@ -211,7 +218,10 @@ class PrimaryKeyRelatedField(RelatedField):
pk = obj.serializable_value(self.source or field_name) pk = obj.serializable_value(self.source or field_name)
except AttributeError: except AttributeError:
# RelatedObject (reverse relationship) # RelatedObject (reverse relationship)
obj = getattr(obj, self.source or field_name) try:
obj = getattr(obj, self.source or field_name)
except ObjectDoesNotExist:
return None
return self.to_native(obj.pk) return self.to_native(obj.pk)
# Forward relationship # Forward relationship
return self.to_native(pk) return self.to_native(pk)
@ -226,7 +236,7 @@ class ManyPrimaryKeyRelatedField(ManyRelatedField):
default_error_messages = { default_error_messages = {
'does_not_exist': _("Invalid pk '%s' - object does not exist."), 'does_not_exist': _("Invalid pk '%s' - object does not exist."),
'invalid': _('Invalid value.'), 'incorrect_type': _('Incorrect type. Expected pk value, received %s.'),
} }
def prepare_value(self, obj): def prepare_value(self, obj):
@ -266,7 +276,8 @@ class ManyPrimaryKeyRelatedField(ManyRelatedField):
msg = self.error_messages['does_not_exist'] % smart_unicode(data) msg = self.error_messages['does_not_exist'] % smart_unicode(data)
raise ValidationError(msg) raise ValidationError(msg)
except (TypeError, ValueError): except (TypeError, ValueError):
msg = self.error_messages['invalid'] received = type(data).__name__
msg = self.error_messages['incorrect_type'] % received
raise ValidationError(msg) raise ValidationError(msg)
### Slug relationships ### Slug relationships
@ -324,7 +335,7 @@ class HyperlinkedRelatedField(RelatedField):
'incorrect_match': _('Invalid hyperlink - Incorrect URL match'), 'incorrect_match': _('Invalid hyperlink - Incorrect URL match'),
'configuration_error': _('Invalid hyperlink due to configuration error'), 'configuration_error': _('Invalid hyperlink due to configuration error'),
'does_not_exist': _("Invalid hyperlink - object does not exist."), 'does_not_exist': _("Invalid hyperlink - object does not exist."),
'invalid': _('Invalid value.'), 'incorrect_type': _('Incorrect type. Expected url string, received %s.'),
} }
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
@ -367,13 +378,13 @@ class HyperlinkedRelatedField(RelatedField):
kwargs = {self.slug_url_kwarg: slug} kwargs = {self.slug_url_kwarg: slug}
try: try:
return reverse(self.view_name, kwargs=kwargs, request=request, format=format) return reverse(view_name, kwargs=kwargs, request=request, format=format)
except: except:
pass pass
kwargs = {self.pk_url_kwarg: obj.pk, self.slug_url_kwarg: slug} kwargs = {self.pk_url_kwarg: obj.pk, self.slug_url_kwarg: slug}
try: try:
return reverse(self.view_name, kwargs=kwargs, request=request, format=format) return reverse(view_name, kwargs=kwargs, request=request, format=format)
except: except:
pass pass
@ -388,8 +399,8 @@ class HyperlinkedRelatedField(RelatedField):
try: try:
http_prefix = value.startswith('http:') or value.startswith('https:') http_prefix = value.startswith('http:') or value.startswith('https:')
except AttributeError: except AttributeError:
msg = self.error_messages['invalid'] msg = self.error_messages['incorrect_type']
raise ValidationError(msg) raise ValidationError(msg % type(value).__name__)
if http_prefix: if http_prefix:
# If needed convert absolute URLs to relative path # If needed convert absolute URLs to relative path
@ -425,8 +436,8 @@ class HyperlinkedRelatedField(RelatedField):
except ObjectDoesNotExist: except ObjectDoesNotExist:
raise ValidationError(self.error_messages['does_not_exist']) raise ValidationError(self.error_messages['does_not_exist'])
except (TypeError, ValueError): except (TypeError, ValueError):
msg = self.error_messages['invalid'] msg = self.error_messages['incorrect_type']
raise ValidationError(msg) raise ValidationError(msg % type(value).__name__)
return obj return obj
@ -490,13 +501,13 @@ class HyperlinkedIdentityField(Field):
kwargs = {self.slug_url_kwarg: slug} kwargs = {self.slug_url_kwarg: slug}
try: try:
return reverse(self.view_name, kwargs=kwargs, request=request, format=format) return reverse(view_name, kwargs=kwargs, request=request, format=format)
except: except:
pass pass
kwargs = {self.pk_url_kwarg: obj.pk, self.slug_url_kwarg: slug} kwargs = {self.pk_url_kwarg: obj.pk, self.slug_url_kwarg: slug}
try: try:
return reverse(self.view_name, kwargs=kwargs, request=request, format=format) return reverse(view_name, kwargs=kwargs, request=request, format=format)
except: except:
pass pass

View File

@ -298,15 +298,18 @@ class BaseSerializer(Field):
Override default so that we can apply ModelSerializer as a nested Override default so that we can apply ModelSerializer as a nested
field to relationships. field to relationships.
""" """
if self.source: try:
for component in self.source.split('.'): if self.source:
obj = getattr(obj, component) for component in self.source.split('.'):
obj = getattr(obj, component)
if is_simple_callable(obj):
obj = obj()
else:
obj = getattr(obj, field_name)
if is_simple_callable(obj): if is_simple_callable(obj):
obj = obj() obj = obj()
else: except ObjectDoesNotExist:
obj = getattr(obj, field_name) return None
if is_simple_callable(obj):
obj = value()
# If the object has an "all" method, assume it's a relationship # If the object has an "all" method, assume it's a relationship
if is_simple_callable(getattr(obj, 'all', None)): if is_simple_callable(getattr(obj, 'all', None)):
@ -412,7 +415,7 @@ class ModelSerializer(Serializer):
""" """
Returns a default instance of the pk field. Returns a default instance of the pk field.
""" """
return Field() return self.get_field(model_field)
def get_nested_field(self, model_field): def get_nested_field(self, model_field):
""" """
@ -430,7 +433,7 @@ class ModelSerializer(Serializer):
# TODO: filter queryset using: # TODO: filter queryset using:
# .using(db).complex_filter(self.rel.limit_choices_to) # .using(db).complex_filter(self.rel.limit_choices_to)
kwargs = { kwargs = {
'null': model_field.null, 'null': model_field.null or model_field.blank,
'queryset': model_field.rel.to._default_manager 'queryset': model_field.rel.to._default_manager
} }
@ -449,6 +452,9 @@ class ModelSerializer(Serializer):
if model_field.null or model_field.blank: if model_field.null or model_field.blank:
kwargs['required'] = False kwargs['required'] = False
if isinstance(model_field, models.AutoField) or not model_field.editable:
kwargs['read_only'] = True
if model_field.has_default(): if model_field.has_default():
kwargs['required'] = False kwargs['required'] = False
kwargs['default'] = model_field.get_default() kwargs['default'] = model_field.get_default()
@ -462,6 +468,7 @@ class ModelSerializer(Serializer):
return ChoiceField(**kwargs) return ChoiceField(**kwargs)
field_mapping = { field_mapping = {
models.AutoField: IntegerField,
models.FloatField: FloatField, models.FloatField: FloatField,
models.IntegerField: IntegerField, models.IntegerField: IntegerField,
models.PositiveIntegerField: IntegerField, models.PositiveIntegerField: IntegerField,

View File

@ -112,7 +112,7 @@
<div class="request-info"> <div class="request-info">
<pre class="prettyprint"><b>{{ request.method }}</b> {{ request.get_full_path }}</pre> <pre class="prettyprint"><b>{{ request.method }}</b> {{ request.get_full_path }}</pre>
<div> </div>
<div class="response-info"> <div class="response-info">
<pre class="prettyprint"><div class="meta nocode"><b>HTTP {{ response.status_code }} {{ response.status_text }}</b>{% autoescape off %} <pre class="prettyprint"><div class="meta nocode"><b>HTTP {{ response.status_code }} {{ response.status_text }}</b>{% autoescape off %}
{% for key, val in response.items %}<b>{{ key }}:</b> <span class="lit">{{ val|urlize_quoted_links }}</span> {% for key, val in response.items %}<b>{{ key }}:</b> <span class="lit">{{ val|urlize_quoted_links }}</span>

View File

@ -1,5 +1,4 @@
from django.test import TestCase from django.test import TestCase
from django.test.client import RequestFactory
from rest_framework import status from rest_framework import status
from rest_framework.response import Response from rest_framework.response import Response
from rest_framework.renderers import JSONRenderer from rest_framework.renderers import JSONRenderer
@ -29,13 +28,27 @@ class DecoratorTestCase(TestCase):
response.request = request response.request = request
return APIView.finalize_response(self, request, response, *args, **kwargs) return APIView.finalize_response(self, request, response, *args, **kwargs)
def test_wrap_view(self): def test_api_view_incorrect(self):
"""
If @api_view is not applied correct, we should raise an assertion.
"""
@api_view(['GET']) @api_view
def view(request): def view(request):
return Response({}) return Response()
self.assertTrue(isinstance(view.cls_instance, APIView)) request = self.factory.get('/')
self.assertRaises(AssertionError, view, request)
def test_api_view_incorrect_arguments(self):
"""
If @api_view is missing arguments, we should raise an assertion.
"""
with self.assertRaises(AssertionError):
@api_view('GET')
def view(request):
return Response()
def test_calling_method(self): def test_calling_method(self):

View File

@ -0,0 +1,49 @@
"""
General serializer field tests.
"""
from django.db import models
from django.test import TestCase
from rest_framework import serializers
class TimestampedModel(models.Model):
added = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class CharPrimaryKeyModel(models.Model):
id = models.CharField(max_length=20, primary_key=True)
class TimestampedModelSerializer(serializers.ModelSerializer):
class Meta:
model = TimestampedModel
class CharPrimaryKeyModelSerializer(serializers.ModelSerializer):
class Meta:
model = CharPrimaryKeyModel
class ReadOnlyFieldTests(TestCase):
def test_auto_now_fields_read_only(self):
"""
auto_now and auto_now_add fields should be read_only by default.
"""
serializer = TimestampedModelSerializer()
self.assertEquals(serializer.fields['added'].read_only, True)
def test_auto_pk_fields_read_only(self):
"""
AutoField fields should be read_only by default.
"""
serializer = TimestampedModelSerializer()
self.assertEquals(serializer.fields['id'].read_only, True)
def test_non_auto_pk_fields_not_read_only(self):
"""
PK fields other than AutoField fields should not be read_only by default.
"""
serializer = CharPrimaryKeyModelSerializer()
self.assertEquals(serializer.fields['id'].read_only, False)

View File

@ -205,3 +205,14 @@ class NullableForeignKeySource(RESTFrameworkModel):
name = models.CharField(max_length=100) name = models.CharField(max_length=100)
target = models.ForeignKey(ForeignKeyTarget, null=True, blank=True, target = models.ForeignKey(ForeignKeyTarget, null=True, blank=True,
related_name='nullable_sources') related_name='nullable_sources')
# OneToOne
class OneToOneTarget(RESTFrameworkModel):
name = models.CharField(max_length=100)
class NullableOneToOneSource(RESTFrameworkModel):
name = models.CharField(max_length=100)
target = models.OneToOneField(OneToOneTarget, null=True, blank=True,
related_name='nullable_source')

View File

@ -181,10 +181,10 @@ class UnitTestPagination(TestCase):
""" """
Ensure context gets passed through to the object serializer. Ensure context gets passed through to the object serializer.
""" """
serializer = PassOnContextPaginationSerializer(self.first_page) serializer = PassOnContextPaginationSerializer(self.first_page, context={'foo': 'bar'})
serializer.data serializer.data
results = serializer.fields[serializer.results_field] results = serializer.fields[serializer.results_field]
self.assertTrue(serializer.context is results.context) self.assertEquals(serializer.context, results.context)
class TestUnpaginated(TestCase): class TestUnpaginated(TestCase):

View File

@ -1,8 +1,8 @@
from django.db import models
from django.test import TestCase from django.test import TestCase
from rest_framework import serializers from rest_framework import serializers
from rest_framework.compat import patterns, url from rest_framework.compat import patterns, url
from rest_framework.tests.models import ManyToManyTarget, ManyToManySource, ForeignKeyTarget, ForeignKeySource from rest_framework.tests.models import ManyToManyTarget, ManyToManySource, ForeignKeyTarget, ForeignKeySource, NullableForeignKeySource, OneToOneTarget, NullableOneToOneSource
def dummy_view(request, pk): def dummy_view(request, pk):
pass pass
@ -13,8 +13,11 @@ urlpatterns = patterns('',
url(r'^foreignkeysource/(?P<pk>[0-9]+)/$', dummy_view, name='foreignkeysource-detail'), url(r'^foreignkeysource/(?P<pk>[0-9]+)/$', dummy_view, name='foreignkeysource-detail'),
url(r'^foreignkeytarget/(?P<pk>[0-9]+)/$', dummy_view, name='foreignkeytarget-detail'), url(r'^foreignkeytarget/(?P<pk>[0-9]+)/$', dummy_view, name='foreignkeytarget-detail'),
url(r'^nullableforeignkeysource/(?P<pk>[0-9]+)/$', dummy_view, name='nullableforeignkeysource-detail'), url(r'^nullableforeignkeysource/(?P<pk>[0-9]+)/$', dummy_view, name='nullableforeignkeysource-detail'),
url(r'^onetoonetarget/(?P<pk>[0-9]+)/$', dummy_view, name='onetoonetarget-detail'),
url(r'^nullableonetoonesource/(?P<pk>[0-9]+)/$', dummy_view, name='nullableonetoonesource-detail'),
) )
class ManyToManyTargetSerializer(serializers.HyperlinkedModelSerializer): class ManyToManyTargetSerializer(serializers.HyperlinkedModelSerializer):
sources = serializers.ManyHyperlinkedRelatedField(view_name='manytomanysource-detail') sources = serializers.ManyHyperlinkedRelatedField(view_name='manytomanysource-detail')
@ -40,18 +43,19 @@ class ForeignKeySourceSerializer(serializers.HyperlinkedModelSerializer):
# Nullable ForeignKey # Nullable ForeignKey
class NullableForeignKeySource(models.Model):
name = models.CharField(max_length=100)
target = models.ForeignKey(ForeignKeyTarget, null=True, blank=True,
related_name='nullable_sources')
class NullableForeignKeySourceSerializer(serializers.HyperlinkedModelSerializer): class NullableForeignKeySourceSerializer(serializers.HyperlinkedModelSerializer):
class Meta: class Meta:
model = NullableForeignKeySource model = NullableForeignKeySource
# OneToOne
class NullableOneToOneTargetSerializer(serializers.HyperlinkedModelSerializer):
nullable_source = serializers.HyperlinkedRelatedField(view_name='nullableonetoonesource-detail')
class Meta:
model = OneToOneTarget
# TODO: Add test that .data cannot be accessed prior to .is_valid # TODO: Add test that .data cannot be accessed prior to .is_valid
class HyperlinkedManyToManyTests(TestCase): class HyperlinkedManyToManyTests(TestCase):
@ -211,6 +215,13 @@ class HyperlinkedForeignKeyTests(TestCase):
] ]
self.assertEquals(serializer.data, expected) self.assertEquals(serializer.data, expected)
def test_foreign_key_update_incorrect_type(self):
data = {'url': '/foreignkeysource/1/', 'name': u'source-1', 'target': 2}
instance = ForeignKeySource.objects.get(pk=1)
serializer = ForeignKeySourceSerializer(instance, data=data)
self.assertFalse(serializer.is_valid())
self.assertEquals(serializer.errors, {'target': [u'Incorrect type. Expected url string, received int.']})
def test_reverse_foreign_key_update(self): def test_reverse_foreign_key_update(self):
data = {'url': '/foreignkeytarget/2/', 'name': u'target-2', 'sources': ['/foreignkeysource/1/', '/foreignkeysource/3/']} data = {'url': '/foreignkeytarget/2/', 'name': u'target-2', 'sources': ['/foreignkeysource/1/', '/foreignkeysource/3/']}
instance = ForeignKeyTarget.objects.get(pk=2) instance = ForeignKeyTarget.objects.get(pk=2)
@ -223,7 +234,7 @@ class HyperlinkedForeignKeyTests(TestCase):
expected = [ expected = [
{'url': '/foreignkeytarget/1/', 'name': u'target-1', 'sources': ['/foreignkeysource/1/', '/foreignkeysource/2/', '/foreignkeysource/3/']}, {'url': '/foreignkeytarget/1/', 'name': u'target-1', 'sources': ['/foreignkeysource/1/', '/foreignkeysource/2/', '/foreignkeysource/3/']},
{'url': '/foreignkeytarget/2/', 'name': u'target-2', 'sources': []}, {'url': '/foreignkeytarget/2/', 'name': u'target-2', 'sources': []},
] ]
self.assertEquals(new_serializer.data, expected) self.assertEquals(new_serializer.data, expected)
serializer.save() serializer.save()
@ -409,3 +420,24 @@ class HyperlinkedNullableForeignKeyTests(TestCase):
# {'id': 2, 'name': u'target-2', 'sources': []}, # {'id': 2, 'name': u'target-2', 'sources': []},
# ] # ]
# self.assertEquals(serializer.data, expected) # self.assertEquals(serializer.data, expected)
class HyperlinkedNullableOneToOneTests(TestCase):
urls = 'rest_framework.tests.relations_hyperlink'
def setUp(self):
target = OneToOneTarget(name='target-1')
target.save()
new_target = OneToOneTarget(name='target-2')
new_target.save()
source = NullableOneToOneSource(name='source-1', target=target)
source.save()
def test_reverse_foreign_key_retrieve_with_null(self):
queryset = OneToOneTarget.objects.all()
serializer = NullableOneToOneTargetSerializer(queryset)
expected = [
{'url': '/onetoonetarget/1/', 'name': u'target-1', 'nullable_source': '/nullableonetoonesource/1/'},
{'url': '/onetoonetarget/2/', 'name': u'target-2', 'nullable_source': None},
]
self.assertEquals(serializer.data, expected)

View File

@ -1,7 +1,6 @@
from django.db import models
from django.test import TestCase from django.test import TestCase
from rest_framework import serializers from rest_framework import serializers
from rest_framework.tests.models import ForeignKeyTarget, ForeignKeySource, NullableForeignKeySource from rest_framework.tests.models import ForeignKeyTarget, ForeignKeySource, NullableForeignKeySource, OneToOneTarget, NullableOneToOneSource
class ForeignKeySourceSerializer(serializers.ModelSerializer): class ForeignKeySourceSerializer(serializers.ModelSerializer):
@ -28,6 +27,18 @@ class NullableForeignKeySourceSerializer(serializers.ModelSerializer):
model = NullableForeignKeySource model = NullableForeignKeySource
class NullableOneToOneSourceSerializer(serializers.ModelSerializer):
class Meta:
model = NullableOneToOneSource
class NullableOneToOneTargetSerializer(serializers.ModelSerializer):
nullable_source = NullableOneToOneSourceSerializer()
class Meta:
model = OneToOneTarget
class ReverseForeignKeyTests(TestCase): class ReverseForeignKeyTests(TestCase):
def setUp(self): def setUp(self):
target = ForeignKeyTarget(name='target-1') target = ForeignKeyTarget(name='target-1')
@ -82,3 +93,22 @@ class NestedNullableForeignKeyTests(TestCase):
{'id': 3, 'name': u'source-3', 'target': None}, {'id': 3, 'name': u'source-3', 'target': None},
] ]
self.assertEquals(serializer.data, expected) self.assertEquals(serializer.data, expected)
class NestedNullableOneToOneTests(TestCase):
def setUp(self):
target = OneToOneTarget(name='target-1')
target.save()
new_target = OneToOneTarget(name='target-2')
new_target.save()
source = NullableOneToOneSource(name='source-1', target=target)
source.save()
def test_reverse_foreign_key_retrieve_with_null(self):
queryset = OneToOneTarget.objects.all()
serializer = NullableOneToOneTargetSerializer(queryset)
expected = [
{'id': 1, 'name': u'target-1', 'nullable_source': {'id': 1, 'name': u'source-1', 'target': 1}},
{'id': 2, 'name': u'target-2', 'nullable_source': None},
]
self.assertEquals(serializer.data, expected)

View File

@ -1,7 +1,6 @@
from django.db import models
from django.test import TestCase from django.test import TestCase
from rest_framework import serializers from rest_framework import serializers
from rest_framework.tests.models import ManyToManyTarget, ManyToManySource, ForeignKeyTarget, ForeignKeySource, NullableForeignKeySource from rest_framework.tests.models import ManyToManyTarget, ManyToManySource, ForeignKeyTarget, ForeignKeySource, NullableForeignKeySource, OneToOneTarget, NullableOneToOneSource
class ManyToManyTargetSerializer(serializers.ModelSerializer): class ManyToManyTargetSerializer(serializers.ModelSerializer):
@ -33,6 +32,14 @@ class NullableForeignKeySourceSerializer(serializers.ModelSerializer):
model = NullableForeignKeySource model = NullableForeignKeySource
# OneToOne
class NullableOneToOneTargetSerializer(serializers.ModelSerializer):
nullable_source = serializers.PrimaryKeyRelatedField()
class Meta:
model = OneToOneTarget
# TODO: Add test that .data cannot be accessed prior to .is_valid # TODO: Add test that .data cannot be accessed prior to .is_valid
class PKManyToManyTests(TestCase): class PKManyToManyTests(TestCase):
@ -187,6 +194,13 @@ class PKForeignKeyTests(TestCase):
] ]
self.assertEquals(serializer.data, expected) self.assertEquals(serializer.data, expected)
def test_foreign_key_update_incorrect_type(self):
data = {'id': 1, 'name': u'source-1', 'target': 'foo'}
instance = ForeignKeySource.objects.get(pk=1)
serializer = ForeignKeySourceSerializer(instance, data=data)
self.assertFalse(serializer.is_valid())
self.assertEquals(serializer.errors, {'target': [u'Incorrect type. Expected pk value, received str.']})
def test_reverse_foreign_key_update(self): def test_reverse_foreign_key_update(self):
data = {'id': 2, 'name': u'target-2', 'sources': [1, 3]} data = {'id': 2, 'name': u'target-2', 'sources': [1, 3]}
instance = ForeignKeyTarget.objects.get(pk=2) instance = ForeignKeyTarget.objects.get(pk=2)
@ -199,7 +213,7 @@ class PKForeignKeyTests(TestCase):
expected = [ expected = [
{'id': 1, 'name': u'target-1', 'sources': [1, 2, 3]}, {'id': 1, 'name': u'target-1', 'sources': [1, 2, 3]},
{'id': 2, 'name': u'target-2', 'sources': []}, {'id': 2, 'name': u'target-2', 'sources': []},
] ]
self.assertEquals(new_serializer.data, expected) self.assertEquals(new_serializer.data, expected)
serializer.save() serializer.save()
@ -383,3 +397,22 @@ class PKNullableForeignKeyTests(TestCase):
# {'id': 2, 'name': u'target-2', 'sources': []}, # {'id': 2, 'name': u'target-2', 'sources': []},
# ] # ]
# self.assertEquals(serializer.data, expected) # self.assertEquals(serializer.data, expected)
class PKNullableOneToOneTests(TestCase):
def setUp(self):
target = OneToOneTarget(name='target-1')
target.save()
new_target = OneToOneTarget(name='target-2')
new_target.save()
source = NullableOneToOneSource(name='source-1', target=target)
source.save()
def test_reverse_foreign_key_retrieve_with_null(self):
queryset = OneToOneTarget.objects.all()
serializer = NullableOneToOneTargetSerializer(queryset)
expected = [
{'id': 1, 'name': u'target-1', 'nullable_source': 1},
{'id': 2, 'name': u'target-2', 'nullable_source': None},
]
self.assertEquals(serializer.data, expected)

View File

@ -0,0 +1,257 @@
from django.test import TestCase
from rest_framework import serializers
from rest_framework.tests.models import NullableForeignKeySource, ForeignKeySource, ForeignKeyTarget
class ForeignKeyTargetSerializer(serializers.ModelSerializer):
sources = serializers.ManySlugRelatedField(slug_field='name')
class Meta:
model = ForeignKeyTarget
class ForeignKeySourceSerializer(serializers.ModelSerializer):
target = serializers.SlugRelatedField(slug_field='name')
class Meta:
model = ForeignKeySource
class NullableForeignKeySourceSerializer(serializers.ModelSerializer):
target = serializers.SlugRelatedField(slug_field='name', null=True)
class Meta:
model = NullableForeignKeySource
# TODO: M2M Tests, FKTests (Non-nulable), One2One
class PKForeignKeyTests(TestCase):
def setUp(self):
target = ForeignKeyTarget(name='target-1')
target.save()
new_target = ForeignKeyTarget(name='target-2')
new_target.save()
for idx in range(1, 4):
source = ForeignKeySource(name='source-%d' % idx, target=target)
source.save()
def test_foreign_key_retrieve(self):
queryset = ForeignKeySource.objects.all()
serializer = ForeignKeySourceSerializer(queryset)
expected = [
{'id': 1, 'name': u'source-1', 'target': 'target-1'},
{'id': 2, 'name': u'source-2', 'target': 'target-1'},
{'id': 3, 'name': u'source-3', 'target': 'target-1'}
]
self.assertEquals(serializer.data, expected)
def test_reverse_foreign_key_retrieve(self):
queryset = ForeignKeyTarget.objects.all()
serializer = ForeignKeyTargetSerializer(queryset)
expected = [
{'id': 1, 'name': u'target-1', 'sources': ['source-1', 'source-2', 'source-3']},
{'id': 2, 'name': u'target-2', 'sources': []},
]
self.assertEquals(serializer.data, expected)
def test_foreign_key_update(self):
data = {'id': 1, 'name': u'source-1', 'target': 'target-2'}
instance = ForeignKeySource.objects.get(pk=1)
serializer = ForeignKeySourceSerializer(instance, data=data)
self.assertTrue(serializer.is_valid())
self.assertEquals(serializer.data, data)
serializer.save()
# Ensure source 1 is updated, and everything else is as expected
queryset = ForeignKeySource.objects.all()
serializer = ForeignKeySourceSerializer(queryset)
expected = [
{'id': 1, 'name': u'source-1', 'target': 'target-2'},
{'id': 2, 'name': u'source-2', 'target': 'target-1'},
{'id': 3, 'name': u'source-3', 'target': 'target-1'}
]
self.assertEquals(serializer.data, expected)
def test_foreign_key_update_incorrect_type(self):
data = {'id': 1, 'name': u'source-1', 'target': 123}
instance = ForeignKeySource.objects.get(pk=1)
serializer = ForeignKeySourceSerializer(instance, data=data)
self.assertFalse(serializer.is_valid())
self.assertEquals(serializer.errors, {'target': [u'Object with name=123 does not exist.']})
def test_reverse_foreign_key_update(self):
data = {'id': 2, 'name': u'target-2', 'sources': ['source-1', 'source-3']}
instance = ForeignKeyTarget.objects.get(pk=2)
serializer = ForeignKeyTargetSerializer(instance, data=data)
self.assertTrue(serializer.is_valid())
# We shouldn't have saved anything to the db yet since save
# hasn't been called.
queryset = ForeignKeyTarget.objects.all()
new_serializer = ForeignKeyTargetSerializer(queryset)
expected = [
{'id': 1, 'name': u'target-1', 'sources': ['source-1', 'source-2', 'source-3']},
{'id': 2, 'name': u'target-2', 'sources': []},
]
self.assertEquals(new_serializer.data, expected)
serializer.save()
self.assertEquals(serializer.data, data)
# Ensure target 2 is update, and everything else is as expected
queryset = ForeignKeyTarget.objects.all()
serializer = ForeignKeyTargetSerializer(queryset)
expected = [
{'id': 1, 'name': u'target-1', 'sources': ['source-2']},
{'id': 2, 'name': u'target-2', 'sources': ['source-1', 'source-3']},
]
self.assertEquals(serializer.data, expected)
def test_foreign_key_create(self):
data = {'id': 4, 'name': u'source-4', 'target': 'target-2'}
serializer = ForeignKeySourceSerializer(data=data)
serializer.is_valid()
self.assertTrue(serializer.is_valid())
obj = serializer.save()
self.assertEquals(serializer.data, data)
self.assertEqual(obj.name, u'source-4')
# Ensure source 4 is added, and everything else is as expected
queryset = ForeignKeySource.objects.all()
serializer = ForeignKeySourceSerializer(queryset)
expected = [
{'id': 1, 'name': u'source-1', 'target': 'target-1'},
{'id': 2, 'name': u'source-2', 'target': 'target-1'},
{'id': 3, 'name': u'source-3', 'target': 'target-1'},
{'id': 4, 'name': u'source-4', 'target': 'target-2'},
]
self.assertEquals(serializer.data, expected)
def test_reverse_foreign_key_create(self):
data = {'id': 3, 'name': u'target-3', 'sources': ['source-1', 'source-3']}
serializer = ForeignKeyTargetSerializer(data=data)
self.assertTrue(serializer.is_valid())
obj = serializer.save()
self.assertEquals(serializer.data, data)
self.assertEqual(obj.name, u'target-3')
# Ensure target 3 is added, and everything else is as expected
queryset = ForeignKeyTarget.objects.all()
serializer = ForeignKeyTargetSerializer(queryset)
expected = [
{'id': 1, 'name': u'target-1', 'sources': ['source-2']},
{'id': 2, 'name': u'target-2', 'sources': []},
{'id': 3, 'name': u'target-3', 'sources': ['source-1', 'source-3']},
]
self.assertEquals(serializer.data, expected)
def test_foreign_key_update_with_invalid_null(self):
data = {'id': 1, 'name': u'source-1', 'target': None}
instance = ForeignKeySource.objects.get(pk=1)
serializer = ForeignKeySourceSerializer(instance, data=data)
self.assertFalse(serializer.is_valid())
self.assertEquals(serializer.errors, {'target': [u'Value may not be null']})
class SlugNullableForeignKeyTests(TestCase):
def setUp(self):
target = ForeignKeyTarget(name='target-1')
target.save()
for idx in range(1, 4):
if idx == 3:
target = None
source = NullableForeignKeySource(name='source-%d' % idx, target=target)
source.save()
def test_foreign_key_retrieve_with_null(self):
queryset = NullableForeignKeySource.objects.all()
serializer = NullableForeignKeySourceSerializer(queryset)
expected = [
{'id': 1, 'name': u'source-1', 'target': 'target-1'},
{'id': 2, 'name': u'source-2', 'target': 'target-1'},
{'id': 3, 'name': u'source-3', 'target': None},
]
self.assertEquals(serializer.data, expected)
def test_foreign_key_create_with_valid_null(self):
data = {'id': 4, 'name': u'source-4', 'target': None}
serializer = NullableForeignKeySourceSerializer(data=data)
self.assertTrue(serializer.is_valid())
obj = serializer.save()
self.assertEquals(serializer.data, data)
self.assertEqual(obj.name, u'source-4')
# Ensure source 4 is created, and everything else is as expected
queryset = NullableForeignKeySource.objects.all()
serializer = NullableForeignKeySourceSerializer(queryset)
expected = [
{'id': 1, 'name': u'source-1', 'target': 'target-1'},
{'id': 2, 'name': u'source-2', 'target': 'target-1'},
{'id': 3, 'name': u'source-3', 'target': None},
{'id': 4, 'name': u'source-4', 'target': None}
]
self.assertEquals(serializer.data, expected)
def test_foreign_key_create_with_valid_emptystring(self):
"""
The emptystring should be interpreted as null in the context
of relationships.
"""
data = {'id': 4, 'name': u'source-4', 'target': ''}
expected_data = {'id': 4, 'name': u'source-4', 'target': None}
serializer = NullableForeignKeySourceSerializer(data=data)
self.assertTrue(serializer.is_valid())
obj = serializer.save()
self.assertEquals(serializer.data, expected_data)
self.assertEqual(obj.name, u'source-4')
# Ensure source 4 is created, and everything else is as expected
queryset = NullableForeignKeySource.objects.all()
serializer = NullableForeignKeySourceSerializer(queryset)
expected = [
{'id': 1, 'name': u'source-1', 'target': 'target-1'},
{'id': 2, 'name': u'source-2', 'target': 'target-1'},
{'id': 3, 'name': u'source-3', 'target': None},
{'id': 4, 'name': u'source-4', 'target': None}
]
self.assertEquals(serializer.data, expected)
def test_foreign_key_update_with_valid_null(self):
data = {'id': 1, 'name': u'source-1', 'target': None}
instance = NullableForeignKeySource.objects.get(pk=1)
serializer = NullableForeignKeySourceSerializer(instance, data=data)
self.assertTrue(serializer.is_valid())
self.assertEquals(serializer.data, data)
serializer.save()
# Ensure source 1 is updated, and everything else is as expected
queryset = NullableForeignKeySource.objects.all()
serializer = NullableForeignKeySourceSerializer(queryset)
expected = [
{'id': 1, 'name': u'source-1', 'target': None},
{'id': 2, 'name': u'source-2', 'target': 'target-1'},
{'id': 3, 'name': u'source-3', 'target': None}
]
self.assertEquals(serializer.data, expected)
def test_foreign_key_update_with_valid_emptystring(self):
"""
The emptystring should be interpreted as null in the context
of relationships.
"""
data = {'id': 1, 'name': u'source-1', 'target': ''}
expected_data = {'id': 1, 'name': u'source-1', 'target': None}
instance = NullableForeignKeySource.objects.get(pk=1)
serializer = NullableForeignKeySourceSerializer(instance, data=data)
self.assertTrue(serializer.is_valid())
self.assertEquals(serializer.data, expected_data)
serializer.save()
# Ensure source 1 is updated, and everything else is as expected
queryset = NullableForeignKeySource.objects.all()
serializer = NullableForeignKeySourceSerializer(queryset)
expected = [
{'id': 1, 'name': u'source-1', 'target': None},
{'id': 2, 'name': u'source-2', 'target': 'target-1'},
{'id': 3, 'name': u'source-3', 'target': None}
]
self.assertEquals(serializer.data, expected)

View File

@ -0,0 +1,78 @@
from collections import namedtuple
from django.core import urlresolvers
from django.test import TestCase
from django.test.client import RequestFactory
from rest_framework.compat import patterns, url, include
from rest_framework.urlpatterns import format_suffix_patterns
# A container class for test paths for the test case
URLTestPath = namedtuple('URLTestPath', ['path', 'args', 'kwargs'])
def dummy_view(request, *args, **kwargs):
pass
class FormatSuffixTests(TestCase):
"""
Tests `format_suffix_patterns` against different URLPatterns to ensure the URLs still resolve properly, including any captured parameters.
"""
def _resolve_urlpatterns(self, urlpatterns, test_paths):
factory = RequestFactory()
try:
urlpatterns = format_suffix_patterns(urlpatterns)
except:
self.fail("Failed to apply `format_suffix_patterns` on the supplied urlpatterns")
resolver = urlresolvers.RegexURLResolver(r'^/', urlpatterns)
for test_path in test_paths:
request = factory.get(test_path.path)
try:
callback, callback_args, callback_kwargs = resolver.resolve(request.path_info)
except:
self.fail("Failed to resolve URL: %s" % request.path_info)
self.assertEquals(callback_args, test_path.args)
self.assertEquals(callback_kwargs, test_path.kwargs)
def test_format_suffix(self):
urlpatterns = patterns(
'',
url(r'^test$', dummy_view),
)
test_paths = [
URLTestPath('/test', (), {}),
URLTestPath('/test.api', (), {'format': 'api'}),
URLTestPath('/test.asdf', (), {'format': 'asdf'}),
]
self._resolve_urlpatterns(urlpatterns, test_paths)
def test_default_args(self):
urlpatterns = patterns(
'',
url(r'^test$', dummy_view, {'foo': 'bar'}),
)
test_paths = [
URLTestPath('/test', (), {'foo': 'bar', }),
URLTestPath('/test.api', (), {'foo': 'bar', 'format': 'api'}),
URLTestPath('/test.asdf', (), {'foo': 'bar', 'format': 'asdf'}),
]
self._resolve_urlpatterns(urlpatterns, test_paths)
def test_included_urls(self):
nested_patterns = patterns(
'',
url(r'^path$', dummy_view)
)
urlpatterns = patterns(
'',
url(r'^test/', include(nested_patterns), {'foo': 'bar'}),
)
test_paths = [
URLTestPath('/test/path', (), {'foo': 'bar', }),
URLTestPath('/test/path.api', (), {'foo': 'bar', 'format': 'api'}),
URLTestPath('/test/path.asdf', (), {'foo': 'bar', 'format': 'asdf'}),
]
self._resolve_urlpatterns(urlpatterns, test_paths)

View File

@ -1,5 +1,35 @@
from rest_framework.compat import url from rest_framework.compat import url, include
from rest_framework.settings import api_settings from rest_framework.settings import api_settings
from django.core.urlresolvers import RegexURLResolver
def apply_suffix_patterns(urlpatterns, suffix_pattern, suffix_required):
ret = []
for urlpattern in urlpatterns:
if isinstance(urlpattern, RegexURLResolver):
# Set of included URL patterns
regex = urlpattern.regex.pattern
namespace = urlpattern.namespace
app_name = urlpattern.app_name
kwargs = urlpattern.default_kwargs
# Add in the included patterns, after applying the suffixes
patterns = apply_suffix_patterns(urlpattern.url_patterns,
suffix_pattern,
suffix_required)
ret.append(url(regex, include(patterns, namespace, app_name), kwargs))
else:
# Regular URL pattern
regex = urlpattern.regex.pattern.rstrip('$') + suffix_pattern
view = urlpattern._callback or urlpattern._callback_str
kwargs = urlpattern.default_args
name = urlpattern.name
# Add in both the existing and the new urlpattern
if not suffix_required:
ret.append(urlpattern)
ret.append(url(regex, view, kwargs, name))
return ret
def format_suffix_patterns(urlpatterns, suffix_required=False, allowed=None): def format_suffix_patterns(urlpatterns, suffix_required=False, allowed=None):
@ -28,15 +58,4 @@ def format_suffix_patterns(urlpatterns, suffix_required=False, allowed=None):
else: else:
suffix_pattern = r'\.(?P<%s>[a-z]+)$' % suffix_kwarg suffix_pattern = r'\.(?P<%s>[a-z]+)$' % suffix_kwarg
ret = [] return apply_suffix_patterns(urlpatterns, suffix_pattern, suffix_required)
for urlpattern in urlpatterns:
# Form our complementing '.format' urlpattern
regex = urlpattern.regex.pattern.rstrip('$') + suffix_pattern
view = urlpattern._callback or urlpattern._callback_str
kwargs = urlpattern.default_args
name = urlpattern.name
# Add in both the existing and the new urlpattern
if not suffix_required:
ret.append(urlpattern)
ret.append(url(regex, view, kwargs, name))
return ret

View File

@ -12,7 +12,7 @@ from rest_framework.serializers import DictWithMetadata, SortedDictWithMetadata
class JSONEncoder(json.JSONEncoder): class JSONEncoder(json.JSONEncoder):
""" """
JSONEncoder subclass that knows how to encode date/time, JSONEncoder subclass that knows how to encode date/time/timedelta,
decimal types, and generators. decimal types, and generators.
""" """
def default(self, o): def default(self, o):
@ -34,6 +34,8 @@ class JSONEncoder(json.JSONEncoder):
if o.microsecond: if o.microsecond:
r = r[:12] r = r[:12]
return r return r
elif isinstance(o, datetime.timedelta):
return str(o.total_seconds())
elif isinstance(o, decimal.Decimal): elif isinstance(o, decimal.Decimal):
return str(o) return str(o)
elif hasattr(o, '__iter__'): elif hasattr(o, '__iter__'):