mirror of
https://github.com/encode/django-rest-framework.git
synced 2024-11-23 10:03:57 +03:00
Merge pull request #898 from minddust/fix_md_format
Fix md formatting and typos
This commit is contained in:
commit
100a168a0b
|
@ -86,7 +86,7 @@ Note that when a request may successfully authenticate, but still be denied perm
|
|||
|
||||
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'`.
|
||||
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
|
||||
|
@ -216,9 +216,9 @@ If you're using an AJAX style API with SessionAuthentication, you'll need to mak
|
|||
|
||||
## OAuthAuthentication
|
||||
|
||||
This authentication uses [OAuth 1.0a][oauth-1.0a] authentication scheme. OAuth 1.0a provides signature validation which provides a reasonable level of security over plain non-HTTPS connections. However, it may also be considered more complicated than OAuth2, as it requires clients to sign their requests.
|
||||
This authentication uses [OAuth 1.0a][oauth-1.0a] authentication scheme. OAuth 1.0a provides signature validation which provides a reasonable level of security over plain non-HTTPS connections. However, it may also be considered more complicated than OAuth2, as it requires clients to sign their requests.
|
||||
|
||||
This authentication class depends on the optional `django-oauth-plus` and `oauth2` packages. In order to make it work you must install these packages and add `oauth_provider` to your `INSTALLED_APPS`:
|
||||
This authentication class depends on the optional `django-oauth-plus` and `oauth2` packages. In order to make it work you must install these packages and add `oauth_provider` to your `INSTALLED_APPS`:
|
||||
|
||||
INSTALLED_APPS = (
|
||||
...
|
||||
|
@ -231,7 +231,7 @@ Don't forget to run `syncdb` once you've added the package.
|
|||
|
||||
#### Getting started with django-oauth-plus
|
||||
|
||||
The OAuthAuthentication class only provides token verification and signature validation for requests. It doesn't provide authorization flow for your clients. You still need to implement your own views for accessing and authorizing tokens.
|
||||
The OAuthAuthentication class only provides token verification and signature validation for requests. It doesn't provide authorization flow for your clients. You still need to implement your own views for accessing and authorizing tokens.
|
||||
|
||||
The `django-oauth-plus` package provides simple foundation for classic 'three-legged' oauth flow. Please refer to [the documentation][django-oauth-plus] for more details.
|
||||
|
||||
|
@ -239,7 +239,7 @@ The `django-oauth-plus` package provides simple foundation for classic 'three-le
|
|||
|
||||
This authentication uses [OAuth 2.0][rfc6749] authentication scheme. OAuth2 is more simple to work with than OAuth1, and provides much better security than simple token authentication. It is an unauthenticated scheme, and requires you to use an HTTPS connection.
|
||||
|
||||
This authentication class depends on the optional [django-oauth2-provider][django-oauth2-provider] project. In order to make it work you must install this package and add `provider` and `provider.oauth2` to your `INSTALLED_APPS`:
|
||||
This authentication class depends on the optional [django-oauth2-provider][django-oauth2-provider] project. In order to make it work you must install this package and add `provider` and `provider.oauth2` to your `INSTALLED_APPS`:
|
||||
|
||||
INSTALLED_APPS = (
|
||||
...
|
||||
|
@ -266,9 +266,9 @@ Finally, sync your database.
|
|||
|
||||
#### Getting started with django-oauth2-provider
|
||||
|
||||
The `OAuth2Authentication` class only provides token verification for requests. It doesn't provide authorization flow for your clients.
|
||||
The `OAuth2Authentication` class only provides token verification for requests. It doesn't provide authorization flow for your clients.
|
||||
|
||||
The OAuth 2 authorization flow is taken care by the [django-oauth2-provider][django-oauth2-provider] dependency. A walkthrough is given here, but for more details you should refer to [the documentation][django-oauth2-provider-docs].
|
||||
The OAuth 2 authorization flow is taken care by the [django-oauth2-provider][django-oauth2-provider] dependency. A walkthrough is given here, but for more details you should refer to [the documentation][django-oauth2-provider-docs].
|
||||
|
||||
To get started:
|
||||
|
||||
|
@ -276,7 +276,7 @@ To get started:
|
|||
|
||||
You can create a client, either through the shell, or by using the Django admin.
|
||||
|
||||
Go to the admin panel and create a new `Provider.Client` entry. It will create the `client_id` and `client_secret` properties for you.
|
||||
Go to the admin panel and create a new `Provider.Client` entry. It will create the `client_id` and `client_secret` properties for you.
|
||||
|
||||
##### 2. Request an access token
|
||||
|
||||
|
|
|
@ -16,7 +16,7 @@ Serializer fields handle converting between primitive values and internal dataty
|
|||
|
||||
## Core arguments
|
||||
|
||||
Each serializer field class constructor takes at least these arguments. Some Field classes take additional, field-specific arguments, but the following should always be accepted:
|
||||
Each serializer field class constructor takes at least these arguments. Some Field classes take additional, field-specific arguments, but the following should always be accepted:
|
||||
|
||||
### `source`
|
||||
|
||||
|
@ -119,7 +119,7 @@ A generic field that can be tied to any arbitrary model field. The `ModelField`
|
|||
|
||||
## SerializerMethodField
|
||||
|
||||
This is a read-only field. It gets its value by calling a method on the serializer class it is attached to. It can be used to add any sort of data to the serialized representation of your object. The field's constructor accepts a single argument, which is the name of the method on the serializer to be called. The method should accept a single argument (in addition to `self`), which is the object being serialized. It should return whatever you want to be included in the serialized representation of the object. For example:
|
||||
This is a read-only field. It gets its value by calling a method on the serializer class it is attached to. It can be used to add any sort of data to the serialized representation of your object. The field's constructor accepts a single argument, which is the name of the method on the serializer to be called. The method should accept a single argument (in addition to `self`), which is the object being serialized. It should return whatever you want to be included in the serialized representation of the object. For example:
|
||||
|
||||
from rest_framework import serializers
|
||||
from django.contrib.auth.models import User
|
||||
|
@ -158,7 +158,7 @@ or `django.db.models.fields.TextField`.
|
|||
|
||||
## URLField
|
||||
|
||||
Corresponds to `django.db.models.fields.URLField`. Uses Django's `django.core.validators.URLValidator` for validation.
|
||||
Corresponds to `django.db.models.fields.URLField`. Uses Django's `django.core.validators.URLValidator` for validation.
|
||||
|
||||
**Signature:** `CharField(max_length=200, min_length=None)`
|
||||
|
||||
|
@ -211,9 +211,9 @@ In the case of JSON this means the default datetime representation uses the [ECM
|
|||
**Signature:** `DateTimeField(format=None, input_formats=None)`
|
||||
|
||||
* `format` - A string representing the output format. If not specified, this defaults to `None`, which indicates that python `datetime` objects should be returned by `to_native`. In this case the datetime encoding will be determined by the renderer.
|
||||
* `input_formats` - A list of strings representing the input formats which may be used to parse the date. If not specified, the `DATETIME_INPUT_FORMATS` setting will be used, which defaults to `['iso-8601']`.
|
||||
* `input_formats` - A list of strings representing the input formats which may be used to parse the date. If not specified, the `DATETIME_INPUT_FORMATS` setting will be used, which defaults to `['iso-8601']`.
|
||||
|
||||
DateTime format strings may either be [python strftime formats][strftime] which explicitly specifiy the format, or the special string `'iso-8601'`, which indicates that [ISO 8601][iso8601] style datetimes should be used. (eg `'2013-01-29T12:34:56.000000Z'`)
|
||||
DateTime format strings may either be [python strftime formats][strftime] which explicitly specify the format, or the special string `'iso-8601'`, which indicates that [ISO 8601][iso8601] style datetimes should be used. (eg `'2013-01-29T12:34:56.000000Z'`)
|
||||
|
||||
## DateField
|
||||
|
||||
|
@ -224,7 +224,7 @@ Corresponds to `django.db.models.fields.DateField`
|
|||
**Signature:** `DateField(format=None, input_formats=None)`
|
||||
|
||||
* `format` - A string representing the output format. If not specified, this defaults to `None`, which indicates that python `date` objects should be returned by `to_native`. In this case the date encoding will be determined by the renderer.
|
||||
* `input_formats` - A list of strings representing the input formats which may be used to parse the date. If not specified, the `DATE_INPUT_FORMATS` setting will be used, which defaults to `['iso-8601']`.
|
||||
* `input_formats` - A list of strings representing the input formats which may be used to parse the date. If not specified, the `DATE_INPUT_FORMATS` setting will be used, which defaults to `['iso-8601']`.
|
||||
|
||||
Date format strings may either be [python strftime formats][strftime] which explicitly specify the format, or the special string `'iso-8601'`, which indicates that [ISO 8601][iso8601] style dates should be used. (eg `'2013-01-29'`)
|
||||
|
||||
|
@ -239,9 +239,9 @@ Corresponds to `django.db.models.fields.TimeField`
|
|||
**Signature:** `TimeField(format=None, input_formats=None)`
|
||||
|
||||
* `format` - A string representing the output format. If not specified, this defaults to `None`, which indicates that python `time` objects should be returned by `to_native`. In this case the time encoding will be determined by the renderer.
|
||||
* `input_formats` - A list of strings representing the input formats which may be used to parse the date. If not specified, the `TIME_INPUT_FORMATS` setting will be used, which defaults to `['iso-8601']`.
|
||||
* `input_formats` - A list of strings representing the input formats which may be used to parse the date. If not specified, the `TIME_INPUT_FORMATS` setting will be used, which defaults to `['iso-8601']`.
|
||||
|
||||
Time format strings may either be [python strftime formats][strftime] which explicitly specifiy the format, or the special string `'iso-8601'`, which indicates that [ISO 8601][iso8601] style times should be used. (eg `'12:34:56.000000'`)
|
||||
Time format strings may either be [python strftime formats][strftime] which explicitly specify the format, or the special string `'iso-8601'`, which indicates that [ISO 8601][iso8601] style times should be used. (eg `'12:34:56.000000'`)
|
||||
|
||||
## IntegerField
|
||||
|
||||
|
@ -263,7 +263,7 @@ Corresponds to `django.db.models.fields.DecimalField`.
|
|||
|
||||
## FileField
|
||||
|
||||
A file representation. Performs Django's standard FileField validation.
|
||||
A file representation. Performs Django's standard FileField validation.
|
||||
|
||||
Corresponds to `django.forms.fields.FileField`.
|
||||
|
||||
|
@ -292,7 +292,7 @@ Django's regular [FILE_UPLOAD_HANDLERS] are used for handling uploaded files.
|
|||
|
||||
# Custom fields
|
||||
|
||||
If you want to create a custom field, you'll probably want to override either one or both of the `.to_native()` and `.from_native()` methods. These two methods are used to convert between the intial datatype, and a primative, serializable datatype. Primative 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 primative objects.
|
||||
If you want to create a custom field, you'll probably want to override either one or both of the `.to_native()` and `.from_native()` methods. These two methods are used to convert between the initial datatype, and a primative, serializable datatype. Primative 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 primative objects.
|
||||
|
||||
The `.to_native()` method is called to convert the initial datatype into a primative, serializable datatype. The `from_native()` method is called to restore a primative datatype into it's initial representation.
|
||||
|
||||
|
|
|
@ -2,7 +2,7 @@
|
|||
|
||||
# Filtering
|
||||
|
||||
> The root QuerySet provided by the Manager describes all objects in the database table. Usually, though, you'll need to select only a subset of the complete set of objects.
|
||||
> The root QuerySet provided by the Manager describes all objects in the database table. Usually, though, you'll need to select only a subset of the complete set of objects.
|
||||
>
|
||||
> — [Django documentation][cite]
|
||||
|
||||
|
|
|
@ -58,11 +58,11 @@ Also note that `format_suffix_patterns` does not support descending into `includ
|
|||
|
||||
## Accept headers vs. format suffixes
|
||||
|
||||
There seems to be a view among some of the Web community that filename extensions are not a RESTful pattern, and that `HTTP Accept` headers should always be used instead.
|
||||
There seems to be a view among some of the Web community that filename extensions are not a RESTful pattern, and that `HTTP Accept` headers should always be used instead.
|
||||
|
||||
It is actually a misconception. For example, take the following quote from Roy Fielding discussing the relative merits of query parameter media-type indicators vs. file extension media-type indicators:
|
||||
|
||||
“That's why I always prefer extensions. Neither choice has anything to do with REST.” — Roy Fielding, [REST discuss mailing list][cite2]
|
||||
“That's why I always prefer extensions. Neither choice has anything to do with REST.” — Roy Fielding, [REST discuss mailing list][cite2]
|
||||
|
||||
The quote does not mention Accept headers, but it does make it clear that format suffixes should be considered an acceptable pattern.
|
||||
|
||||
|
|
|
@ -2,7 +2,7 @@
|
|||
|
||||
# Permissions
|
||||
|
||||
> Authentication or identification by itself is not usually sufficient to gain access to information or code. For that, the entity requesting access must have authorization.
|
||||
> Authentication or identification by itself is not usually sufficient to gain access to information or code. For that, the entity requesting access must have authorization.
|
||||
>
|
||||
> — [Apple Developer Documentation][cite]
|
||||
|
||||
|
@ -147,7 +147,7 @@ If you need to test if a request is a read operation or a write operation, you s
|
|||
|
||||
**Note**: In versions 2.0 and 2.1, the signature for the permission checks always included an optional `obj` parameter, like so: `.has_permission(self, request, view, obj=None)`. The method would be called twice, first for the global permission checks, with no object supplied, and second for the object-level check when required.
|
||||
|
||||
As of version 2.2 this signature has now been replaced with two seperate method calls, which is more explict and obvious. The old style signature continues to work, but it's use will result in a `PendingDeprecationWarning`, which is silent by default. In 2.3 this will be escalated to a `DeprecationWarning`, and in 2.4 the old-style signature will be removed.
|
||||
As of version 2.2 this signature has now been replaced with two separate method calls, which is more explict and obvious. The old style signature continues to work, but it's use will result in a `PendingDeprecationWarning`, which is silent by default. In 2.3 this will be escalated to a `DeprecationWarning`, and in 2.4 the old-style signature will be removed.
|
||||
|
||||
For more details see the [2.2 release announcement][2.2-announcement].
|
||||
|
||||
|
|
|
@ -138,7 +138,7 @@ By default this field is read-write, although you can change this behavior using
|
|||
* `many` - If applied to a to-many relationship, you should set this argument to `True`.
|
||||
* `required` - If set to `False`, the field will accept values of `None` or the empty-string for nullable relationships.
|
||||
* `queryset` - By default `ModelSerializer` classes will use the default queryset for the relationship. `Serializer` classes must either set a queryset explicitly, or set `read_only=True`.
|
||||
* `lookup_field` - The field on the target that should be used for the lookup. Should correspond to a URL keyword argument on the referenced view. Default is `'pk'`.
|
||||
* `lookup_field` - The field on the target that should be used for the lookup. Should correspond to a URL keyword argument on the referenced view. Default is `'pk'`.
|
||||
* `format` - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the `format` argument.
|
||||
|
||||
## SlugRelatedField
|
||||
|
@ -202,7 +202,7 @@ This field is always read-only.
|
|||
**Arguments**:
|
||||
|
||||
* `view_name` - The view name that should be used as the target of the relationship. **required**.
|
||||
* `lookup_field` - The field on the target that should be used for the lookup. Should correspond to a URL keyword argument on the referenced view. Default is `'pk'`.
|
||||
* `lookup_field` - The field on the target that should be used for the lookup. Should correspond to a URL keyword argument on the referenced view. Default is `'pk'`.
|
||||
* `format` - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the `format` argument.
|
||||
|
||||
---
|
||||
|
|
|
@ -233,13 +233,13 @@ The request data, as set by the `Response()` instantiation.
|
|||
|
||||
### `media_type=None`
|
||||
|
||||
Optional. If provided, this is the accepted media type, as determined by the content negotiation stage.
|
||||
Optional. If provided, this is the accepted media type, as determined by the content negotiation stage.
|
||||
|
||||
Depending on the client's `Accept:` header, this may be more specific than the renderer's `media_type` attribute, and may include media type parameters. For example `"application/json; nested=true"`.
|
||||
|
||||
### `renderer_context=None`
|
||||
|
||||
Optional. If provided, this is a dictionary of contextual information provided by the view.
|
||||
Optional. If provided, this is a dictionary of contextual information provided by the view.
|
||||
|
||||
By default this will include the following keys: `view`, `request`, `response`, `args`, `kwargs`.
|
||||
|
||||
|
@ -325,7 +325,7 @@ For example:
|
|||
In some cases you might want a renderer to serve a range of media types.
|
||||
In this case you can underspecify the media types it should respond to, by using a `media_type` value such as `image/*`, or `*/*`.
|
||||
|
||||
If you underspecify the renderer's media type, you should make sure to specify the media type explictly when you return the response, using the `content_type` attribute. For example:
|
||||
If you underspecify the renderer's media type, you should make sure to specify the media type explicitly when you return the response, using the `content_type` attribute. For example:
|
||||
|
||||
return Response(data, content_type='image/png')
|
||||
|
||||
|
|
|
@ -2,7 +2,7 @@
|
|||
|
||||
# Responses
|
||||
|
||||
> Unlike basic HttpResponse objects, TemplateResponse objects retain the details of the context that was provided by the view to compute the response. The final output of the response is not computed until it is needed, later in the response process.
|
||||
> Unlike basic HttpResponse objects, TemplateResponse objects retain the details of the context that was provided by the view to compute the response. The final output of the response is not computed until it is needed, later in the response process.
|
||||
>
|
||||
> — [Django documentation][cite]
|
||||
|
||||
|
|
|
@ -2,7 +2,7 @@
|
|||
|
||||
# Routers
|
||||
|
||||
> Resource routing allows you to quickly declare all of the common routes for a given resourceful controller. Instead of declaring separate routes for your index... a resourceful route declares them in a single line of code.
|
||||
> Resource routing allows you to quickly declare all of the common routes for a given resourceful controller. Instead of declaring separate routes for your index... a resourceful route declares them in a single line of code.
|
||||
>
|
||||
> — [Ruby on Rails Documentation][cite]
|
||||
|
||||
|
|
|
@ -3,7 +3,7 @@
|
|||
# Serializers
|
||||
|
||||
> Expanding the usefulness of the serializers is something that we would
|
||||
like to address. However, it's not a trivial problem, and it
|
||||
like to address. However, it's not a trivial problem, and it
|
||||
will take some serious design work.
|
||||
>
|
||||
> — Russell Keith-Magee, [Django users group][cite]
|
||||
|
@ -104,11 +104,11 @@ When deserializing a list of items, errors will be returned as a list of diction
|
|||
|
||||
#### Field-level validation
|
||||
|
||||
You can specify custom field-level validation by adding `.validate_<fieldname>` methods to your `Serializer` subclass. These are analogous to `.clean_<fieldname>` methods on Django forms, but accept slightly different arguments.
|
||||
You can specify custom field-level validation by adding `.validate_<fieldname>` methods to your `Serializer` subclass. These are analogous to `.clean_<fieldname>` methods on Django forms, but accept slightly different arguments.
|
||||
|
||||
They take a dictionary of deserialized attributes as a first argument, and the field name in that dictionary as a second argument (which will be either the name of the field or the value of the `source` argument to the field, if one was provided).
|
||||
|
||||
Your `validate_<fieldname>` methods should either just return the `attrs` dictionary or raise a `ValidationError`. For example:
|
||||
Your `validate_<fieldname>` methods should either just return the `attrs` dictionary or raise a `ValidationError`. For example:
|
||||
|
||||
from rest_framework import serializers
|
||||
|
||||
|
@ -127,7 +127,7 @@ Your `validate_<fieldname>` methods should either just return the `attrs` dictio
|
|||
|
||||
#### Object-level validation
|
||||
|
||||
To do any other validation that requires access to multiple fields, add a method called `.validate()` to your `Serializer` subclass. This method takes a single argument, which is the `attrs` dictionary. It should raise a `ValidationError` if necessary, or just return `attrs`. For example:
|
||||
To do any other validation that requires access to multiple fields, add a method called `.validate()` to your `Serializer` subclass. This method takes a single argument, which is the `attrs` dictionary. It should raise a `ValidationError` if necessary, or just return `attrs`. For example:
|
||||
|
||||
from rest_framework import serializers
|
||||
|
||||
|
@ -285,7 +285,7 @@ To map the incoming data items to their corresponding object instances, the `.ge
|
|||
|
||||
There are some cases where you need to provide extra context to the serializer in addition to the object being serialized. One common case is if you're using a serializer that includes hyperlinked relations, which requires the serializer to have access to the current request so that it can properly generate fully qualified URLs.
|
||||
|
||||
You can provide arbitrary additional context by passing a `context` argument when instantiating the serializer. For example:
|
||||
You can provide arbitrary additional context by passing a `context` argument when instantiating the serializer. For example:
|
||||
|
||||
serializer = AccountSerializer(account, context={'request': request})
|
||||
serializer.data
|
||||
|
@ -333,7 +333,7 @@ The `depth` option should be set to an integer value that indicates the depth of
|
|||
|
||||
## Specifying which fields should be read-only
|
||||
|
||||
You may wish to specify multiple fields as read-only. Instead of adding each field explicitly with the `read_only=True` attribute, you may use the `read_only_fields` Meta option, like so:
|
||||
You may wish to specify multiple fields as read-only. Instead of adding each field explicitly with the `read_only=True` attribute, you may use the `read_only_fields` Meta option, like so:
|
||||
|
||||
class AccountSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
|
@ -425,7 +425,7 @@ Doing so should be considered advanced usage, and will only be needed if you hav
|
|||
|
||||
The `field_mapping` attribute is a dictionary that maps model classes to serializer classes. Overriding the attribute will let you set a different set of default serializer classes.
|
||||
|
||||
For more advanced customization than simply changing the default serializer class you can override various `get_<field_type>_field` methods. Doing so will allow you to customize the arguments that each serializer field is initialized with. Each of these methods may either return a field or serializer instance, or `None`.
|
||||
For more advanced customization than simply changing the default serializer class you can override various `get_<field_type>_field` methods. Doing so will allow you to customize the arguments that each serializer field is initialized with. Each of these methods may either return a field or serializer instance, or `None`.
|
||||
|
||||
### get_pk_field
|
||||
|
||||
|
|
|
@ -2,7 +2,7 @@
|
|||
|
||||
# Status Codes
|
||||
|
||||
> 418 I'm a teapot - Any attempt to brew coffee with a teapot should result in the error code "418 I'm a teapot". The resulting entity body MAY be short and stout.
|
||||
> 418 I'm a teapot - Any attempt to brew coffee with a teapot should result in the error code "418 I'm a teapot". The resulting entity body MAY be short and stout.
|
||||
>
|
||||
> — [RFC 2324][rfc2324], Hyper Text Coffee Pot Control Protocol
|
||||
|
||||
|
@ -53,7 +53,7 @@ This class of status code indicates that further action needs to be taken by the
|
|||
|
||||
## Client Error - 4xx
|
||||
|
||||
The 4xx class of status code is intended for cases in which the client seems to have erred. Except when responding to a HEAD request, the server SHOULD include an entity containing an explanation of the error situation, and whether it is a temporary or permanent condition.
|
||||
The 4xx class of status code is intended for cases in which the client seems to have erred. Except when responding to a HEAD request, the server SHOULD include an entity containing an explanation of the error situation, and whether it is a temporary or permanent condition.
|
||||
|
||||
HTTP_400_BAD_REQUEST
|
||||
HTTP_401_UNAUTHORIZED
|
||||
|
@ -79,7 +79,7 @@ The 4xx class of status code is intended for cases in which the client seems to
|
|||
|
||||
## Server Error - 5xx
|
||||
|
||||
Response status codes beginning with the digit "5" indicate cases in which the server is aware that it has erred or is incapable of performing the request. Except when responding to a HEAD request, the server SHOULD include an entity containing an explanation of the error situation, and whether it is a temporary or permanent condition.
|
||||
Response status codes beginning with the digit "5" indicate cases in which the server is aware that it has erred or is incapable of performing the request. Except when responding to a HEAD request, the server SHOULD include an entity containing an explanation of the error situation, and whether it is a temporary or permanent condition.
|
||||
|
||||
HTTP_500_INTERNAL_SERVER_ERROR
|
||||
HTTP_501_NOT_IMPLEMENTED
|
||||
|
|
|
@ -122,13 +122,13 @@ You won't typically need to override this method.
|
|||
>
|
||||
> — [Nick Coghlan][cite2]
|
||||
|
||||
REST framework also allows you to work with regular function based views. It provides a set of simple decorators that wrap your function based views to ensure they receive an instance of `Request` (rather than the usual Django `HttpRequest`) and allows them to return a `Response` (instead of a Django `HttpResponse`), and allow you to configure how the request is processed.
|
||||
REST framework also allows you to work with regular function based views. It provides a set of simple decorators that wrap your function based views to ensure they receive an instance of `Request` (rather than the usual Django `HttpRequest`) and allows them to return a `Response` (instead of a Django `HttpResponse`), and allow you to configure how the request is processed.
|
||||
|
||||
## @api_view()
|
||||
|
||||
**Signature:** `@api_view(http_method_names)`
|
||||
|
||||
The core of this functionality is the `api_view` decorator, which takes a list of HTTP methods that your view should respond to. For example, this is how you would write a very simple view that just manually returns some data:
|
||||
The core of this functionality is the `api_view` decorator, which takes a list of HTTP methods that your view should respond to. For example, this is how you would write a very simple view that just manually returns some data:
|
||||
|
||||
from rest_framework.decorators import api_view
|
||||
|
||||
|
@ -141,7 +141,7 @@ This view will use the default renderers, parsers, authentication classes etc sp
|
|||
|
||||
## API policy decorators
|
||||
|
||||
To override the default settings, REST framework provides a set of additional decorators which can be added to your views. These must come *after* (below) the `@api_view` decorator. For example, to create a view that uses a [throttle](throttling) to ensure it can only be called once per day by a particular user, use the `@throttle_classes` decorator, passing a list of throttle classes:
|
||||
To override the default settings, REST framework provides a set of additional decorators which can be added to your views. These must come *after* (below) the `@api_view` decorator. For example, to create a view that uses a [throttle](throttling) to ensure it can only be called once per day by a particular user, use the `@throttle_classes` decorator, passing a list of throttle classes:
|
||||
|
||||
from rest_framework.decorators import api_view, throttle_classes
|
||||
from rest_framework.throttling import UserRateThrottle
|
||||
|
|
|
@ -15,7 +15,7 @@ Django REST framework is a powerful and flexible toolkit that makes it easy to b
|
|||
|
||||
Some reasons you might want to use REST framework:
|
||||
|
||||
* The Web browseable API is a huge useability win for your developers.
|
||||
* The Web browseable API is a huge usability win for your developers.
|
||||
* Authentication policies including OAuth1a and OAuth2 out of the box.
|
||||
* Serialization that supports both ORM and non-ORM data sources.
|
||||
* Customizable all the way down - just use regular function-based views if you don't need the more powerful features.
|
||||
|
|
|
@ -45,7 +45,7 @@ The best place to get started with ViewSets and Routers is to take a look at the
|
|||
|
||||
## Simpler views
|
||||
|
||||
This release rationalises the API and implementation of the generic views, dropping the dependancy on Django's `SingleObjectMixin` and `MultipleObjectMixin` classes, removing a number of unneeded attributes, and generally making the implementation more obvious and easy to work with.
|
||||
This release rationalises the API and implementation of the generic views, dropping the dependency on Django's `SingleObjectMixin` and `MultipleObjectMixin` classes, removing a number of unneeded attributes, and generally making the implementation more obvious and easy to work with.
|
||||
|
||||
This improvement is reflected in improved documentation for the `GenericAPIView` base class, and should make it easier to determine how to override methods on the base class if you need to write customized subclasses.
|
||||
|
||||
|
@ -108,7 +108,7 @@ Using the `SingleObjectAPIView` and `MultipleObjectAPIView` base classes continu
|
|||
|
||||
### Removed attributes
|
||||
|
||||
The following attributes and methods, were previously present as part of Django's generic view implementations, but were unneeded and unusedand have now been entirely removed.
|
||||
The following attributes and methods, were previously present as part of Django's generic view implementations, but were unneeded and unused and have now been entirely removed.
|
||||
|
||||
* context_object_name
|
||||
* get_context_data()
|
||||
|
@ -173,7 +173,7 @@ For example:
|
|||
raise Http404
|
||||
return queryset
|
||||
|
||||
In our opinion removing lesser-used attributes like `allow_empty` helps us move towards simpler generic view implementations, making them more obvious to use and override, and re-inforcing the preferred style of developers writing their own base classes and mixins for custom behavior rather than relying on the configurability of the generic views.
|
||||
In our opinion removing lesser-used attributes like `allow_empty` helps us move towards simpler generic view implementations, making them more obvious to use and override, and re-enforcing the preferred style of developers writing their own base classes and mixins for custom behavior rather than relying on the configurability of the generic views.
|
||||
|
||||
## Simpler URL lookups
|
||||
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
# 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."
|
||||
> "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]
|
||||
|
||||
|
|
|
@ -1,20 +1,20 @@
|
|||
# The Browsable API
|
||||
|
||||
> It is a profoundly erroneous truism... that we should cultivate the habit of thinking of what we are doing. The precise opposite is the case. Civilization advances by extending the number of important operations which we can perform without thinking about them.
|
||||
> It is a profoundly erroneous truism... that we should cultivate the habit of thinking of what we are doing. The precise opposite is the case. Civilization advances by extending the number of important operations which we can perform without thinking about them.
|
||||
>
|
||||
> — [Alfred North Whitehead][cite], An Introduction to Mathematics (1911)
|
||||
|
||||
|
||||
API may stand for Application *Programming* Interface, but humans have to be able to read the APIs, too; someone has to do the programming. Django REST Framework supports generating human-friendly HTML output for each resource when the `HTML` format is requested. These pages allow for easy browsing of resources, as well as forms for submitting data to the resources using `POST`, `PUT`, and `DELETE`.
|
||||
API may stand for Application *Programming* Interface, but humans have to be able to read the APIs, too; someone has to do the programming. Django REST Framework supports generating human-friendly HTML output for each resource when the `HTML` format is requested. These pages allow for easy browsing of resources, as well as forms for submitting data to the resources using `POST`, `PUT`, and `DELETE`.
|
||||
|
||||
## URLs
|
||||
|
||||
If you include fully-qualified URLs in your resource output, they will be 'urlized' and made clickable for easy browsing by humans. The `rest_framework` package includes a [`reverse`][drfreverse] helper for this purpose.
|
||||
If you include fully-qualified URLs in your resource output, they will be 'urlized' and made clickable for easy browsing by humans. The `rest_framework` package includes a [`reverse`][drfreverse] helper for this purpose.
|
||||
|
||||
|
||||
## Formats
|
||||
|
||||
By default, the API will return the format specified by the headers, which in the case of the browser is HTML. The format can be specified using `?format=` in the request, so you can look at the raw JSON response in a browser by adding `?format=json` to the URL. There are helpful extensions for viewing JSON in [Firefox][ffjsonview] and [Chrome][chromejsonview].
|
||||
By default, the API will return the format specified by the headers, which in the case of the browser is HTML. The format can be specified using `?format=` in the request, so you can look at the raw JSON response in a browser by adding `?format=json` to the URL. There are helpful extensions for viewing JSON in [Firefox][ffjsonview] and [Chrome][chromejsonview].
|
||||
|
||||
|
||||
## Customizing
|
||||
|
@ -25,15 +25,15 @@ The included browsable API template is built with [Bootstrap (2.1.1)][bootstrap]
|
|||
|
||||
### Theme
|
||||
|
||||
To replace the theme wholesale, add a `bootstrap_theme` block to your `api.html` and insert a `link` to the desired Bootstrap theme css file. This will completely replace the included theme.
|
||||
To replace the theme wholesale, add a `bootstrap_theme` block to your `api.html` and insert a `link` to the desired Bootstrap theme css file. This will completely replace the included theme.
|
||||
|
||||
{% block bootstrap_theme %}
|
||||
<link rel="stylesheet" href="/path/to/my/bootstrap.css" type="text/css">
|
||||
{% endblock %}
|
||||
|
||||
A suitable replacement theme can be generated using Bootstrap's [Customize Tool][bcustomize]. Also, there are pre-made themes available at [Bootswatch][bswatch]. To use any of the Bootswatch themes, simply download the theme's `bootstrap.min.css` file, add it to your project, and replace the default one as described above.
|
||||
A suitable replacement theme can be generated using Bootstrap's [Customize Tool][bcustomize]. Also, there are pre-made themes available at [Bootswatch][bswatch]. To use any of the Bootswatch themes, simply download the theme's `bootstrap.min.css` file, add it to your project, and replace the default one as described above.
|
||||
|
||||
You can also change the navbar variant, which by default is `navbar-inverse`, using the `bootstrap_navbar_variant` block. The empty `{% block bootstrap_navbar_variant %}{% endblock %}` will use the original Bootstrap navbar style.
|
||||
You can also change the navbar variant, which by default is `navbar-inverse`, using the `bootstrap_navbar_variant` block. The empty `{% block bootstrap_navbar_variant %}{% endblock %}` will use the original Bootstrap navbar style.
|
||||
|
||||
Full Example
|
||||
|
||||
|
@ -57,11 +57,11 @@ All of the blocks available in the browsable API base template that can be used
|
|||
* `bootstrap_theme` - CSS for the Bootstrap theme
|
||||
* `bootstrap_navbar_variant` - CSS class for the navbar
|
||||
* `branding` - section of the navbar, see [Bootstrap components][bcomponentsnav]
|
||||
* `breadcrumbs` - Links showing resource nesting, allowing the user to go back up the resources. It's recommended to preserve these, but they can be overridden using the breadcrumbs block.
|
||||
* `breadcrumbs` - Links showing resource nesting, allowing the user to go back up the resources. It's recommended to preserve these, but they can be overridden using the breadcrumbs block.
|
||||
* `footer` - Any copyright notices or similar footer materials can go here (by default right-aligned)
|
||||
* `style` - CSS stylesheets for the page
|
||||
* `title` - title of the page
|
||||
* `userlinks` - This is a list of links on the right of the header, by default containing login/logout links. To add links instead of replace, use {{ block.super }} to preserve the authentication links.
|
||||
* `userlinks` - This is a list of links on the right of the header, by default containing login/logout links. To add links instead of replace, use {{ block.super }} to preserve the authentication links.
|
||||
|
||||
#### Components
|
||||
|
||||
|
@ -69,7 +69,7 @@ All of the [Bootstrap components][bcomponents] are available.
|
|||
|
||||
##### Tooltips
|
||||
|
||||
The browsable API makes use of the Bootstrap tooltips component. Any element with the `js-tooltip` class and a `title` attribute has that title content displayed in a tooltip on hover after a 1000ms delay.
|
||||
The browsable API makes use of the Bootstrap tooltips component. Any element with the `js-tooltip` class and a `title` attribute has that title content displayed in a tooltip on hover after a 1000ms delay.
|
||||
|
||||
### Login Template
|
||||
|
||||
|
@ -107,7 +107,7 @@ The context that's available to the template:
|
|||
|
||||
#### Not using base.html
|
||||
|
||||
For more advanced customization, such as not having a Bootstrap basis or tighter integration with the rest of your site, you can simply choose not to have `api.html` extend `base.html`. Then the page content and capabilities are entirely up to you.
|
||||
For more advanced customization, such as not having a Bootstrap basis or tighter integration with the rest of your site, you can simply choose not to have `api.html` extend `base.html`. Then the page content and capabilities are entirely up to you.
|
||||
|
||||
[cite]: http://en.wikiquote.org/wiki/Alfred_North_Whitehead
|
||||
[drfreverse]: ../api-guide/reverse.md
|
||||
|
|
|
@ -21,7 +21,7 @@ For example, given the following form:
|
|||
|
||||
## HTTP header based method overriding
|
||||
|
||||
REST framework also supports method overriding via the semi-standard `X-HTTP-Method-Override` header. This can be useful if you are working with non-form content such as JSON and are working with an older web server and/or hosting provider that doesn't recognise particular HTTP methods such as `PATCH`. For example [Amazon Web Services ELB][aws_elb].
|
||||
REST framework also supports method overriding via the semi-standard `X-HTTP-Method-Override` header. This can be useful if you are working with non-form content such as JSON and are working with an older web server and/or hosting provider that doesn't recognise particular HTTP methods such as `PATCH`. For example [Amazon Web Services ELB][aws_elb].
|
||||
|
||||
To use it, make a `POST` request, setting the `X-HTTP-Method-Override` header.
|
||||
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
# Contributing to REST framework
|
||||
|
||||
> The world can only really be changed one piece at a time. The art is picking that piece.
|
||||
> The world can only really be changed one piece at a time. The art is picking that piece.
|
||||
>
|
||||
> — [Tim Berners-Lee][cite]
|
||||
|
||||
|
@ -24,7 +24,7 @@ Some tips on good issue reporting:
|
|||
|
||||
* When describing issues try to phrase your ticket in terms of the *behavior* you think needs changing rather than the *code* you think need changing.
|
||||
* Search the issue list first for related items, and make sure you're running the latest version of REST framework before reporting an issue.
|
||||
* If reporting a bug, then try to include a pull request with a failing test case. This will help us quickly identify if there is a valid issue, and make sure that it gets fixed more quickly if there is one.
|
||||
* If reporting a bug, then try to include a pull request with a failing test case. This will help us quickly identify if there is a valid issue, and make sure that it gets fixed more quickly if there is one.
|
||||
|
||||
|
||||
|
||||
|
@ -32,6 +32,7 @@ Some tips on good issue reporting:
|
|||
|
||||
# Development
|
||||
|
||||
|
||||
* git clone & PYTHONPATH
|
||||
* Pep8
|
||||
* Recommend editor that runs pep8
|
||||
|
|
|
@ -225,7 +225,7 @@ The security vulnerabilities only affect APIs which use the `XMLParser` class, b
|
|||
* Bugfix: Validation errors instead of exceptions when related fields receive incorrect types.
|
||||
* Bugfix: Handle ObjectDoesNotExist exception when serializing null reverse one-to-one
|
||||
|
||||
**Note**: Prior to 2.1.16, The Decimals would render in JSON using floating point if `simplejson` was installed, but otherwise render using string notation. Now that use of `simplejson` has been deprecated, Decimals will consistently render using string notation. See [#582] for more details.
|
||||
**Note**: Prior to 2.1.16, The Decimals would render in JSON using floating point if `simplejson` was installed, but otherwise render using string notation. Now that use of `simplejson` has been deprecated, Decimals will consistently render using string notation. See [#582] for more details.
|
||||
|
||||
### 2.1.15
|
||||
|
||||
|
|
|
@ -2,7 +2,7 @@
|
|||
|
||||
What it is, and why you should care.
|
||||
|
||||
> Most people just make the mistake that it should be simple to design simple things. In reality, the effort required to design something is inversely proportional to the simplicity of the result.
|
||||
> Most people just make the mistake that it should be simple to design simple things. In reality, the effort required to design something is inversely proportional to the simplicity of the result.
|
||||
>
|
||||
> — [Roy Fielding][cite]
|
||||
|
||||
|
@ -22,9 +22,9 @@ This article is intended to give you a flavor of what REST framework 2 is, and w
|
|||
|
||||
Before we get cracking, let's start with the hard sell, with a few bits of feedback from some early adopters…
|
||||
|
||||
"Django REST framework 2 is beautiful. Some of the API design is worthy of @kennethreitz." - [Kit La Touche][quote1]
|
||||
"Django REST framework 2 is beautiful. Some of the API design is worthy of @kennethreitz." - [Kit La Touche][quote1]
|
||||
|
||||
"Since it's pretty much just Django, controlling things like URLs has been a breeze... I think [REST framework 2] has definitely got the right approach here; even simple things like being able to override a function called post to do custom work during rather than having to intimately know what happens during a post make a huge difference to your productivity." - [Ian Strachan][quote2]
|
||||
"Since it's pretty much just Django, controlling things like URLs has been a breeze... I think [REST framework 2] has definitely got the right approach here; even simple things like being able to override a function called post to do custom work during rather than having to intimately know what happens during a post make a huge difference to your productivity." - [Ian Strachan][quote2]
|
||||
|
||||
"I switched to the 2.0 branch and I don't regret it - fully refactored my code in another ½ day and it's *much* more to my tastes" - [Bruno Desthuilliers][quote3]
|
||||
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
# REST, Hypermedia & HATEOAS
|
||||
|
||||
> You keep using that word "REST". I do not think it means what you think it means.
|
||||
> You keep using that word "REST". I do not think it means what you think it means.
|
||||
>
|
||||
> — Mike Amundsen, [REST fest 2012 keynote][cite].
|
||||
|
||||
|
|
|
@ -2,13 +2,13 @@
|
|||
|
||||
## Introduction
|
||||
|
||||
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.
|
||||
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.
|
||||
|
||||
---
|
||||
|
||||
**Note**: The code for this tutorial is available in the [tomchristie/rest-framework-tutorial][repo] repository on GitHub. The completed implementation is also online as a sandbox version for testing, [available here][sandbox].
|
||||
**Note**: The code for this tutorial is available in the [tomchristie/rest-framework-tutorial][repo] repository on GitHub. The completed implementation is also online as a sandbox version for testing, [available here][sandbox].
|
||||
|
||||
---
|
||||
|
||||
|
@ -73,7 +73,7 @@ Okay, we're ready to roll.
|
|||
|
||||
## Creating a model to work with
|
||||
|
||||
For the purposes of this tutorial we're going to start by creating a simple `Snippet` model that is used to store code snippets. Go ahead and edit the `snippets` app's `models.py` file. Note: Good programming practices include comments. Although you will find them in our repository version of this tutorial code, we have omitted them here to focus on the code itself.
|
||||
For the purposes of this tutorial we're going to start by creating a simple `Snippet` model that is used to store code snippets. Go ahead and edit the `snippets` app's `models.py` file. Note: Good programming practices include comments. Although you will find them in our repository version of this tutorial code, we have omitted them here to focus on the code itself.
|
||||
|
||||
from django.db import models
|
||||
from pygments.lexers import get_all_lexers
|
||||
|
@ -293,7 +293,7 @@ We'll also need a view which corresponds to an individual snippet, and can be us
|
|||
snippet.delete()
|
||||
return HttpResponse(status=204)
|
||||
|
||||
Finally we need to wire these views up. Create the `snippets/urls.py` file:
|
||||
Finally we need to wire these views up. Create the `snippets/urls.py` file:
|
||||
|
||||
from django.conf.urls import patterns, url
|
||||
|
||||
|
|
|
@ -98,7 +98,7 @@ Notice that we're no longer explicitly tying our requests or responses to a give
|
|||
|
||||
## Adding optional format suffixes to our URLs
|
||||
|
||||
To take advantage of the fact that our responses are no longer hardwired to a single content type let's add support for format suffixes to our API endpoints. Using format suffixes gives us URLs that explicitly refer to a given format, and means our API will be able to handle URLs such as [http://example.com/api/items/4.json][json-url].
|
||||
To take advantage of the fact that our responses are no longer hardwired to a single content type let's add support for format suffixes to our API endpoints. Using format suffixes gives us URLs that explicitly refer to a given format, and means our API will be able to handle URLs such as [http://example.com/api/items/4.json][json-url].
|
||||
|
||||
Start by adding a `format` keyword argument to both of the views, like so.
|
||||
|
||||
|
@ -158,7 +158,7 @@ Now go and open the API in a web browser, by visiting [http://127.0.0.1:8000/sni
|
|||
|
||||
### Browsability
|
||||
|
||||
Because the API chooses the content type of the response based on the client request, it will, by default, return an HTML-formatted representation of the resource when that resource is requested by a web browser. This allows for the API to return a fully web-browsable HTML representation.
|
||||
Because the API chooses the content type of the response based on the client request, it will, by default, return an HTML-formatted representation of the resource when that resource is requested by a web browser. This allows for the API to return a fully web-browsable HTML representation.
|
||||
|
||||
Having a web-browsable API is a huge usability win, and makes developing and using your API much easier. It also dramatically lowers the barrier-to-entry for other developers wanting to inspect and work with your API.
|
||||
|
||||
|
|
|
@ -102,7 +102,7 @@ Let's take a look at how we can compose our views by using the mixin classes.
|
|||
def post(self, request, *args, **kwargs):
|
||||
return self.create(request, *args, **kwargs)
|
||||
|
||||
We'll take a moment to examine exactly what's happening here. We're building our view using `GenericAPIView`, and adding in `ListModelMixin` and `CreateModelMixin`.
|
||||
We'll take a moment to examine exactly what's happening here. We're building our view using `GenericAPIView`, and adding in `ListModelMixin` and `CreateModelMixin`.
|
||||
|
||||
The base class provides the core functionality, and the mixin classes provide the `.list()` and `.create()` actions. We're then explicitly binding the `get` and `post` methods to the appropriate actions. Simple enough stuff so far.
|
||||
|
||||
|
|
|
@ -94,7 +94,7 @@ On **both** the `SnippetList` and `SnippetDetail` view classes, add the followin
|
|||
|
||||
## Updating our serializer
|
||||
|
||||
Now that snippets are associated with the user that created them, let's update our `SnippetSerializer` to reflect that. Add the following field to the serializer definition:
|
||||
Now that snippets are associated with the user that created them, let's update our `SnippetSerializer` to reflect that. Add the following field to the serializer definition:
|
||||
|
||||
owner = serializers.Field(source='owner.username')
|
||||
|
||||
|
@ -120,7 +120,7 @@ Then, add the following property to **both** the `SnippetList` and `SnippetDetai
|
|||
|
||||
## Adding login to the Browsable API
|
||||
|
||||
If you open a browser and navigate to the browsable API at the moment, you'll find that you're no longer able to create new code snippets. In order to do so we'd need to be able to login as a user.
|
||||
If you open a browser and navigate to the browsable API at the moment, you'll find that you're no longer able to create new code snippets. In order to do so we'd need to be able to login as a user.
|
||||
|
||||
We can add a login view for use with the browsable API, by editing our URLconf once more.
|
||||
|
||||
|
|
|
@ -29,7 +29,7 @@ Unlike all our other API endpoints, we don't want to use JSON, but instead just
|
|||
|
||||
The other thing we need to consider when creating the code highlight view is that there's no existing concrete generic view that we can use. We're not returning an object instance, but instead a property of an object instance.
|
||||
|
||||
Instead of using a concrete generic view, we'll use the base class for representing instances, and create our own `.get()` method. In your snippets.views add:
|
||||
Instead of using a concrete generic view, we'll use the base class for representing instances, and create our own `.get()` method. In your snippets.views add:
|
||||
|
||||
from rest_framework import renderers
|
||||
from rest_framework.response import Response
|
||||
|
|
Loading…
Reference in New Issue
Block a user