mirror of
https://github.com/encode/django-rest-framework.git
synced 2025-01-30 19:24:40 +03:00
Latest docs build
This commit is contained in:
parent
a7dad0da01
commit
33f1cd24cd
|
@ -186,6 +186,7 @@
|
|||
<li><a href="#django-oauth-toolkit">Django OAuth Toolkit</a></li>
|
||||
<li><a href="#django-oauth2-consumer">Django OAuth2 Consumer</a></li>
|
||||
<li><a href="#json-web-token-authentication">JSON Web Token Authentication</a></li>
|
||||
<li><a href="#http-signature-authentication">HTTP Signature Authentication</a></li>
|
||||
|
||||
<div>
|
||||
|
||||
|
@ -481,6 +482,8 @@ class ExampleAuthentication(authentication.BaseAuthentication):
|
|||
<p>The <a href="https://github.com/Rediker-Software/doac">Django OAuth2 Consumer</a> library from <a href="https://github.com/Rediker-Software">Rediker Software</a> is another package that provides <a href="https://github.com/Rediker-Software/doac/blob/master/docs/integrations.md#">OAuth 2.0 support for REST framework</a>. The package includes token scoping permissions on tokens, which allows finer-grained access to your API.</p>
|
||||
<h2 id="json-web-token-authentication">JSON Web Token Authentication</h2>
|
||||
<p>JSON Web Token is a fairly new standard which can be used for token-based authentication. Unlike the built-in TokenAuthentication scheme, JWT Authentication doesn't need to use a database to validate a token. <a href="https://github.com/GetBlimp">Blimp</a> maintains the <a href="https://github.com/GetBlimp/django-rest-framework-jwt">djangorestframework-jwt</a> package which provides a JWT Authentication class as well as a mechanism for clients to obtain a JWT given the username and password.</p>
|
||||
<h2 id="http-signature-authentication">HTTP Signature Authentication</h2>
|
||||
<p>HTTP Signature (currently a <a href="https://datatracker.ietf.org/doc/draft-cavage-http-signatures/">IETF draft</a>) provides a way to achieve origin authentication and message integrity for HTTP messages. Similar to <a href="http://docs.aws.amazon.com/general/latest/gr/signature-version-4.html">Amazon's HTTP Signature scheme</a>, used by many of its services, it permits stateless, per-request authentication. <a href="https://github.com/etoccalino/">Elvio Toccalino</a> maintains the <a href="https://github.com/etoccalino/django-rest-framework-httpsignature">djangorestframework-httpsignature</a> package which provides an easy to use HTTP Signature Authentication mechanism.</p>
|
||||
</div><!--/span-->
|
||||
</div><!--/row-->
|
||||
</div><!--/.fluid-container-->
|
||||
|
|
|
@ -207,7 +207,7 @@
|
|||
<li>Django's <code>PermissionDenied</code> exception.</li>
|
||||
</ul>
|
||||
<p>In each case, REST framework will return a response with an appropriate status code and content-type. The body of the response will include any additional details regarding the nature of the error.</p>
|
||||
<p>By default all error responses will include a key <code>details</code> in the body of the response, but other keys may also be included.</p>
|
||||
<p>By default all error responses will include a key <code>detail</code> in the body of the response, but other keys may also be included.</p>
|
||||
<p>For example, the following request:</p>
|
||||
<pre class="prettyprint lang-py"><code>DELETE http://api.example.com/foo/bar HTTP/1.1
|
||||
Accept: application/json
|
||||
|
@ -259,13 +259,13 @@ def custom_exception_handler(exc):
|
|||
<h2 id="apiexception">APIException</h2>
|
||||
<p><strong>Signature:</strong> <code>APIException()</code></p>
|
||||
<p>The <strong>base class</strong> for all exceptions raised inside REST framework.</p>
|
||||
<p>To provide a custom exception, subclass <code>APIException</code> and set the <code>.status_code</code> and <code>.detail</code> properties on the class.</p>
|
||||
<p>To provide a custom exception, subclass <code>APIException</code> and set the <code>.status_code</code> and <code>.default_detail</code> properties on the class.</p>
|
||||
<p>For example, if your API relies on a third party service that may sometimes be unreachable, you might want to implement an exception for the "503 Service Unavailable" HTTP response code. You could do this like so:</p>
|
||||
<pre class="prettyprint lang-py"><code>from rest_framework.exceptions import APIException
|
||||
|
||||
class ServiceUnavailable(APIException):
|
||||
status_code = 503
|
||||
detail = 'Service temporarily unavailable, try again later.'
|
||||
default_detail = 'Service temporarily unavailable, try again later.'
|
||||
</code></pre>
|
||||
<h2 id="parseerror">ParseError</h2>
|
||||
<p><strong>Signature:</strong> <code>ParseError(detail=None)</code></p>
|
||||
|
|
|
@ -270,6 +270,7 @@ class AccountSerializer(serializers.HyperlinkedModelSerializer):
|
|||
expired = serializers.Field(source='has_expired')
|
||||
|
||||
class Meta:
|
||||
model = Account
|
||||
fields = ('url', 'owner', 'name', 'expired')
|
||||
</code></pre>
|
||||
<p>Would produce output similar to:</p>
|
||||
|
@ -285,7 +286,7 @@ class AccountSerializer(serializers.HyperlinkedModelSerializer):
|
|||
<h2 id="writablefield">WritableField</h2>
|
||||
<p>A field that supports both read and write operations. By itself <code>WritableField</code> does not perform any translation of input values into a given type. You won't typically use this field directly, but you may want to override it and implement the <code>.to_native(self, value)</code> and <code>.from_native(self, value)</code> methods.</p>
|
||||
<h2 id="modelfield">ModelField</h2>
|
||||
<p>A generic field that can be tied to any arbitrary model field. The <code>ModelField</code> class delegates the task of serialization/deserialization to it's associated model field. This field can be used to create serializer fields for custom model fields, without having to create a new custom serializer field.</p>
|
||||
<p>A generic field that can be tied to any arbitrary model field. The <code>ModelField</code> class delegates the task of serialization/deserialization to its associated model field. This field can be used to create serializer fields for custom model fields, without having to create a new custom serializer field.</p>
|
||||
<p>The <code>ModelField</code> class is generally intended for internal use, but can be used by your API if needed. In order to properly instantiate a <code>ModelField</code>, it must be passed a field that is attached to an instantiated model. For example: <code>ModelField(model_field=MyModel()._meta.get_field('custom_field'))</code></p>
|
||||
<p><strong>Signature:</strong> <code>ModelField(model_field=<Django ModelField instance>)</code></p>
|
||||
<h2 id="serializermethodfield">SerializerMethodField</h2>
|
||||
|
@ -400,7 +401,7 @@ Django's regular <a href="https://docs.djangoproject.com/en/dev/ref/settings/#st
|
|||
<hr />
|
||||
<h1 id="custom-fields">Custom fields</h1>
|
||||
<p>If you want to create a custom field, you'll probably want to override either one or both of the <code>.to_native()</code> and <code>.from_native()</code> methods. These two methods are used to convert between the initial datatype, and a primitive, serializable datatype. Primitive datatypes may be any of a number, string, date/time/datetime or None. They may also be any list or dictionary like object that only contains other primitive objects.</p>
|
||||
<p>The <code>.to_native()</code> method is called to convert the initial datatype into a primitive, serializable datatype. The <code>from_native()</code> method is called to restore a primitive datatype into it's initial representation.</p>
|
||||
<p>The <code>.to_native()</code> method is called to convert the initial datatype into a primitive, serializable datatype. The <code>from_native()</code> method is called to restore a primitive datatype into its initial representation.</p>
|
||||
<h2 id="examples">Examples</h2>
|
||||
<p>Let's look at an example of serializing a class that represents an RGB color value:</p>
|
||||
<pre class="prettyprint lang-py"><code>class Color(object):
|
||||
|
|
|
@ -299,7 +299,7 @@ class UserList(generics.ListCreateAPIView):
|
|||
self.check_object_permissions(self.request, obj)
|
||||
return obj
|
||||
</code></pre>
|
||||
<p>Note that if your API doesn't include any object level permissions, you may optionally exclude the <code>`self.check_object_permissions, and simply return the object from the</code>get_object_or_404` lookup.</p>
|
||||
<p>Note that if your API doesn't include any object level permissions, you may optionally exclude the <code>self.check_object_permissions</code>, and simply return the object from the <code>get_object_or_404</code> lookup.</p>
|
||||
<h4 id="get_filter_backendsself"><code>get_filter_backends(self)</code></h4>
|
||||
<p>Returns the classes that should be used to filter the queryset. Defaults to returning the <code>filter_backends</code> attribute.</p>
|
||||
<p>May be override to provide more complex behavior with filters, as using different (or even exlusive) lists of filter_backends depending on different criteria.</p>
|
||||
|
|
|
@ -6,7 +6,7 @@
|
|||
<link href="http://www.django-rest-framework.org/img/favicon.ico" rel="icon" type="image/x-icon">
|
||||
<link rel="canonical" href="http://www.django-rest-framework.org/api-guide/pagination"/>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<meta name="description" content="Django, API, REST, Pagination, Custom pagination serializers">
|
||||
<meta name="description" content="Django, API, REST, Pagination, Custom pagination serializers, Third party packages">
|
||||
<meta name="author" content="Tom Christie">
|
||||
|
||||
<!-- Le styles -->
|
||||
|
@ -175,6 +175,8 @@
|
|||
<li class="main"><a href="#custom-pagination-serializers">Custom pagination serializers</a></li>
|
||||
<li><a href="#example">Example</a></li>
|
||||
<li><a href="#using-your-custom-pagination-serializer">Using your custom pagination serializer</a></li>
|
||||
<li class="main"><a href="#third-party-packages">Third party packages</a></li>
|
||||
<li><a href="#drf-extensions">DRF-extensions</a></li>
|
||||
|
||||
<div>
|
||||
|
||||
|
@ -309,6 +311,10 @@ class CustomPaginationSerializer(pagination.BasePaginationSerializer):
|
|||
pagination_serializer_class = CustomPaginationSerializer
|
||||
paginate_by = 10
|
||||
</code></pre>
|
||||
<h1 id="third-party-packages">Third party packages</h1>
|
||||
<p>The following third party packages are also available.</p>
|
||||
<h2 id="drf-extensions">DRF-extensions</h2>
|
||||
<p>The <a href="http://chibisov.github.io/drf-extensions/docs/"><code>DRF-extensions</code> package</a> includes a <a href="http://chibisov.github.io/drf-extensions/docs/#paginatebymaxmixin"><code>PaginateByMaxMixin</code> mixin class</a> that allows your API clients to specify <code>?page_size=max</code> to obtain the maximum allowed page size.</p>
|
||||
</div><!--/span-->
|
||||
</div><!--/row-->
|
||||
</div><!--/.fluid-container-->
|
||||
|
|
|
@ -503,14 +503,14 @@ The <code>ModelSerializer</code> class lets you automatically create a Serialize
|
|||
fields = ('email', 'username', 'password')
|
||||
write_only_fields = ('password',) # Note: Password field is write-only
|
||||
|
||||
def restore_object(self, attrs, instance=None):
|
||||
"""
|
||||
Instantiate a new User instance.
|
||||
"""
|
||||
assert instance is None, 'Cannot update users with CreateUserSerializer'
|
||||
user = User(email=attrs['email'], username=attrs['username'])
|
||||
user.set_password(attrs['password'])
|
||||
return user
|
||||
def restore_object(self, attrs, instance=None):
|
||||
"""
|
||||
Instantiate a new User instance.
|
||||
"""
|
||||
assert instance is None, 'Cannot update users with CreateUserSerializer'
|
||||
user = User(email=attrs['email'], username=attrs['username'])
|
||||
user.set_password(attrs['password'])
|
||||
return user
|
||||
</code></pre>
|
||||
<h2 id="specifying-fields-explicitly">Specifying fields explicitly</h2>
|
||||
<p>You can add extra fields to a <code>ModelSerializer</code> or override the default fields by declaring fields on the class, just as you would for a <code>Serializer</code> class.</p>
|
||||
|
|
|
@ -357,11 +357,11 @@ class AccountTests(APITestCase):
|
|||
<h1 id="testing-responses">Testing responses</h1>
|
||||
<h2 id="checking-the-response-data">Checking the response data</h2>
|
||||
<p>When checking the validity of test responses it's often more convenient to inspect the data that the response was created with, rather than inspecting the fully rendered response.</p>
|
||||
<p>For example, it's easier to inspect <code>request.data</code>:</p>
|
||||
<p>For example, it's easier to inspect <code>response.data</code>:</p>
|
||||
<pre class="prettyprint lang-py"><code>response = self.client.get('/users/4/')
|
||||
self.assertEqual(response.data, {'id': 4, 'username': 'lauren'})
|
||||
</code></pre>
|
||||
<p>Instead of inspecting the result of parsing <code>request.content</code>:</p>
|
||||
<p>Instead of inspecting the result of parsing <code>response.content</code>:</p>
|
||||
<pre class="prettyprint lang-py"><code>response = self.client.get('/users/4/')
|
||||
self.assertEqual(json.loads(response.content), {'id': 4, 'username': 'lauren'})
|
||||
</code></pre>
|
||||
|
|
|
@ -307,7 +307,7 @@ class UploadView(APIView):
|
|||
<p>...and the following settings.</p>
|
||||
<pre class="prettyprint lang-py"><code>REST_FRAMEWORK = {
|
||||
'DEFAULT_THROTTLE_CLASSES': (
|
||||
'rest_framework.throttling.ScopedRateThrottle'
|
||||
'rest_framework.throttling.ScopedRateThrottle',
|
||||
),
|
||||
'DEFAULT_THROTTLE_RATES': {
|
||||
'contacts': '1000/day',
|
||||
|
|
|
@ -372,7 +372,7 @@ class UserViewSet(viewsets.ModelViewSet):
|
|||
mixins.RetrieveModelMixin,
|
||||
viewsets.GenericViewSet):
|
||||
"""
|
||||
A viewset that provides `retrieve`, `update`, and `list` actions.
|
||||
A viewset that provides `retrieve`, `create`, and `list` actions.
|
||||
|
||||
To use it, override the class and set the `.queryset` and
|
||||
`.serializer_class` attributes.
|
||||
|
|
|
@ -239,7 +239,7 @@
|
|||
<p>To run the tests, clone the repository, and then:</p>
|
||||
<pre class="prettyprint lang-py"><code># Setup the virtual environment
|
||||
virtualenv env
|
||||
env/bin/activate
|
||||
source env/bin/activate
|
||||
pip install -r requirements.txt
|
||||
pip install -r optionals.txt
|
||||
|
||||
|
|
|
@ -366,6 +366,7 @@
|
|||
<li>Ian Foote - <a href="https://github.com/ian-foote">ian-foote</a></li>
|
||||
<li>Chuck Harmston - <a href="https://github.com/chuckharmston">chuckharmston</a></li>
|
||||
<li>Philip Forget - <a href="https://github.com/philipforget">philipforget</a></li>
|
||||
<li>Artem Mezhenin - <a href="https://github.com/amezhenin">amezhenin</a></li>
|
||||
</ul>
|
||||
<p>Many thanks to everyone who's contributed to the project.</p>
|
||||
<h2 id="additional-thanks">Additional thanks</h2>
|
||||
|
|
Loading…
Reference in New Issue
Block a user