mirror of
https://github.com/encode/django-rest-framework.git
synced 2024-11-11 04:07:39 +03:00
Merge branch 'upstream_master' into docs_patch_method
Conflicts: docs/api-guide/authentication.md
This commit is contained in:
commit
499d6424ae
48
README.md
48
README.md
|
@ -81,6 +81,21 @@ To run the tests.
|
|||
|
||||
# Changelog
|
||||
|
||||
### 2.1.17
|
||||
|
||||
**Date**: 26th Jan 2013
|
||||
|
||||
* Support proper 401 Unauthorized responses where appropriate, instead of always using 403 Forbidden.
|
||||
* Support json encoding of timedelta objects.
|
||||
* `format_suffix_patterns()` now supports `include` style URL patterns.
|
||||
* Bugfix: Fix issues with custom pagination serializers.
|
||||
* Bugfix: Nested serializers now accept `source='*'` argument.
|
||||
* Bugfix: Return proper validation errors when incorrect types supplied for relational fields.
|
||||
* Bugfix: Support nullable FKs with `SlugRelatedField`.
|
||||
* Bugfix: Don't call custom validation methods if the field has an error.
|
||||
|
||||
**Note**: If the primary authentication class is `TokenAuthentication` or `BasicAuthentication`, a view will now correctly return 401 responses to unauthenticated access, with an appropriate `WWW-Authenticate` header, instead of 403 responses.
|
||||
|
||||
### 2.1.16
|
||||
|
||||
**Date**: 14th Jan 2013
|
||||
|
@ -131,20 +146,20 @@ This change will not affect user code, so long as it's following the recommended
|
|||
* Bugfix: Fix exception in browseable API on DELETE.
|
||||
* Bugfix: Fix issue where pk was was being set to a string if set by URL kwarg.
|
||||
|
||||
## 2.1.11
|
||||
### 2.1.11
|
||||
|
||||
**Date**: 17th Dec 2012
|
||||
|
||||
* Bugfix: Fix issue with M2M fields in browseable API.
|
||||
|
||||
## 2.1.10
|
||||
### 2.1.10
|
||||
|
||||
**Date**: 17th Dec 2012
|
||||
|
||||
* Bugfix: Ensure read-only fields don't have model validation applied.
|
||||
* Bugfix: Fix hyperlinked fields in paginated results.
|
||||
|
||||
## 2.1.9
|
||||
### 2.1.9
|
||||
|
||||
**Date**: 11th Dec 2012
|
||||
|
||||
|
@ -152,14 +167,14 @@ This change will not affect user code, so long as it's following the recommended
|
|||
* Bugfix: Fix `Meta.fields` only working as tuple not as list.
|
||||
* Bugfix: Edge case if unnecessarily specifying `required=False` on read only field.
|
||||
|
||||
## 2.1.8
|
||||
### 2.1.8
|
||||
|
||||
**Date**: 8th Dec 2012
|
||||
|
||||
* Fix for creating nullable Foreign Keys with `''` as well as `None`.
|
||||
* Added `null=<bool>` related field option.
|
||||
|
||||
## 2.1.7
|
||||
### 2.1.7
|
||||
|
||||
**Date**: 7th Dec 2012
|
||||
|
||||
|
@ -171,19 +186,19 @@ This change will not affect user code, so long as it's following the recommended
|
|||
* Make `Request.user` settable.
|
||||
* Bugfix: Fix `RegexField` to work with `BrowsableAPIRenderer`
|
||||
|
||||
## 2.1.6
|
||||
### 2.1.6
|
||||
|
||||
**Date**: 23rd Nov 2012
|
||||
|
||||
* Bugfix: Unfix DjangoModelPermissions. (I am a doofus.)
|
||||
|
||||
## 2.1.5
|
||||
### 2.1.5
|
||||
|
||||
**Date**: 23rd Nov 2012
|
||||
|
||||
* Bugfix: Fix DjangoModelPermissions.
|
||||
|
||||
## 2.1.4
|
||||
### 2.1.4
|
||||
|
||||
**Date**: 22nd Nov 2012
|
||||
|
||||
|
@ -194,7 +209,7 @@ This change will not affect user code, so long as it's following the recommended
|
|||
* Added `obtain_token_view` to get tokens when using `TokenAuthentication`.
|
||||
* Bugfix: Django 1.5 configurable user support for `TokenAuthentication`.
|
||||
|
||||
## 2.1.3
|
||||
### 2.1.3
|
||||
|
||||
**Date**: 16th Nov 2012
|
||||
|
||||
|
@ -205,14 +220,14 @@ This change will not affect user code, so long as it's following the recommended
|
|||
* 201 Responses now return a 'Location' header.
|
||||
* Bugfix: Serializer fields now respect `max_length`.
|
||||
|
||||
## 2.1.2
|
||||
### 2.1.2
|
||||
|
||||
**Date**: 9th Nov 2012
|
||||
|
||||
* **Filtering support.**
|
||||
* Bugfix: Support creation of objects with reverse M2M relations.
|
||||
|
||||
## 2.1.1
|
||||
### 2.1.1
|
||||
|
||||
**Date**: 7th Nov 2012
|
||||
|
||||
|
@ -222,7 +237,7 @@ This change will not affect user code, so long as it's following the recommended
|
|||
* Bugfix: Make textareas same width as other fields in browsable API.
|
||||
* Private API change: `.get_serializer` now uses same `instance` and `data` ordering as serializer initialization.
|
||||
|
||||
## 2.1.0
|
||||
### 2.1.0
|
||||
|
||||
**Date**: 5th Nov 2012
|
||||
|
||||
|
@ -235,13 +250,13 @@ This change will not affect user code, so long as it's following the recommended
|
|||
* Minor field improvements. (Don't stringify dicts, more robust many-pk fields.)
|
||||
* Bugfixes (Support choice field in Browseable API)
|
||||
|
||||
## 2.0.2
|
||||
### 2.0.2
|
||||
|
||||
**Date**: 2nd Nov 2012
|
||||
|
||||
* Fix issues with pk related fields in the browsable API.
|
||||
|
||||
## 2.0.1
|
||||
### 2.0.1
|
||||
|
||||
**Date**: 1st Nov 2012
|
||||
|
||||
|
@ -249,12 +264,12 @@ This change will not affect user code, so long as it's following the recommended
|
|||
* Added SlugRelatedField and ManySlugRelatedField.
|
||||
* If PUT creates an instance return '201 Created', instead of '200 OK'.
|
||||
|
||||
## 2.0.0
|
||||
### 2.0.0
|
||||
|
||||
**Date**: 30th Oct 2012
|
||||
|
||||
* Redesign of core components.
|
||||
* Fix **all of the things**.
|
||||
* **Fix all of the things**.
|
||||
|
||||
# License
|
||||
|
||||
|
@ -295,4 +310,3 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|||
[markdown]: http://pypi.python.org/pypi/Markdown/
|
||||
[pyyaml]: http://pypi.python.org/pypi/PyYAML
|
||||
[django-filter]: http://pypi.python.org/pypi/django-filter
|
||||
|
||||
|
|
|
@ -8,7 +8,7 @@
|
|||
|
||||
Authentication is the mechanism of associating an incoming request with a set of identifying credentials, such as the user the request came from, or the token that it was signed with. The [permission] and [throttling] policies can then use those credentials to determine if the request should be permitted.
|
||||
|
||||
REST framework provides a number of authentication policies out of the box, and also allows you to implement custom policies.
|
||||
REST framework provides a number of authentication schemes out of the box, and also allows you to implement custom schemes.
|
||||
|
||||
Authentication will run the first time either the `request.user` or `request.auth` properties are accessed, and determines how those properties are initialized.
|
||||
|
||||
|
@ -16,17 +16,25 @@ The `request.user` property will typically be set to an instance of the `contrib
|
|||
|
||||
The `request.auth` property is used for any additional authentication information, for example, it may be used to represent an authentication token that the request was signed with.
|
||||
|
||||
---
|
||||
|
||||
**Note:** Don't forget that **authentication by itself won't allow or disallow an incoming request**, it simply identifies the credentials that the request was made with.
|
||||
|
||||
For information on how to setup the permission polices for your API please see the [permissions documentation][permission].
|
||||
|
||||
---
|
||||
|
||||
## How authentication is determined
|
||||
|
||||
The authentication policy is always defined as a list of classes. REST framework will attempt to authenticate with each class in the list, and will set `request.user` and `request.auth` using the return value of the first class that successfully authenticates.
|
||||
The authentication schemes are always defined as a list of classes. REST framework will attempt to authenticate with each class in the list, and will set `request.user` and `request.auth` using the return value of the first class that successfully authenticates.
|
||||
|
||||
If no class authenticates, `request.user` will be set to an instance of `django.contrib.auth.models.AnonymousUser`, and `request.auth` will be set to `None`.
|
||||
|
||||
The value of `request.user` and `request.auth` for unauthenticated requests can be modified using the `UNAUTHENTICATED_USER` and `UNAUTHENTICATED_TOKEN` settings.
|
||||
|
||||
## Setting the authentication policy
|
||||
## Setting the authentication scheme
|
||||
|
||||
The default authentication policy may be set globally, using the `DEFAULT_AUTHENTICATION_CLASSES` setting. For example.
|
||||
The default authentication schemes may be set globally, using the `DEFAULT_AUTHENTICATION` setting. For example.
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
'DEFAULT_AUTHENTICATION_CLASSES': (
|
||||
|
@ -35,7 +43,7 @@ The default authentication policy may be set globally, using the `DEFAULT_AUTHEN
|
|||
)
|
||||
}
|
||||
|
||||
You can also set the authentication policy on a per-view basis, using the `APIView` class based views.
|
||||
You can also set the authentication scheme on a per-view basis, using the `APIView` class based views.
|
||||
|
||||
class ExampleView(APIView):
|
||||
authentication_classes = (SessionAuthentication, BasicAuthentication)
|
||||
|
@ -60,24 +68,52 @@ Or, if you're using the `@api_view` decorator with function based views.
|
|||
}
|
||||
return Response(content)
|
||||
|
||||
## Unauthorized and Forbidden responses
|
||||
|
||||
When an unauthenticated request is denied permission there are two different error codes that may be appropriate.
|
||||
|
||||
* [HTTP 401 Unauthorized][http401]
|
||||
* [HTTP 403 Permission Denied][http403]
|
||||
|
||||
HTTP 401 responses must always include a `WWW-Authenticate` header, that instructs the client how to authenticate. HTTP 403 responses do not include the `WWW-Authenticate` header.
|
||||
|
||||
The kind of response that will be used depends on the authentication scheme. Although multiple authentication schemes may be in use, only one scheme may be used to determine the type of response. **The first authentication class set on the view is used when determining the type of response**.
|
||||
|
||||
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
|
||||
|
||||
## BasicAuthentication
|
||||
|
||||
This policy uses [HTTP Basic Authentication][basicauth], signed against a user's username and password. Basic authentication is generally only appropriate for testing.
|
||||
This authentication scheme uses [HTTP Basic Authentication][basicauth], signed against a user's username and password. Basic authentication is generally only appropriate for testing.
|
||||
|
||||
If successfully authenticated, `BasicAuthentication` provides the following credentials.
|
||||
|
||||
* `request.user` will be a Django `User` instance.
|
||||
* `request.auth` will be `None`.
|
||||
|
||||
Unauthenticated responses that are denied permission will result in an `HTTP 401 Unauthorized` response with an appropriate WWW-Authenticate header. For example:
|
||||
|
||||
WWW-Authenticate: Basic realm="api"
|
||||
|
||||
**Note:** If you use `BasicAuthentication` in production you must ensure that your API is only available over `https` only. You should also ensure that your API clients will always re-request the username and password at login, and will never store those details to persistent storage.
|
||||
|
||||
## TokenAuthentication
|
||||
|
||||
This policy uses a simple token-based HTTP Authentication scheme. Token authentication is appropriate for client-server setups, such as native desktop and mobile clients.
|
||||
This authentication scheme uses a simple token-based HTTP Authentication scheme. Token authentication is appropriate for client-server setups, such as native desktop and mobile clients.
|
||||
|
||||
To use the `TokenAuthentication` policy, include `rest_framework.authtoken` in your `INSTALLED_APPS` setting.
|
||||
To use the `TokenAuthentication` scheme, include `rest_framework.authtoken` in your `INSTALLED_APPS` setting.
|
||||
|
||||
You'll also need to create tokens for your users.
|
||||
|
||||
|
@ -93,10 +129,15 @@ For clients to authenticate, the token key should be included in the `Authorizat
|
|||
If successfully authenticated, `TokenAuthentication` provides the following credentials.
|
||||
|
||||
* `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:
|
||||
|
||||
WWW-Authenticate: Token
|
||||
|
||||
**Note:** If you use `TokenAuthentication` in production you must ensure that your API is only available over `https` only.
|
||||
|
||||
=======
|
||||
If you want every user to have an automatically generated Token, you can simply catch the User's `post_save` signal.
|
||||
|
||||
@receiver(post_save, sender=User)
|
||||
|
@ -127,22 +168,56 @@ The `obtain_auth_token` view will return a JSON response when valid `username` a
|
|||
|
||||
## SessionAuthentication
|
||||
|
||||
This policy uses Django's default session backend for authentication. Session authentication is appropriate for AJAX clients that are running in the same session context as your website.
|
||||
This authentication scheme uses Django's default session backend for authentication. Session authentication is appropriate for AJAX clients that are running in the same session context as your website.
|
||||
|
||||
If successfully authenticated, `SessionAuthentication` provides the following credentials.
|
||||
|
||||
* `request.user` will be a Django `User` instance.
|
||||
* `request.auth` will be `None`.
|
||||
|
||||
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`, `PATCH`, `POST` or `DELETE` requests. See the [Django CSRF documentation][csrf-ajax] for more details.
|
||||
|
||||
# Custom authentication
|
||||
|
||||
To implement a custom authentication policy, subclass `BaseAuthentication` and override the `.authenticate(self, request)` method. The method should return a two-tuple of `(user, auth)` if authentication succeeds, or `None` otherwise.
|
||||
To implement a custom authentication scheme, subclass `BaseAuthentication` and override the `.authenticate(self, request)` method. The method should return a two-tuple of `(user, auth)` if authentication succeeds, or `None` otherwise.
|
||||
|
||||
In some circumstances instead of returning `None`, you may want to raise an `AuthenticationFailed` exception from the `.authenticate()` method.
|
||||
|
||||
Typically the approach you should take is:
|
||||
|
||||
* If authentication is not attempted, return `None`. Any other authentication schemes also in use will still be checked.
|
||||
* If authentication is attempted but fails, raise a `AuthenticationFailed` exception. An error response will be returned immediately, without checking any other authentication schemes.
|
||||
|
||||
You *may* also override the `.authentication_header(self, request)` method. If implemented, it should return a string that will be used as the value of the `WWW-Authenticate` header in a `HTTP 401 Unauthorized` response.
|
||||
|
||||
If the `.authentication_header()` method is not overridden, the authentication scheme will return `HTTP 403 Forbidden` responses when an unauthenticated request is denied access.
|
||||
|
||||
## Example
|
||||
|
||||
The following example will authenticate any incoming request as the user given by the username in a custom request header named 'X_USERNAME'.
|
||||
|
||||
class ExampleAuthentication(authentication.BaseAuthentication):
|
||||
def has_permission(self, request, view, obj=None):
|
||||
username = request.META.get('X_USERNAME')
|
||||
if not username:
|
||||
return None
|
||||
|
||||
try:
|
||||
user = User.objects.get(username=username)
|
||||
except User.DoesNotExist:
|
||||
raise authenticate.AuthenticationFailed('No such user')
|
||||
|
||||
return (user, None)
|
||||
|
||||
|
||||
[cite]: http://jacobian.org/writing/rest-worst-practices/
|
||||
[http401]: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.2
|
||||
[http403]: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.4
|
||||
[basicauth]: http://tools.ietf.org/html/rfc2617
|
||||
[oauth]: http://oauth.net/2/
|
||||
[permission]: permissions.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
|
||||
|
|
|
@ -53,11 +53,27 @@ Raised if the request contains malformed data when accessing `request.DATA` or `
|
|||
|
||||
By default this exception results in a response with the HTTP status code "400 Bad Request".
|
||||
|
||||
## AuthenticationFailed
|
||||
|
||||
**Signature:** `AuthenticationFailed(detail=None)`
|
||||
|
||||
Raised when an incoming request includes incorrect authentication.
|
||||
|
||||
By default this exception results in a response with the HTTP status code "401 Unauthenticated", but it may also result in a "403 Forbidden" response, depending on the authentication scheme in use. See the [authentication documentation][authentication] for more details.
|
||||
|
||||
## NotAuthenticated
|
||||
|
||||
**Signature:** `NotAuthenticated(detail=None)`
|
||||
|
||||
Raised when an unauthenticated request fails the permission checks.
|
||||
|
||||
By default this exception results in a response with the HTTP status code "401 Unauthenticated", but it may also result in a "403 Forbidden" response, depending on the authentication scheme in use. See the [authentication documentation][authentication] for more details.
|
||||
|
||||
## PermissionDenied
|
||||
|
||||
**Signature:** `PermissionDenied(detail=None)`
|
||||
|
||||
Raised when an incoming request fails the permission checks.
|
||||
Raised when an authenticated request fails the permission checks.
|
||||
|
||||
By default this exception results in a response with the HTTP status code "403 Forbidden".
|
||||
|
||||
|
@ -86,3 +102,4 @@ Raised when an incoming request fails the throttling checks.
|
|||
By default this exception results in a response with the HTTP status code "429 Too Many Requests".
|
||||
|
||||
[cite]: http://www.doughellmann.com/articles/how-tos/python-exception-handling/index.html
|
||||
[authentication]: authentication.md
|
||||
|
|
|
@ -193,6 +193,16 @@ A date and time representation.
|
|||
|
||||
Corresponds to `django.db.models.fields.DateTimeField`
|
||||
|
||||
When using `ModelSerializer` or `HyperlinkedModelSerializer`, note that any model fields with `auto_now=True` or `auto_now_add=True` will use serializer fields that are `read_only=True` by default.
|
||||
|
||||
If you want to override this behavior, you'll need to declare the `DateTimeField` explicitly on the serializer. For example:
|
||||
|
||||
class CommentSerializer(serializers.ModelSerializer):
|
||||
created = serializers.DateTimeField()
|
||||
|
||||
class Meta:
|
||||
model = Comment
|
||||
|
||||
## IntegerField
|
||||
|
||||
An integer representation.
|
||||
|
|
|
@ -114,8 +114,8 @@ You can also override the name used for the object list field, by setting the `r
|
|||
For example, to nest a pair of links labelled 'prev' and 'next', and set the name for the results field to 'objects', you might use something like this.
|
||||
|
||||
class LinksSerializer(serializers.Serializer):
|
||||
next = pagination.NextURLField(source='*')
|
||||
prev = pagination.PreviousURLField(source='*')
|
||||
next = pagination.NextPageField(source='*')
|
||||
prev = pagination.PreviousPageField(source='*')
|
||||
|
||||
class CustomPaginationSerializer(pagination.BasePaginationSerializer):
|
||||
links = LinksSerializer(source='*') # Takes the page object as the source
|
||||
|
|
|
@ -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.
|
||||
|
||||
---
|
||||
|
||||
**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
|
||||
|
||||
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.
|
||||
|
@ -169,6 +179,7 @@ The following third party packages are also available.
|
|||
|
||||
[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
|
||||
[messagepack]: https://github.com/juanriaza/django-rest-framework-msgpack
|
||||
[juanriaza]: https://github.com/juanriaza
|
||||
|
|
|
@ -110,6 +110,15 @@ To implement a custom permission, override `BasePermission` and implement the `.
|
|||
|
||||
The method should return `True` if the request should be granted access, and `False` otherwise.
|
||||
|
||||
## Example
|
||||
|
||||
The following is an example of a permission class that checks the incoming request's IP address against a blacklist, and denies the request if the IP has been blacklisted.
|
||||
|
||||
class BlacklistPermission(permissions.BasePermission):
|
||||
def has_permission(self, request, view, obj=None):
|
||||
ip_addr = request.META['REMOTE_ADDR']
|
||||
blacklisted = Blacklist.objects.filter(ip_addr=ip_addr).exists()
|
||||
return not blacklisted
|
||||
|
||||
[cite]: https://developer.apple.com/library/mac/#documentation/security/Conceptual/AuthenticationAndAuthorizationGuide/Authorization/Authorization.html
|
||||
[authentication]: authentication.md
|
||||
|
|
|
@ -67,7 +67,7 @@ For example, given the following models:
|
|||
And a model serializer defined like this:
|
||||
|
||||
class BookmarkSerializer(serializers.ModelSerializer):
|
||||
tags = serializers.ManyRelatedField(source='tags')
|
||||
tags = serializers.ManyRelatedField()
|
||||
|
||||
class Meta:
|
||||
model = Bookmark
|
||||
|
|
|
@ -80,7 +80,7 @@ Renders the request data into `JSONP`. The `JSONP` media type provides a mechan
|
|||
|
||||
The javascript callback function must be set by the client including a `callback` URL query parameter. For example `http://example.com/api/users?callback=jsonpCallback`. If the callback function is not explicitly set by the client it will default to `'callback'`.
|
||||
|
||||
**Note**: If you require cross-domain AJAX requests, you may also want to consider using [CORS] as an alternative to `JSONP`.
|
||||
**Note**: If you require cross-domain AJAX requests, you may want to consider using the more modern approach of [CORS][cors] as an alternative to `JSONP`. See the [CORS documentation][cors-docs] for more details.
|
||||
|
||||
**.media_type**: `application/javascript`
|
||||
|
||||
|
@ -288,7 +288,8 @@ Comma-separated values are a plain-text tabular data format, that can be easily
|
|||
[cite]: https://docs.djangoproject.com/en/dev/ref/template-response/#the-rendering-process
|
||||
[conneg]: content-negotiation.md
|
||||
[browser-accept-headers]: http://www.gethifi.com/blog/browser-rest-http-accept-headers
|
||||
[CORS]: http://en.wikipedia.org/wiki/Cross-origin_resource_sharing
|
||||
[cors]: http://www.w3.org/TR/cors/
|
||||
[cors-docs]: ../topics/ajax-csrf-cors.md
|
||||
[HATEOAS]: http://timelessrepo.com/haters-gonna-hateoas
|
||||
[quote]: http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven
|
||||
[application/vnd.github+json]: http://developer.github.com/v3/media/
|
||||
|
|
|
@ -150,8 +150,16 @@ User requests to either `ContactListView` or `ContactDetailView` would be restri
|
|||
|
||||
# Custom throttles
|
||||
|
||||
To create a custom throttle, override `BaseThrottle` and implement `.allow_request(request, view)`. The method should return `True` if the request should be allowed, and `False` otherwise.
|
||||
To create a custom throttle, override `BaseThrottle` and implement `.allow_request(self, request, view)`. The method should return `True` if the request should be allowed, and `False` otherwise.
|
||||
|
||||
Optionally you may also override the `.wait()` method. If implemented, `.wait()` should return a recommended number of seconds to wait before attempting the next request, or `None`. The `.wait()` method will only be called if `.allow_request()` has previously returned `False`.
|
||||
|
||||
## Example
|
||||
|
||||
The following is an example of a rate throttle, that will randomly throttle 1 in every 10 requests.
|
||||
|
||||
class RandomRateThrottle(throttles.BaseThrottle):
|
||||
def allow_request(self, request, view):
|
||||
return random.randint(1, 10) == 1
|
||||
|
||||
[permissions]: permissions.md
|
||||
|
|
|
@ -25,18 +25,29 @@ pre {
|
|||
margin-top: 9px;
|
||||
}
|
||||
|
||||
body.index-page #main-content p.badges {
|
||||
padding-bottom: 1px;
|
||||
}
|
||||
|
||||
/* GitHub 'Star' badge */
|
||||
body.index-page #main-content iframe {
|
||||
body.index-page #main-content iframe.github-star-button {
|
||||
float: right;
|
||||
margin-top: -12px;
|
||||
margin-right: -15px;
|
||||
}
|
||||
|
||||
/* Tweet button */
|
||||
body.index-page #main-content iframe.twitter-share-button {
|
||||
float: right;
|
||||
margin-top: -12px;
|
||||
margin-right: 8px;
|
||||
}
|
||||
|
||||
/* Travis CI badge */
|
||||
body.index-page #main-content p:first-of-type {
|
||||
body.index-page #main-content img.travis-build-image {
|
||||
float: right;
|
||||
margin-right: 8px;
|
||||
margin-top: -14px;
|
||||
margin-top: -9px;
|
||||
margin-bottom: 0px;
|
||||
}
|
||||
|
||||
|
|
|
@ -1,5 +1,11 @@
|
|||
<iframe src="http://ghbtns.com/github-btn.html?user=tomchristie&repo=django-rest-framework&type=watch&count=true" allowtransparency="true" frameborder="0" scrolling="0" width="110px" height="20px"></iframe>
|
||||
[![Travis build image][travis-build-image]][travis]
|
||||
<p class="badges">
|
||||
<iframe src="http://ghbtns.com/github-btn.html?user=tomchristie&repo=django-rest-framework&type=watch&count=true" class="github-star-button" allowtransparency="true" frameborder="0" scrolling="0" width="110px" height="20px"></iframe>
|
||||
|
||||
<a href="https://twitter.com/share" class="twitter-share-button" data-url="django-rest-framework.org" data-text="Current status: Checking out the totally awesome Django REST framework! http://django-rest-framework.org" data-count="none">Tweet</a>
|
||||
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="http://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>
|
||||
|
||||
<img alt="Travis build image" src="https://secure.travis-ci.org/tomchristie/django-rest-framework.png?branch=master" class="travis-build-image">
|
||||
</p>
|
||||
|
||||
# Django REST framework
|
||||
|
||||
|
@ -111,6 +117,7 @@ The API guide is your complete reference manual to all the functionality provide
|
|||
|
||||
General guides to using REST framework.
|
||||
|
||||
* [AJAX, CSRF & CORS][ajax-csrf-cors]
|
||||
* [Browser enhancements][browser-enhancements]
|
||||
* [The Browsable API][browsableapi]
|
||||
* [REST, Hypermedia & HATEOAS][rest-hypermedia-hateoas]
|
||||
|
@ -132,10 +139,15 @@ Run the tests:
|
|||
|
||||
## 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.
|
||||
|
||||
For updates on REST framework development, you may also want to follow [the author][twitter] on Twitter.
|
||||
|
||||
<a style="padding-top: 10px" href="https://twitter.com/_tomchristie" class="twitter-follow-button" data-show-count="false">Follow @_tomchristie</a>
|
||||
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>
|
||||
|
||||
## License
|
||||
|
||||
Copyright (c) 2011-2013, Tom Christie
|
||||
|
@ -199,7 +211,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|||
[status]: api-guide/status-codes.md
|
||||
[settings]: api-guide/settings.md
|
||||
|
||||
[csrf]: topics/csrf.md
|
||||
[ajax-csrf-cors]: topics/ajax-csrf-cors.md
|
||||
[browser-enhancements]: topics/browser-enhancements.md
|
||||
[browsableapi]: topics/browsable-api.md
|
||||
[rest-hypermedia-hateoas]: topics/rest-hypermedia-hateoas.md
|
||||
|
@ -209,5 +221,10 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|||
[credits]: topics/credits.md
|
||||
|
||||
[group]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework
|
||||
[DabApps]: http://dabapps.com
|
||||
[email]: mailto:tom@tomchristie.com
|
||||
[stack-overflow]: http://stackoverflow.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/
|
||||
[twitter]: https://twitter.com/_tomchristie
|
||||
|
|
|
@ -89,6 +89,7 @@
|
|||
<li class="dropdown">
|
||||
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Topics <b class="caret"></b></a>
|
||||
<ul class="dropdown-menu">
|
||||
<li><a href="{{ base_url }}/topics/ajax-csrf-cors{{ suffix }}">AJAX, CSRF & CORS</a></li>
|
||||
<li><a href="{{ base_url }}/topics/browser-enhancements{{ suffix }}">Browser enhancements</a></li>
|
||||
<li><a href="{{ base_url }}/topics/browsable-api{{ suffix }}">The Browsable API</a></li>
|
||||
<li><a href="{{ base_url }}/topics/rest-hypermedia-hateoas{{ suffix }}">REST, Hypermedia & HATEOAS</a></li>
|
||||
|
|
41
docs/topics/ajax-csrf-cors.md
Normal file
41
docs/topics/ajax-csrf-cors.md
Normal file
|
@ -0,0 +1,41 @@
|
|||
# Working with AJAX, CSRF & CORS
|
||||
|
||||
> "Take a close look at possible CSRF / XSRF vulnerabilities on your own websites. They're the worst kind of vulnerability — very easy to exploit by attackers, yet not so intuitively easy to understand for software developers, at least until you've been bitten by one."
|
||||
>
|
||||
> — [Jeff Atwood][cite]
|
||||
|
||||
## Javascript clients
|
||||
|
||||
If your building a javascript client to interface with your Web API, you'll need to consider if the client can use the same authentication policy that is used by the rest of the website, and also determine if you need to use CSRF tokens or CORS headers.
|
||||
|
||||
AJAX requests that are made within the same context as the API they are interacting with will typically use `SessionAuthentication`. This ensures that once a user has logged in, any AJAX requests made can be authenticated using the same session-based authentication that is used for the rest of the website.
|
||||
|
||||
AJAX requests that are made on a different site from the API they are communicating with will typically need to use a non-session-based authentication scheme, such as `TokenAuthentication`.
|
||||
|
||||
## CSRF protection
|
||||
|
||||
[Cross Site Request Forgery][csrf] protection is a mechanism of guarding against a particular type of attack, which can occur when a user has not logged out of a web site, and continues to have a valid session. In this circumstance a malicious site may be able to perform actions against the target site, within the context of the logged-in session.
|
||||
|
||||
To guard against these type of attacks, you need to do two things:
|
||||
|
||||
1. Ensure that the 'safe' HTTP operations, such as `GET`, `HEAD` and `OPTIONS` cannot be used to alter any server-side state.
|
||||
2. Ensure that any 'unsafe' HTTP operations, such as `POST`, `PUT`, `PATCH` and `DELETE`, always require a valid CSRF token.
|
||||
|
||||
If you're using `SessionAuthentication` you'll need to include valid CSRF tokens for any `POST`, `PUT`, `PATCH` or `DELETE` operations.
|
||||
|
||||
The Django documentation describes how to [include CSRF tokens in AJAX requests][csrf-ajax].
|
||||
|
||||
## CORS
|
||||
|
||||
[Cross-Origin Resource Sharing][cors] is a mechanism for allowing clients to interact with APIs that are hosted on a different domain. CORS works by requiring the server to include a specific set of headers that allow a browser to determine if and when cross-domain requests should be allowed.
|
||||
|
||||
The best way to deal with CORS in REST framework is to add the required response headers in middleware. This ensures that CORS is supported transparently, without having to change any behavior in your views.
|
||||
|
||||
[Otto Yiu][ottoyiu] maintains the [django-cors-headers] package, which is known to work correctly with REST framework APIs.
|
||||
|
||||
[cite]: http://www.codinghorror.com/blog/2008/10/preventing-csrf-and-xsrf-attacks.html
|
||||
[csrf]: https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)
|
||||
[csrf-ajax]: https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax
|
||||
[cors]: http://www.w3.org/TR/cors/
|
||||
[ottoyiu]: https://github.com/ottoyiu/
|
||||
[django-cors-headers]: https://github.com/ottoyiu/django-cors-headers/
|
|
@ -92,6 +92,11 @@ The following people have helped make REST framework great.
|
|||
* Johannes Spielmann - [shezi]
|
||||
* James Cleveland - [radiosilence]
|
||||
* Steve Gregory - [steve-gregory]
|
||||
* Federico Capoano - [nemesisdesign]
|
||||
* Bruno Renié - [brutasse]
|
||||
* Kevin Stone - [kevinastone]
|
||||
* Guglielmo Celata - [guglielmo]
|
||||
* Mike Tums - [mktums]
|
||||
|
||||
Many thanks to everyone who's contributed to the project.
|
||||
|
||||
|
@ -219,3 +224,8 @@ You can also contact [@_tomchristie][twitter] directly on twitter.
|
|||
[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
|
||||
[guglielmo]: https://github.com/guglielmo
|
||||
[mktums]: https://github.com/mktums
|
||||
|
|
|
@ -1,12 +0,0 @@
|
|||
# Working with AJAX and CSRF
|
||||
|
||||
> "Take a close look at possible CSRF / XSRF vulnerabilities on your own websites. They're the worst kind of vulnerability -- very easy to exploit by attackers, yet not so intuitively easy to understand for software developers, at least until you've been bitten by one."
|
||||
>
|
||||
> — [Jeff Atwood][cite]
|
||||
|
||||
* Explain need to add CSRF token to AJAX requests.
|
||||
* Explain deferred CSRF style used by REST framework
|
||||
* Why you should use Django's standard login/logout views, and not REST framework view
|
||||
|
||||
|
||||
[cite]: http://www.codinghorror.com/blog/2008/10/preventing-csrf-and-xsrf-attacks.html
|
|
@ -12,14 +12,34 @@ Medium version numbers (0.x.0) may include minor API changes. You should read t
|
|||
|
||||
Major version numbers (x.0.0) are reserved for project milestones. No major point releases are currently planned.
|
||||
|
||||
## Upgrading
|
||||
|
||||
To upgrade Django REST framework to the latest version, use pip:
|
||||
|
||||
pip install -U djangorestframework
|
||||
|
||||
You can determine your currently installed version using `pip freeze`:
|
||||
|
||||
pip freeze | grep djangorestframework
|
||||
|
||||
---
|
||||
|
||||
## 2.1.x series
|
||||
|
||||
### Master
|
||||
### 2.1.17
|
||||
|
||||
**Date**: 26th Jan 2013
|
||||
|
||||
* Support proper 401 Unauthorized responses where appropriate, instead of always using 403 Forbidden.
|
||||
* Support json encoding of timedelta objects.
|
||||
* `format_suffix_patterns()` now supports `include` style URL patterns.
|
||||
* Bugfix: Fix issues with custom pagination serializers.
|
||||
* Bugfix: Nested serializers now accept `source='*'` argument.
|
||||
* Bugfix: Return proper validation errors when incorrect types supplied for relational fields.
|
||||
* Bugfix: Support nullable FKs with `SlugRelatedField`.
|
||||
* Bugfix: Don't call custom validation methods if the field has an error.
|
||||
|
||||
**Note**: If the primary authentication class is `TokenAuthentication` or `BasicAuthentication`, a view will now correctly return 401 responses to unauthenticated access, with an appropriate `WWW-Authenticate` header, instead of 403 responses.
|
||||
|
||||
### 2.1.16
|
||||
|
||||
|
|
|
@ -4,7 +4,7 @@
|
|||
|
||||
This tutorial will cover creating a simple pastebin code highlighting Web API. Along the way it will introduce the various components that make up REST framework, and give you a comprehensive understanding of how everything fits together.
|
||||
|
||||
The tutorial is fairly in-depth, so you should probably get a cookie and a cup of your favorite brew before getting started.<!-- If you just want a quick overview, you should head over to the [quickstart] documentation instead. -->
|
||||
The tutorial is fairly in-depth, so you should probably get a cookie and a cup of your favorite brew before getting started. If you just want a quick overview, you should head over to the [quickstart] documentation instead.
|
||||
|
||||
---
|
||||
|
||||
|
@ -109,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 rest_framework import serializers
|
||||
from snippets import models
|
||||
from snippets.models import Snippet
|
||||
|
||||
|
||||
class SnippetSerializer(serializers.Serializer):
|
||||
|
@ -130,15 +130,15 @@ The first thing we need to get started on our Web API is provide a way of serial
|
|||
"""
|
||||
if instance:
|
||||
# Update existing instance
|
||||
instance.title = attrs['title']
|
||||
instance.code = attrs['code']
|
||||
instance.linenos = attrs['linenos']
|
||||
instance.language = attrs['language']
|
||||
instance.style = attrs['style']
|
||||
instance.title = attrs.get('title', instance.title)
|
||||
instance.code = attrs.get('code', instance.code)
|
||||
instance.linenos = attrs.get('linenos', instance.linenos)
|
||||
instance.language = attrs.get('language', instance.language)
|
||||
instance.style = attrs.get('style', instance.style)
|
||||
return 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.
|
||||
|
||||
|
|
|
@ -22,7 +22,7 @@ We'd also need to make sure that when the model is saved, that we populate the h
|
|||
We'll need some extra imports:
|
||||
|
||||
from pygments.lexers import get_lexer_by_name
|
||||
from pygments.formatters import HtmlFormatter
|
||||
from pygments.formatters.html import HtmlFormatter
|
||||
from pygments import highlight
|
||||
|
||||
And now we can add a `.save()` method to our model class:
|
||||
|
@ -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:
|
||||
|
||||
from django.contrib.auth.models import User
|
||||
|
||||
class UserSerializer(serializers.ModelSerializer):
|
||||
snippets = serializers.ManyPrimaryKeyRelatedField()
|
||||
|
||||
|
@ -164,7 +166,8 @@ In the snippets app, create a new file, `permissions.py`
|
|||
if obj is None:
|
||||
return True
|
||||
|
||||
# Read permissions are allowed to any request
|
||||
# Read permissions are allowed to any request,
|
||||
# so we'll always allow GET, HEAD or OPTIONS requests.
|
||||
if request.method in permissions.SAFE_METHODS:
|
||||
return True
|
||||
|
||||
|
@ -188,4 +191,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.
|
||||
|
||||
[tut-5]: 5-relationships-and-hyperlinked-apis.md
|
||||
[tut-5]: 5-relationships-and-hyperlinked-apis.md
|
||||
|
|
|
@ -165,7 +165,7 @@ We've reached the end of our tutorial. If you want to get more involved in the
|
|||
|
||||
* 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 on Twitter][twitter] and say hi.
|
||||
* Follow [the author][twitter] on Twitter and say hi.
|
||||
|
||||
**Now go build awesome things.**
|
||||
|
||||
|
|
|
@ -1,3 +1,3 @@
|
|||
__version__ = '2.1.16'
|
||||
__version__ = '2.1.17'
|
||||
|
||||
VERSION = __version__ # synonym
|
||||
|
|
|
@ -21,32 +21,46 @@ class BaseAuthentication(object):
|
|||
"""
|
||||
raise NotImplementedError(".authenticate() must be overridden.")
|
||||
|
||||
def authenticate_header(self, request):
|
||||
"""
|
||||
Return a string to be used as the value of the `WWW-Authenticate`
|
||||
header in a `401 Unauthenticated` response, or `None` if the
|
||||
authentication scheme should return `403 Permission Denied` responses.
|
||||
"""
|
||||
pass
|
||||
|
||||
|
||||
class BasicAuthentication(BaseAuthentication):
|
||||
"""
|
||||
HTTP Basic authentication against username/password.
|
||||
"""
|
||||
www_authenticate_realm = 'api'
|
||||
|
||||
def authenticate(self, request):
|
||||
"""
|
||||
Returns a `User` if a correct username and password have been supplied
|
||||
using HTTP Basic authentication. Otherwise returns `None`.
|
||||
"""
|
||||
if 'HTTP_AUTHORIZATION' in request.META:
|
||||
auth = request.META['HTTP_AUTHORIZATION'].split()
|
||||
if len(auth) == 2 and auth[0].lower() == "basic":
|
||||
try:
|
||||
auth_parts = base64.b64decode(auth[1]).partition(':')
|
||||
except TypeError:
|
||||
return None
|
||||
auth = request.META.get('HTTP_AUTHORIZATION', '').split()
|
||||
|
||||
try:
|
||||
userid = smart_unicode(auth_parts[0])
|
||||
password = smart_unicode(auth_parts[2])
|
||||
except DjangoUnicodeDecodeError:
|
||||
return None
|
||||
if not auth or auth[0].lower() != "basic":
|
||||
return None
|
||||
|
||||
return self.authenticate_credentials(userid, password)
|
||||
if len(auth) != 2:
|
||||
raise exceptions.AuthenticationFailed('Invalid basic header')
|
||||
|
||||
try:
|
||||
auth_parts = base64.b64decode(auth[1]).partition(':')
|
||||
except TypeError:
|
||||
raise exceptions.AuthenticationFailed('Invalid basic header')
|
||||
|
||||
try:
|
||||
userid = smart_unicode(auth_parts[0])
|
||||
password = smart_unicode(auth_parts[2])
|
||||
except DjangoUnicodeDecodeError:
|
||||
raise exceptions.AuthenticationFailed('Invalid basic header')
|
||||
|
||||
return self.authenticate_credentials(userid, password)
|
||||
|
||||
def authenticate_credentials(self, userid, password):
|
||||
"""
|
||||
|
@ -55,6 +69,10 @@ class BasicAuthentication(BaseAuthentication):
|
|||
user = authenticate(username=userid, password=password)
|
||||
if user is not None and user.is_active:
|
||||
return (user, None)
|
||||
raise exceptions.AuthenticationFailed('Invalid username/password')
|
||||
|
||||
def authenticate_header(self, request):
|
||||
return 'Basic realm="%s"' % self.www_authenticate_realm
|
||||
|
||||
|
||||
class SessionAuthentication(BaseAuthentication):
|
||||
|
@ -74,7 +92,7 @@ class SessionAuthentication(BaseAuthentication):
|
|||
|
||||
# Unauthenticated, CSRF validation not required
|
||||
if not user or not user.is_active:
|
||||
return
|
||||
return None
|
||||
|
||||
# Enforce CSRF validation for session based authentication.
|
||||
class CSRFCheck(CsrfViewMiddleware):
|
||||
|
@ -85,7 +103,7 @@ class SessionAuthentication(BaseAuthentication):
|
|||
reason = CSRFCheck().process_view(http_request, None, (), {})
|
||||
if reason:
|
||||
# CSRF failed, bail with explicit error message
|
||||
raise exceptions.PermissionDenied('CSRF Failed: %s' % reason)
|
||||
raise exceptions.AuthenticationFailed('CSRF Failed: %s' % reason)
|
||||
|
||||
# CSRF passed with authenticated user
|
||||
return (user, None)
|
||||
|
@ -112,14 +130,26 @@ class TokenAuthentication(BaseAuthentication):
|
|||
def authenticate(self, request):
|
||||
auth = request.META.get('HTTP_AUTHORIZATION', '').split()
|
||||
|
||||
if len(auth) == 2 and auth[0].lower() == "token":
|
||||
key = auth[1]
|
||||
try:
|
||||
token = self.model.objects.get(key=key)
|
||||
except self.model.DoesNotExist:
|
||||
return None
|
||||
if not auth or auth[0].lower() != "token":
|
||||
return None
|
||||
|
||||
if len(auth) != 2:
|
||||
raise exceptions.AuthenticationFailed('Invalid token header')
|
||||
|
||||
return self.authenticate_credentials(auth[1])
|
||||
|
||||
def authenticate_credentials(self, key):
|
||||
try:
|
||||
token = self.model.objects.get(key=key)
|
||||
except self.model.DoesNotExist:
|
||||
raise exceptions.AuthenticationFailed('Invalid token')
|
||||
|
||||
if token.user.is_active:
|
||||
return (token.user, token)
|
||||
raise exceptions.AuthenticationFailed('User inactive or deleted')
|
||||
|
||||
def authenticate_header(self, request):
|
||||
return 'Token'
|
||||
|
||||
if token.user.is_active:
|
||||
return (token.user, token)
|
||||
|
||||
# TODO: OAuthAuthentication
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
from rest_framework.views import APIView
|
||||
import types
|
||||
|
||||
|
||||
def api_view(http_method_names):
|
||||
|
@ -23,6 +24,14 @@ def api_view(http_method_names):
|
|||
# pass
|
||||
# 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',))
|
||||
WrappedAPIView.http_method_names = [method.lower() for method in allowed_methods]
|
||||
|
||||
|
|
|
@ -23,6 +23,22 @@ class ParseError(APIException):
|
|||
self.detail = detail or self.default_detail
|
||||
|
||||
|
||||
class AuthenticationFailed(APIException):
|
||||
status_code = status.HTTP_401_UNAUTHORIZED
|
||||
default_detail = 'Incorrect authentication credentials.'
|
||||
|
||||
def __init__(self, detail=None):
|
||||
self.detail = detail or self.default_detail
|
||||
|
||||
|
||||
class NotAuthenticated(APIException):
|
||||
status_code = status.HTTP_401_UNAUTHORIZED
|
||||
default_detail = 'Authentication credentials were not provided.'
|
||||
|
||||
def __init__(self, detail=None):
|
||||
self.detail = detail or self.default_detail
|
||||
|
||||
|
||||
class PermissionDenied(APIException):
|
||||
status_code = status.HTTP_403_FORBIDDEN
|
||||
default_detail = 'You do not have permission to perform this action.'
|
||||
|
|
|
@ -34,6 +34,17 @@ class PreviousPageField(serializers.Field):
|
|||
return replace_query_param(url, self.page_field, page)
|
||||
|
||||
|
||||
class DefaultObjectSerializer(serializers.Field):
|
||||
"""
|
||||
If no object serializer is specified, then this serializer will be applied
|
||||
as the default.
|
||||
"""
|
||||
|
||||
def __init__(self, source=None, context=None):
|
||||
# Note: Swallow context kwarg - only required for eg. ModelSerializer.
|
||||
super(DefaultObjectSerializer, self).__init__(source=source)
|
||||
|
||||
|
||||
class PaginationSerializerOptions(serializers.SerializerOptions):
|
||||
"""
|
||||
An object that stores the options that may be provided to a
|
||||
|
@ -44,7 +55,7 @@ class PaginationSerializerOptions(serializers.SerializerOptions):
|
|||
def __init__(self, meta):
|
||||
super(PaginationSerializerOptions, self).__init__(meta)
|
||||
self.object_serializer_class = getattr(meta, 'object_serializer_class',
|
||||
serializers.Field)
|
||||
DefaultObjectSerializer)
|
||||
|
||||
|
||||
class BasePaginationSerializer(serializers.Serializer):
|
||||
|
@ -62,14 +73,13 @@ class BasePaginationSerializer(serializers.Serializer):
|
|||
super(BasePaginationSerializer, self).__init__(*args, **kwargs)
|
||||
results_field = self.results_field
|
||||
object_serializer = self.opts.object_serializer_class
|
||||
self.fields[results_field] = object_serializer(source='object_list')
|
||||
|
||||
def to_native(self, obj):
|
||||
"""
|
||||
Prevent default behaviour of iterating over elements, and serializing
|
||||
each in turn.
|
||||
"""
|
||||
return self.convert_object(obj)
|
||||
if 'context' in kwargs:
|
||||
context_kwarg = {'context': kwargs['context']}
|
||||
else:
|
||||
context_kwarg = {}
|
||||
|
||||
self.fields[results_field] = object_serializer(source='object_list', **context_kwarg)
|
||||
|
||||
|
||||
class PaginationSerializer(BasePaginationSerializer):
|
||||
|
|
|
@ -177,7 +177,7 @@ class PrimaryKeyRelatedField(RelatedField):
|
|||
|
||||
default_error_messages = {
|
||||
'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...
|
||||
|
@ -208,7 +208,8 @@ class PrimaryKeyRelatedField(RelatedField):
|
|||
msg = self.error_messages['does_not_exist'] % smart_unicode(data)
|
||||
raise ValidationError(msg)
|
||||
except (TypeError, ValueError):
|
||||
msg = self.error_messages['invalid']
|
||||
received = type(data).__name__
|
||||
msg = self.error_messages['incorrect_type'] % received
|
||||
raise ValidationError(msg)
|
||||
|
||||
def field_to_native(self, obj, field_name):
|
||||
|
@ -235,7 +236,7 @@ class ManyPrimaryKeyRelatedField(ManyRelatedField):
|
|||
|
||||
default_error_messages = {
|
||||
'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):
|
||||
|
@ -275,7 +276,8 @@ class ManyPrimaryKeyRelatedField(ManyRelatedField):
|
|||
msg = self.error_messages['does_not_exist'] % smart_unicode(data)
|
||||
raise ValidationError(msg)
|
||||
except (TypeError, ValueError):
|
||||
msg = self.error_messages['invalid']
|
||||
received = type(data).__name__
|
||||
msg = self.error_messages['incorrect_type'] % received
|
||||
raise ValidationError(msg)
|
||||
|
||||
### Slug relationships
|
||||
|
@ -333,7 +335,7 @@ class HyperlinkedRelatedField(RelatedField):
|
|||
'incorrect_match': _('Invalid hyperlink - Incorrect URL match'),
|
||||
'configuration_error': _('Invalid hyperlink due to configuration error'),
|
||||
'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):
|
||||
|
@ -397,8 +399,8 @@ class HyperlinkedRelatedField(RelatedField):
|
|||
try:
|
||||
http_prefix = value.startswith('http:') or value.startswith('https:')
|
||||
except AttributeError:
|
||||
msg = self.error_messages['invalid']
|
||||
raise ValidationError(msg)
|
||||
msg = self.error_messages['incorrect_type']
|
||||
raise ValidationError(msg % type(value).__name__)
|
||||
|
||||
if http_prefix:
|
||||
# If needed convert absolute URLs to relative path
|
||||
|
@ -434,8 +436,8 @@ class HyperlinkedRelatedField(RelatedField):
|
|||
except ObjectDoesNotExist:
|
||||
raise ValidationError(self.error_messages['does_not_exist'])
|
||||
except (TypeError, ValueError):
|
||||
msg = self.error_messages['invalid']
|
||||
raise ValidationError(msg)
|
||||
msg = self.error_messages['incorrect_type']
|
||||
raise ValidationError(msg % type(value).__name__)
|
||||
|
||||
return obj
|
||||
|
||||
|
|
|
@ -86,6 +86,7 @@ class Request(object):
|
|||
self._method = Empty
|
||||
self._content_type = Empty
|
||||
self._stream = Empty
|
||||
self._authenticator = None
|
||||
|
||||
if self.parser_context is None:
|
||||
self.parser_context = {}
|
||||
|
@ -166,7 +167,7 @@ class Request(object):
|
|||
by the authentication classes provided to the request.
|
||||
"""
|
||||
if not hasattr(self, '_user'):
|
||||
self._user, self._auth = self._authenticate()
|
||||
self._authenticator, self._user, self._auth = self._authenticate()
|
||||
return self._user
|
||||
|
||||
@user.setter
|
||||
|
@ -185,7 +186,7 @@ class Request(object):
|
|||
request, such as an authentication token.
|
||||
"""
|
||||
if not hasattr(self, '_auth'):
|
||||
self._user, self._auth = self._authenticate()
|
||||
self._authenticator, self._user, self._auth = self._authenticate()
|
||||
return self._auth
|
||||
|
||||
@auth.setter
|
||||
|
@ -196,6 +197,14 @@ class Request(object):
|
|||
"""
|
||||
self._auth = value
|
||||
|
||||
@property
|
||||
def successful_authenticator(self):
|
||||
"""
|
||||
Return the instance of the authentication instance class that was used
|
||||
to authenticate the request, or `None`.
|
||||
"""
|
||||
return self._authenticator
|
||||
|
||||
def _load_data_and_files(self):
|
||||
"""
|
||||
Parses the request content into self.DATA and self.FILES.
|
||||
|
@ -299,21 +308,23 @@ class Request(object):
|
|||
|
||||
def _authenticate(self):
|
||||
"""
|
||||
Attempt to authenticate the request using each authentication instance in turn.
|
||||
Returns a two-tuple of (user, authtoken).
|
||||
Attempt to authenticate the request using each authentication instance
|
||||
in turn.
|
||||
Returns a three-tuple of (authenticator, user, authtoken).
|
||||
"""
|
||||
for authenticator in self.authenticators:
|
||||
user_auth_tuple = authenticator.authenticate(self)
|
||||
if not user_auth_tuple is None:
|
||||
return user_auth_tuple
|
||||
user, auth = user_auth_tuple
|
||||
return (authenticator, user, auth)
|
||||
return self._not_authenticated()
|
||||
|
||||
def _not_authenticated(self):
|
||||
"""
|
||||
Return a two-tuple of (user, authtoken), representing an
|
||||
unauthenticated request.
|
||||
Return a three-tuple of (authenticator, user, authtoken), representing
|
||||
an unauthenticated request.
|
||||
|
||||
By default this will be (AnonymousUser, None).
|
||||
By default this will be (None, AnonymousUser, None).
|
||||
"""
|
||||
if api_settings.UNAUTHENTICATED_USER:
|
||||
user = api_settings.UNAUTHENTICATED_USER()
|
||||
|
@ -325,7 +336,7 @@ class Request(object):
|
|||
else:
|
||||
auth = None
|
||||
|
||||
return (user, auth)
|
||||
return (None, user, auth)
|
||||
|
||||
def __getattr__(self, attr):
|
||||
"""
|
||||
|
|
|
@ -2,6 +2,7 @@ import copy
|
|||
import datetime
|
||||
import types
|
||||
from decimal import Decimal
|
||||
from django.core.paginator import Page
|
||||
from django.db import models
|
||||
from django.forms import widgets
|
||||
from django.utils.datastructures import SortedDict
|
||||
|
@ -227,6 +228,8 @@ class BaseSerializer(Field):
|
|||
Run `validate_<fieldname>()` and `validate()` methods on the serializer
|
||||
"""
|
||||
for field_name, field in self.fields.items():
|
||||
if field_name in self._errors:
|
||||
continue
|
||||
try:
|
||||
validate_method = getattr(self, 'validate_%s' % field_name, None)
|
||||
if validate_method:
|
||||
|
@ -271,7 +274,11 @@ class BaseSerializer(Field):
|
|||
"""
|
||||
Serialize objects -> primitives.
|
||||
"""
|
||||
if hasattr(obj, '__iter__'):
|
||||
# Note: At the moment we have an ugly hack to determine if we should
|
||||
# walk over iterables. At some point, serializers will require an
|
||||
# explicit `many=True` in order to iterate over a set, and this hack
|
||||
# will disappear.
|
||||
if hasattr(obj, '__iter__') and not isinstance(obj, Page):
|
||||
return [self.convert_object(item) for item in obj]
|
||||
return self.convert_object(obj)
|
||||
|
||||
|
@ -298,6 +305,9 @@ class BaseSerializer(Field):
|
|||
Override default so that we can apply ModelSerializer as a nested
|
||||
field to relationships.
|
||||
"""
|
||||
if self.source == '*':
|
||||
return self.to_native(obj)
|
||||
|
||||
try:
|
||||
if self.source:
|
||||
for component in self.source.split('.'):
|
||||
|
|
|
@ -4,7 +4,7 @@ from django.test import Client, TestCase
|
|||
|
||||
from rest_framework import permissions
|
||||
from rest_framework.authtoken.models import Token
|
||||
from rest_framework.authentication import TokenAuthentication
|
||||
from rest_framework.authentication import TokenAuthentication, BasicAuthentication, SessionAuthentication
|
||||
from rest_framework.compat import patterns
|
||||
from rest_framework.views import APIView
|
||||
|
||||
|
@ -21,10 +21,10 @@ class MockView(APIView):
|
|||
def put(self, request):
|
||||
return HttpResponse({'a': 1, 'b': 2, 'c': 3})
|
||||
|
||||
MockView.authentication_classes += (TokenAuthentication,)
|
||||
|
||||
urlpatterns = patterns('',
|
||||
(r'^$', MockView.as_view()),
|
||||
(r'^session/$', MockView.as_view(authentication_classes=[SessionAuthentication])),
|
||||
(r'^basic/$', MockView.as_view(authentication_classes=[BasicAuthentication])),
|
||||
(r'^token/$', MockView.as_view(authentication_classes=[TokenAuthentication])),
|
||||
(r'^auth-token/$', 'rest_framework.authtoken.views.obtain_auth_token'),
|
||||
)
|
||||
|
||||
|
@ -43,24 +43,25 @@ class BasicAuthTests(TestCase):
|
|||
def test_post_form_passing_basic_auth(self):
|
||||
"""Ensure POSTing json over basic auth with correct credentials passes and does not require CSRF"""
|
||||
auth = 'Basic %s' % base64.encodestring('%s:%s' % (self.username, self.password)).strip()
|
||||
response = self.csrf_client.post('/', {'example': 'example'}, HTTP_AUTHORIZATION=auth)
|
||||
response = self.csrf_client.post('/basic/', {'example': 'example'}, HTTP_AUTHORIZATION=auth)
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
def test_post_json_passing_basic_auth(self):
|
||||
"""Ensure POSTing form over basic auth with correct credentials passes and does not require CSRF"""
|
||||
auth = 'Basic %s' % base64.encodestring('%s:%s' % (self.username, self.password)).strip()
|
||||
response = self.csrf_client.post('/', json.dumps({'example': 'example'}), 'application/json', HTTP_AUTHORIZATION=auth)
|
||||
response = self.csrf_client.post('/basic/', json.dumps({'example': 'example'}), 'application/json', HTTP_AUTHORIZATION=auth)
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
def test_post_form_failing_basic_auth(self):
|
||||
"""Ensure POSTing form over basic auth without correct credentials fails"""
|
||||
response = self.csrf_client.post('/', {'example': 'example'})
|
||||
self.assertEqual(response.status_code, 403)
|
||||
response = self.csrf_client.post('/basic/', {'example': 'example'})
|
||||
self.assertEqual(response.status_code, 401)
|
||||
|
||||
def test_post_json_failing_basic_auth(self):
|
||||
"""Ensure POSTing json over basic auth without correct credentials fails"""
|
||||
response = self.csrf_client.post('/', json.dumps({'example': 'example'}), 'application/json')
|
||||
self.assertEqual(response.status_code, 403)
|
||||
response = self.csrf_client.post('/basic/', json.dumps({'example': 'example'}), 'application/json')
|
||||
self.assertEqual(response.status_code, 401)
|
||||
self.assertEqual(response['WWW-Authenticate'], 'Basic realm="api"')
|
||||
|
||||
|
||||
class SessionAuthTests(TestCase):
|
||||
|
@ -83,7 +84,7 @@ class SessionAuthTests(TestCase):
|
|||
Ensure POSTing form over session authentication without CSRF token fails.
|
||||
"""
|
||||
self.csrf_client.login(username=self.username, password=self.password)
|
||||
response = self.csrf_client.post('/', {'example': 'example'})
|
||||
response = self.csrf_client.post('/session/', {'example': 'example'})
|
||||
self.assertEqual(response.status_code, 403)
|
||||
|
||||
def test_post_form_session_auth_passing(self):
|
||||
|
@ -91,7 +92,7 @@ class SessionAuthTests(TestCase):
|
|||
Ensure POSTing form over session authentication with logged in user and CSRF token passes.
|
||||
"""
|
||||
self.non_csrf_client.login(username=self.username, password=self.password)
|
||||
response = self.non_csrf_client.post('/', {'example': 'example'})
|
||||
response = self.non_csrf_client.post('/session/', {'example': 'example'})
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
def test_put_form_session_auth_passing(self):
|
||||
|
@ -99,14 +100,14 @@ class SessionAuthTests(TestCase):
|
|||
Ensure PUTting form over session authentication with logged in user and CSRF token passes.
|
||||
"""
|
||||
self.non_csrf_client.login(username=self.username, password=self.password)
|
||||
response = self.non_csrf_client.put('/', {'example': 'example'})
|
||||
response = self.non_csrf_client.put('/session/', {'example': 'example'})
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
def test_post_form_session_auth_failing(self):
|
||||
"""
|
||||
Ensure POSTing form over session authentication without logged in user fails.
|
||||
"""
|
||||
response = self.csrf_client.post('/', {'example': 'example'})
|
||||
response = self.csrf_client.post('/session/', {'example': 'example'})
|
||||
self.assertEqual(response.status_code, 403)
|
||||
|
||||
|
||||
|
@ -127,24 +128,24 @@ class TokenAuthTests(TestCase):
|
|||
def test_post_form_passing_token_auth(self):
|
||||
"""Ensure POSTing json over token auth with correct credentials passes and does not require CSRF"""
|
||||
auth = "Token " + self.key
|
||||
response = self.csrf_client.post('/', {'example': 'example'}, HTTP_AUTHORIZATION=auth)
|
||||
response = self.csrf_client.post('/token/', {'example': 'example'}, HTTP_AUTHORIZATION=auth)
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
def test_post_json_passing_token_auth(self):
|
||||
"""Ensure POSTing form over token auth with correct credentials passes and does not require CSRF"""
|
||||
auth = "Token " + self.key
|
||||
response = self.csrf_client.post('/', json.dumps({'example': 'example'}), 'application/json', HTTP_AUTHORIZATION=auth)
|
||||
response = self.csrf_client.post('/token/', json.dumps({'example': 'example'}), 'application/json', HTTP_AUTHORIZATION=auth)
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
def test_post_form_failing_token_auth(self):
|
||||
"""Ensure POSTing form over token auth without correct credentials fails"""
|
||||
response = self.csrf_client.post('/', {'example': 'example'})
|
||||
self.assertEqual(response.status_code, 403)
|
||||
response = self.csrf_client.post('/token/', {'example': 'example'})
|
||||
self.assertEqual(response.status_code, 401)
|
||||
|
||||
def test_post_json_failing_token_auth(self):
|
||||
"""Ensure POSTing json over token auth without correct credentials fails"""
|
||||
response = self.csrf_client.post('/', json.dumps({'example': 'example'}), 'application/json')
|
||||
self.assertEqual(response.status_code, 403)
|
||||
response = self.csrf_client.post('/token/', json.dumps({'example': 'example'}), 'application/json')
|
||||
self.assertEqual(response.status_code, 401)
|
||||
|
||||
def test_token_has_auto_assigned_key_if_none_provided(self):
|
||||
"""Ensure creating a token with no key will auto-assign a key"""
|
||||
|
|
|
@ -28,13 +28,27 @@ class DecoratorTestCase(TestCase):
|
|||
response.request = request
|
||||
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):
|
||||
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):
|
||||
|
||||
|
|
|
@ -1,25 +1,61 @@
|
|||
from django.contrib.contenttypes.models import ContentType
|
||||
from django.contrib.contenttypes.generic import GenericRelation, GenericForeignKey
|
||||
from django.db import models
|
||||
from django.test import TestCase
|
||||
from rest_framework import serializers
|
||||
from rest_framework.tests.models import *
|
||||
|
||||
|
||||
class Tag(models.Model):
|
||||
"""
|
||||
Tags have a descriptive slug, and are attached to an arbitrary object.
|
||||
"""
|
||||
tag = models.SlugField()
|
||||
content_type = models.ForeignKey(ContentType)
|
||||
object_id = models.PositiveIntegerField()
|
||||
tagged_item = GenericForeignKey('content_type', 'object_id')
|
||||
|
||||
def __unicode__(self):
|
||||
return self.tag
|
||||
|
||||
|
||||
class Bookmark(models.Model):
|
||||
"""
|
||||
A URL bookmark that may have multiple tags attached.
|
||||
"""
|
||||
url = models.URLField()
|
||||
tags = GenericRelation(Tag)
|
||||
|
||||
def __unicode__(self):
|
||||
return 'Bookmark: %s' % self.url
|
||||
|
||||
|
||||
class Note(models.Model):
|
||||
"""
|
||||
A textual note that may have multiple tags attached.
|
||||
"""
|
||||
text = models.TextField()
|
||||
tags = GenericRelation(Tag)
|
||||
|
||||
def __unicode__(self):
|
||||
return 'Note: %s' % self.text
|
||||
|
||||
|
||||
class TestGenericRelations(TestCase):
|
||||
def setUp(self):
|
||||
bookmark = Bookmark(url='https://www.djangoproject.com/')
|
||||
bookmark.save()
|
||||
django = Tag(tag_name='django')
|
||||
django.save()
|
||||
python = Tag(tag_name='python')
|
||||
python.save()
|
||||
t1 = TaggedItem(content_object=bookmark, tag=django)
|
||||
t1.save()
|
||||
t2 = TaggedItem(content_object=bookmark, tag=python)
|
||||
t2.save()
|
||||
self.bookmark = bookmark
|
||||
self.bookmark = Bookmark.objects.create(url='https://www.djangoproject.com/')
|
||||
Tag.objects.create(tagged_item=self.bookmark, tag='django')
|
||||
Tag.objects.create(tagged_item=self.bookmark, tag='python')
|
||||
self.note = Note.objects.create(text='Remember the milk')
|
||||
Tag.objects.create(tagged_item=self.note, tag='reminder')
|
||||
|
||||
def test_generic_relation(self):
|
||||
"""
|
||||
Test a relationship that spans a GenericRelation field.
|
||||
IE. A reverse generic relationship.
|
||||
"""
|
||||
|
||||
def test_reverse_generic_relation(self):
|
||||
class BookmarkSerializer(serializers.ModelSerializer):
|
||||
tags = serializers.ManyRelatedField(source='tags')
|
||||
tags = serializers.ManyRelatedField()
|
||||
|
||||
class Meta:
|
||||
model = Bookmark
|
||||
|
@ -31,3 +67,33 @@ class TestGenericRelations(TestCase):
|
|||
'url': u'https://www.djangoproject.com/'
|
||||
}
|
||||
self.assertEquals(serializer.data, expected)
|
||||
|
||||
def test_generic_fk(self):
|
||||
"""
|
||||
Test a relationship that spans a GenericForeignKey field.
|
||||
IE. A forward generic relationship.
|
||||
"""
|
||||
|
||||
class TagSerializer(serializers.ModelSerializer):
|
||||
tagged_item = serializers.RelatedField()
|
||||
|
||||
class Meta:
|
||||
model = Tag
|
||||
exclude = ('id', 'content_type', 'object_id')
|
||||
|
||||
serializer = TagSerializer(Tag.objects.all())
|
||||
expected = [
|
||||
{
|
||||
'tag': u'django',
|
||||
'tagged_item': u'Bookmark: https://www.djangoproject.com/'
|
||||
},
|
||||
{
|
||||
'tag': u'python',
|
||||
'tagged_item': u'Bookmark: https://www.djangoproject.com/'
|
||||
},
|
||||
{
|
||||
'tag': u'reminder',
|
||||
'tagged_item': u'Note: Remember the milk'
|
||||
}
|
||||
]
|
||||
self.assertEquals(serializer.data, expected)
|
||||
|
|
|
@ -86,27 +86,6 @@ class ReadOnlyManyToManyModel(RESTFrameworkModel):
|
|||
text = models.CharField(max_length=100, default='anchor')
|
||||
rel = models.ManyToManyField(Anchor)
|
||||
|
||||
# Models to test generic relations
|
||||
|
||||
|
||||
class Tag(RESTFrameworkModel):
|
||||
tag_name = models.SlugField()
|
||||
|
||||
|
||||
class TaggedItem(RESTFrameworkModel):
|
||||
tag = models.ForeignKey(Tag, related_name='items')
|
||||
content_type = models.ForeignKey(ContentType)
|
||||
object_id = models.PositiveIntegerField()
|
||||
content_object = GenericForeignKey('content_type', 'object_id')
|
||||
|
||||
def __unicode__(self):
|
||||
return self.tag.tag_name
|
||||
|
||||
|
||||
class Bookmark(RESTFrameworkModel):
|
||||
url = models.URLField()
|
||||
tags = GenericRelation(TaggedItem)
|
||||
|
||||
|
||||
# Model to test filtering.
|
||||
class FilterableItem(RESTFrameworkModel):
|
||||
|
|
|
@ -252,6 +252,8 @@ class TestCustomPaginateByParam(TestCase):
|
|||
self.assertEquals(response.data['results'], self.data[:5])
|
||||
|
||||
|
||||
### Tests for context in pagination serializers
|
||||
|
||||
class CustomField(serializers.Field):
|
||||
def to_native(self, value):
|
||||
if not 'view' in self.context:
|
||||
|
@ -262,6 +264,11 @@ class CustomField(serializers.Field):
|
|||
class BasicModelSerializer(serializers.Serializer):
|
||||
text = CustomField()
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super(BasicModelSerializer, self).__init__(*args, **kwargs)
|
||||
if not 'view' in self.context:
|
||||
raise RuntimeError("context isn't getting passed into serializer init")
|
||||
|
||||
|
||||
class TestContextPassedToCustomField(TestCase):
|
||||
def setUp(self):
|
||||
|
@ -279,3 +286,39 @@ class TestContextPassedToCustomField(TestCase):
|
|||
|
||||
self.assertEquals(response.status_code, status.HTTP_200_OK)
|
||||
|
||||
|
||||
### Tests for custom pagination serializers
|
||||
|
||||
class LinksSerializer(serializers.Serializer):
|
||||
next = pagination.NextPageField(source='*')
|
||||
prev = pagination.PreviousPageField(source='*')
|
||||
|
||||
|
||||
class CustomPaginationSerializer(pagination.BasePaginationSerializer):
|
||||
links = LinksSerializer(source='*') # Takes the page object as the source
|
||||
total_results = serializers.Field(source='paginator.count')
|
||||
|
||||
results_field = 'objects'
|
||||
|
||||
|
||||
class TestCustomPaginationSerializer(TestCase):
|
||||
def setUp(self):
|
||||
objects = ['john', 'paul', 'george', 'ringo']
|
||||
paginator = Paginator(objects, 2)
|
||||
self.page = paginator.page(1)
|
||||
|
||||
def test_custom_pagination_serializer(self):
|
||||
request = RequestFactory().get('/foobar')
|
||||
serializer = CustomPaginationSerializer(
|
||||
instance=self.page,
|
||||
context={'request': request}
|
||||
)
|
||||
expected = {
|
||||
'links': {
|
||||
'next': 'http://testserver/foobar?page=2',
|
||||
'prev': None
|
||||
},
|
||||
'total_results': 4,
|
||||
'objects': ['john', 'paul']
|
||||
}
|
||||
self.assertEquals(serializer.data, expected)
|
||||
|
|
|
@ -215,6 +215,13 @@ class HyperlinkedForeignKeyTests(TestCase):
|
|||
]
|
||||
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):
|
||||
data = {'url': '/foreignkeytarget/2/', 'name': u'target-2', 'sources': ['/foreignkeysource/1/', '/foreignkeysource/3/']}
|
||||
instance = ForeignKeyTarget.objects.get(pk=2)
|
||||
|
@ -227,7 +234,7 @@ class HyperlinkedForeignKeyTests(TestCase):
|
|||
expected = [
|
||||
{'url': '/foreignkeytarget/1/', 'name': u'target-1', 'sources': ['/foreignkeysource/1/', '/foreignkeysource/2/', '/foreignkeysource/3/']},
|
||||
{'url': '/foreignkeytarget/2/', 'name': u'target-2', 'sources': []},
|
||||
]
|
||||
]
|
||||
self.assertEquals(new_serializer.data, expected)
|
||||
|
||||
serializer.save()
|
||||
|
|
|
@ -194,6 +194,13 @@ class PKForeignKeyTests(TestCase):
|
|||
]
|
||||
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):
|
||||
data = {'id': 2, 'name': u'target-2', 'sources': [1, 3]}
|
||||
instance = ForeignKeyTarget.objects.get(pk=2)
|
||||
|
|
|
@ -1,9 +1,23 @@
|
|||
from django.test import TestCase
|
||||
from rest_framework import serializers
|
||||
from rest_framework.tests.models import NullableForeignKeySource, ForeignKeyTarget
|
||||
from rest_framework.tests.models import NullableForeignKeySource, ForeignKeySource, ForeignKeyTarget
|
||||
|
||||
|
||||
class NullableSlugSourceSerializer(serializers.ModelSerializer):
|
||||
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:
|
||||
|
@ -11,6 +25,132 @@ class NullableSlugSourceSerializer(serializers.ModelSerializer):
|
|||
|
||||
|
||||
# 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):
|
||||
|
@ -24,7 +164,7 @@ class SlugNullableForeignKeyTests(TestCase):
|
|||
|
||||
def test_foreign_key_retrieve_with_null(self):
|
||||
queryset = NullableForeignKeySource.objects.all()
|
||||
serializer = NullableSlugSourceSerializer(queryset)
|
||||
serializer = NullableForeignKeySourceSerializer(queryset)
|
||||
expected = [
|
||||
{'id': 1, 'name': u'source-1', 'target': 'target-1'},
|
||||
{'id': 2, 'name': u'source-2', 'target': 'target-1'},
|
||||
|
@ -34,7 +174,7 @@ class SlugNullableForeignKeyTests(TestCase):
|
|||
|
||||
def test_foreign_key_create_with_valid_null(self):
|
||||
data = {'id': 4, 'name': u'source-4', 'target': None}
|
||||
serializer = NullableSlugSourceSerializer(data=data)
|
||||
serializer = NullableForeignKeySourceSerializer(data=data)
|
||||
self.assertTrue(serializer.is_valid())
|
||||
obj = serializer.save()
|
||||
self.assertEquals(serializer.data, data)
|
||||
|
@ -42,7 +182,7 @@ class SlugNullableForeignKeyTests(TestCase):
|
|||
|
||||
# Ensure source 4 is created, and everything else is as expected
|
||||
queryset = NullableForeignKeySource.objects.all()
|
||||
serializer = NullableSlugSourceSerializer(queryset)
|
||||
serializer = NullableForeignKeySourceSerializer(queryset)
|
||||
expected = [
|
||||
{'id': 1, 'name': u'source-1', 'target': 'target-1'},
|
||||
{'id': 2, 'name': u'source-2', 'target': 'target-1'},
|
||||
|
@ -58,7 +198,7 @@ class SlugNullableForeignKeyTests(TestCase):
|
|||
"""
|
||||
data = {'id': 4, 'name': u'source-4', 'target': ''}
|
||||
expected_data = {'id': 4, 'name': u'source-4', 'target': None}
|
||||
serializer = NullableSlugSourceSerializer(data=data)
|
||||
serializer = NullableForeignKeySourceSerializer(data=data)
|
||||
self.assertTrue(serializer.is_valid())
|
||||
obj = serializer.save()
|
||||
self.assertEquals(serializer.data, expected_data)
|
||||
|
@ -66,7 +206,7 @@ class SlugNullableForeignKeyTests(TestCase):
|
|||
|
||||
# Ensure source 4 is created, and everything else is as expected
|
||||
queryset = NullableForeignKeySource.objects.all()
|
||||
serializer = NullableSlugSourceSerializer(queryset)
|
||||
serializer = NullableForeignKeySourceSerializer(queryset)
|
||||
expected = [
|
||||
{'id': 1, 'name': u'source-1', 'target': 'target-1'},
|
||||
{'id': 2, 'name': u'source-2', 'target': 'target-1'},
|
||||
|
@ -78,14 +218,14 @@ class SlugNullableForeignKeyTests(TestCase):
|
|||
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 = NullableSlugSourceSerializer(instance, data=data)
|
||||
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 = NullableSlugSourceSerializer(queryset)
|
||||
serializer = NullableForeignKeySourceSerializer(queryset)
|
||||
expected = [
|
||||
{'id': 1, 'name': u'source-1', 'target': None},
|
||||
{'id': 2, 'name': u'source-2', 'target': 'target-1'},
|
||||
|
@ -101,14 +241,14 @@ class SlugNullableForeignKeyTests(TestCase):
|
|||
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 = NullableSlugSourceSerializer(instance, data=data)
|
||||
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 = NullableSlugSourceSerializer(queryset)
|
||||
serializer = NullableForeignKeySourceSerializer(queryset)
|
||||
expected = [
|
||||
{'id': 1, 'name': u'source-1', 'target': None},
|
||||
{'id': 2, 'name': u'source-2', 'target': 'target-1'},
|
||||
|
|
|
@ -162,7 +162,6 @@ class BasicTests(TestCase):
|
|||
"""
|
||||
Attempting to update fields set as read_only should have no effect.
|
||||
"""
|
||||
|
||||
serializer = PersonSerializer(self.person, data={'name': 'dwight', 'age': 99})
|
||||
self.assertEquals(serializer.is_valid(), True)
|
||||
instance = serializer.save()
|
||||
|
@ -183,8 +182,7 @@ class ValidationTests(TestCase):
|
|||
'content': 'x' * 1001,
|
||||
'created': datetime.datetime(2012, 1, 1)
|
||||
}
|
||||
self.actionitem = ActionItem(title='Some to do item',
|
||||
)
|
||||
self.actionitem = ActionItem(title='Some to do item',)
|
||||
|
||||
def test_create(self):
|
||||
serializer = CommentSerializer(data=self.data)
|
||||
|
@ -216,31 +214,6 @@ class ValidationTests(TestCase):
|
|||
self.assertEquals(serializer.is_valid(), True)
|
||||
self.assertEquals(serializer.errors, {})
|
||||
|
||||
def test_field_validation(self):
|
||||
|
||||
class CommentSerializerWithFieldValidator(CommentSerializer):
|
||||
|
||||
def validate_content(self, attrs, source):
|
||||
value = attrs[source]
|
||||
if "test" not in value:
|
||||
raise serializers.ValidationError("Test not in value")
|
||||
return attrs
|
||||
|
||||
data = {
|
||||
'email': 'tom@example.com',
|
||||
'content': 'A test comment',
|
||||
'created': datetime.datetime(2012, 1, 1)
|
||||
}
|
||||
|
||||
serializer = CommentSerializerWithFieldValidator(data=data)
|
||||
self.assertTrue(serializer.is_valid())
|
||||
|
||||
data['content'] = 'This should not validate'
|
||||
|
||||
serializer = CommentSerializerWithFieldValidator(data=data)
|
||||
self.assertFalse(serializer.is_valid())
|
||||
self.assertEquals(serializer.errors, {'content': [u'Test not in value']})
|
||||
|
||||
def test_bad_type_data_is_false(self):
|
||||
"""
|
||||
Data of the wrong type is not valid.
|
||||
|
@ -310,12 +283,69 @@ class ValidationTests(TestCase):
|
|||
self.assertEquals(serializer.errors, {'info': [u'Ensure this value has at most 12 characters (it has 13).']})
|
||||
|
||||
|
||||
class CustomValidationTests(TestCase):
|
||||
class CommentSerializerWithFieldValidator(CommentSerializer):
|
||||
|
||||
def validate_email(self, attrs, source):
|
||||
value = attrs[source]
|
||||
|
||||
return attrs
|
||||
|
||||
def validate_content(self, attrs, source):
|
||||
value = attrs[source]
|
||||
if "test" not in value:
|
||||
raise serializers.ValidationError("Test not in value")
|
||||
return attrs
|
||||
|
||||
def test_field_validation(self):
|
||||
data = {
|
||||
'email': 'tom@example.com',
|
||||
'content': 'A test comment',
|
||||
'created': datetime.datetime(2012, 1, 1)
|
||||
}
|
||||
|
||||
serializer = self.CommentSerializerWithFieldValidator(data=data)
|
||||
self.assertTrue(serializer.is_valid())
|
||||
|
||||
data['content'] = 'This should not validate'
|
||||
|
||||
serializer = self.CommentSerializerWithFieldValidator(data=data)
|
||||
self.assertFalse(serializer.is_valid())
|
||||
self.assertEquals(serializer.errors, {'content': [u'Test not in value']})
|
||||
|
||||
def test_missing_data(self):
|
||||
"""
|
||||
Make sure that validate_content isn't called if the field is missing
|
||||
"""
|
||||
incomplete_data = {
|
||||
'email': 'tom@example.com',
|
||||
'created': datetime.datetime(2012, 1, 1)
|
||||
}
|
||||
serializer = self.CommentSerializerWithFieldValidator(data=incomplete_data)
|
||||
self.assertFalse(serializer.is_valid())
|
||||
self.assertEquals(serializer.errors, {'content': [u'This field is required.']})
|
||||
|
||||
def test_wrong_data(self):
|
||||
"""
|
||||
Make sure that validate_content isn't called if the field input is wrong
|
||||
"""
|
||||
wrong_data = {
|
||||
'email': 'not an email',
|
||||
'content': 'A test comment',
|
||||
'created': datetime.datetime(2012, 1, 1)
|
||||
}
|
||||
serializer = self.CommentSerializerWithFieldValidator(data=wrong_data)
|
||||
self.assertFalse(serializer.is_valid())
|
||||
self.assertEquals(serializer.errors, {'email': [u'Enter a valid e-mail address.']})
|
||||
|
||||
|
||||
class PositiveIntegerAsChoiceTests(TestCase):
|
||||
def test_positive_integer_in_json_is_correctly_parsed(self):
|
||||
data = {'some_integer':1}
|
||||
data = {'some_integer': 1}
|
||||
serializer = PositiveIntegerAsChoiceSerializer(data=data)
|
||||
self.assertEquals(serializer.is_valid(), True)
|
||||
|
||||
|
||||
class ModelValidationTests(TestCase):
|
||||
def test_validate_unique(self):
|
||||
"""
|
||||
|
|
78
rest_framework/tests/urlpatterns.py
Normal file
78
rest_framework/tests/urlpatterns.py
Normal 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)
|
|
@ -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 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):
|
||||
|
@ -28,15 +58,4 @@ def format_suffix_patterns(urlpatterns, suffix_required=False, allowed=None):
|
|||
else:
|
||||
suffix_pattern = r'\.(?P<%s>[a-z]+)$' % suffix_kwarg
|
||||
|
||||
ret = []
|
||||
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
|
||||
return apply_suffix_patterns(urlpatterns, suffix_pattern, suffix_required)
|
||||
|
|
|
@ -148,6 +148,8 @@ class APIView(View):
|
|||
"""
|
||||
If request is not permitted, determine what kind of exception to raise.
|
||||
"""
|
||||
if not self.request.successful_authenticator:
|
||||
raise exceptions.NotAuthenticated()
|
||||
raise exceptions.PermissionDenied()
|
||||
|
||||
def throttled(self, request, wait):
|
||||
|
@ -156,6 +158,15 @@ class APIView(View):
|
|||
"""
|
||||
raise exceptions.Throttled(wait)
|
||||
|
||||
def get_authenticate_header(self, request):
|
||||
"""
|
||||
If a request is unauthenticated, determine the WWW-Authenticate
|
||||
header to use for 401 responses, if any.
|
||||
"""
|
||||
authenticators = self.get_authenticators()
|
||||
if authenticators:
|
||||
return authenticators[0].authenticate_header(request)
|
||||
|
||||
def get_parser_context(self, http_request):
|
||||
"""
|
||||
Returns a dict that is passed through to Parser.parse(),
|
||||
|
@ -319,6 +330,16 @@ class APIView(View):
|
|||
# Throttle wait header
|
||||
self.headers['X-Throttle-Wait-Seconds'] = '%d' % exc.wait
|
||||
|
||||
if isinstance(exc, (exceptions.NotAuthenticated,
|
||||
exceptions.AuthenticationFailed)):
|
||||
# WWW-Authenticate header for 401 responses, else coerce to 403
|
||||
auth_header = self.get_authenticate_header(self.request)
|
||||
|
||||
if auth_header:
|
||||
self.headers['WWW-Authenticate'] = auth_header
|
||||
else:
|
||||
exc.status_code = status.HTTP_403_FORBIDDEN
|
||||
|
||||
if isinstance(exc, exceptions.APIException):
|
||||
return Response({'detail': exc.detail},
|
||||
status=exc.status_code,
|
||||
|
|
Loading…
Reference in New Issue
Block a user