Merge remote-tracking branch 'upstream/master' into set_value_static
# Conflicts: # tests/test_serializer.py
22
.github/stale.yml
vendored
Normal file
|
@ -0,0 +1,22 @@
|
|||
# Documentation: https://github.com/probot/stale
|
||||
|
||||
# Number of days of inactivity before an issue becomes stale
|
||||
daysUntilStale: 60
|
||||
|
||||
# Number of days of inactivity before a stale issue is closed
|
||||
daysUntilClose: 7
|
||||
|
||||
# Comment to post when marking an issue as stale. Set to `false` to disable
|
||||
markComment: >
|
||||
This issue has been automatically marked as stale because it has not had
|
||||
recent activity. It will be closed if no further activity occurs. Thank you
|
||||
for your contributions.
|
||||
|
||||
# Comment to post when closing a stale issue. Set to `false` to disable
|
||||
closeComment: false
|
||||
|
||||
# Limit the number of actions per hour, from 1-30. Default is 30
|
||||
limitPerRun: 1
|
||||
|
||||
# Label to use when marking as stale
|
||||
staleLabel: stale
|
29
.github/workflows/main.yml
vendored
|
@ -18,37 +18,40 @@ jobs:
|
|||
- '3.7'
|
||||
- '3.8'
|
||||
- '3.9'
|
||||
- '3.10'
|
||||
- '3.11'
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- uses: actions/setup-python@v2
|
||||
- uses: actions/setup-python@v4
|
||||
with:
|
||||
python-version: ${{ matrix.python-version }}
|
||||
|
||||
- uses: actions/cache@v2
|
||||
with:
|
||||
path: ~/.cache/pip
|
||||
key: ${{ runner.os }}-pip-${{ hashFiles('requirements/*.txt') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-pip-
|
||||
cache: 'pip'
|
||||
cache-dependency-path: 'requirements/*.txt'
|
||||
|
||||
- name: Upgrade packaging tools
|
||||
run: python -m pip install --upgrade pip setuptools virtualenv wheel
|
||||
|
||||
- name: Install dependencies
|
||||
run: python -m pip install --upgrade codecov tox tox-py
|
||||
run: python -m pip install --upgrade codecov tox
|
||||
|
||||
- name: Install tox-py
|
||||
if: ${{ matrix.python-version == '3.6' }}
|
||||
run: python -m pip install --upgrade tox-py
|
||||
|
||||
- name: Run tox targets for ${{ matrix.python-version }}
|
||||
if: ${{ matrix.python-version != '3.6' }}
|
||||
run: tox run -f py$(echo ${{ matrix.python-version }} | tr -d .)
|
||||
|
||||
- name: Run tox targets for ${{ matrix.python-version }}
|
||||
if: ${{ matrix.python-version == '3.6' }}
|
||||
run: tox --py current
|
||||
|
||||
- name: Run extra tox targets
|
||||
if: ${{ matrix.python-version == '3.9' }}
|
||||
run: |
|
||||
python setup.py bdist_wheel
|
||||
rm -r djangorestframework.egg-info # see #6139
|
||||
tox -e base,dist,docs
|
||||
tox -e dist --installpkg ./dist/djangorestframework-*.whl
|
||||
|
||||
- name: Upload coverage
|
||||
run: |
|
||||
|
|
|
@ -9,7 +9,7 @@ repos:
|
|||
- id: check-symlinks
|
||||
- id: check-toml
|
||||
- repo: https://github.com/pycqa/isort
|
||||
rev: 5.8.0
|
||||
rev: 5.12.0
|
||||
hooks:
|
||||
- id: isort
|
||||
- repo: https://github.com/PyCQA/flake8
|
||||
|
|
|
@ -1,3 +1,7 @@
|
|||
# Contributing to REST framework
|
||||
|
||||
See the [Contributing guide in the documentation](https://www.django-rest-framework.org/community/contributing/).
|
||||
At this point in it's lifespan we consider Django REST framework to be essentially feature-complete. We may accept pull requests that track the continued development of Django versions, but would prefer not to accept new features or code formatting changes.
|
||||
|
||||
Apart from minor documentation changes, the [GitHub discussions page](https://github.com/encode/django-rest-framework/discussions) should generally be your starting point. Please only raise an issue or pull request if you've been recommended to do so after discussion.
|
||||
|
||||
The [Contributing guide in the documentation](https://www.django-rest-framework.org/community/contributing/) gives some more information on our process and code of conduct.
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
include README.md
|
||||
include LICENSE.md
|
||||
recursive-include tests/ *
|
||||
recursive-include rest_framework/static *.js *.css *.png *.ico *.eot *.svg *.ttf *.woff *.woff2
|
||||
recursive-include rest_framework/static *.js *.css *.map *.png *.ico *.eot *.svg *.ttf *.woff *.woff2
|
||||
recursive-include rest_framework/templates *.html schema.js
|
||||
recursive-include rest_framework/locale *.mo
|
||||
global-exclude __pycache__
|
||||
|
|
47
README.md
|
@ -21,12 +21,14 @@ The initial aim is to provide a single full-time position on REST framework.
|
|||
|
||||
[![][sentry-img]][sentry-url]
|
||||
[![][stream-img]][stream-url]
|
||||
[![][rollbar-img]][rollbar-url]
|
||||
[![][esg-img]][esg-url]
|
||||
[![][spacinov-img]][spacinov-url]
|
||||
[![][retool-img]][retool-url]
|
||||
[![][bitio-img]][bitio-url]
|
||||
[![][posthog-img]][posthog-url]
|
||||
[![][cryptapi-img]][cryptapi-url]
|
||||
[![][fezto-img]][fezto-url]
|
||||
|
||||
Many thanks to all our [wonderful sponsors][sponsors], and in particular to our premium backers, [Sentry][sentry-url], [Stream][stream-url], [Rollbar][rollbar-url], [ESG][esg-url], [Retool][retool-url], and [bit.io][bitio-url].
|
||||
Many thanks to all our [wonderful sponsors][sponsors], and in particular to our premium backers, [Sentry][sentry-url], [Stream][stream-url], [Spacinov][spacinov-url], [Retool][retool-url], [bit.io][bitio-url], [PostHog][posthog-url], [CryptAPI][cryptapi-url], and [FEZTO][fezto-url].
|
||||
|
||||
---
|
||||
|
||||
|
@ -52,8 +54,8 @@ There is a live example API for testing purposes, [available here][sandbox].
|
|||
|
||||
# Requirements
|
||||
|
||||
* Python (3.5, 3.6, 3.7, 3.8, 3.9)
|
||||
* Django (2.2, 3.0, 3.1)
|
||||
* Python 3.6+
|
||||
* Django 4.1, 4.0, 3.2, 3.1, 3.0
|
||||
|
||||
We **highly recommend** and only officially support the latest patch release of
|
||||
each Python and Django series.
|
||||
|
@ -65,11 +67,12 @@ Install using `pip`...
|
|||
pip install djangorestframework
|
||||
|
||||
Add `'rest_framework'` to your `INSTALLED_APPS` setting.
|
||||
|
||||
INSTALLED_APPS = [
|
||||
...
|
||||
'rest_framework',
|
||||
]
|
||||
```python
|
||||
INSTALLED_APPS = [
|
||||
...
|
||||
'rest_framework',
|
||||
]
|
||||
```
|
||||
|
||||
# Example
|
||||
|
||||
|
@ -87,9 +90,10 @@ Startup up a new project like so...
|
|||
Now edit the `example/urls.py` module in your project:
|
||||
|
||||
```python
|
||||
from django.urls import path, include
|
||||
from django.contrib.auth.models import User
|
||||
from rest_framework import serializers, viewsets, routers
|
||||
from django.urls import include, path
|
||||
from rest_framework import routers, serializers, viewsets
|
||||
|
||||
|
||||
# Serializers define the API representation.
|
||||
class UserSerializer(serializers.HyperlinkedModelSerializer):
|
||||
|
@ -108,7 +112,6 @@ class UserViewSet(viewsets.ModelViewSet):
|
|||
router = routers.DefaultRouter()
|
||||
router.register(r'users', UserViewSet)
|
||||
|
||||
|
||||
# Wire up our API using automatic URL routing.
|
||||
# Additionally, we include login URLs for the browsable API.
|
||||
urlpatterns = [
|
||||
|
@ -168,7 +171,7 @@ Or to create a new user:
|
|||
|
||||
Full documentation for the project is available at [https://www.django-rest-framework.org/][docs].
|
||||
|
||||
For questions and support, use the [REST framework discussion group][group], or `#restframework` on freenode IRC.
|
||||
For questions and support, use the [REST framework discussion group][group], or `#restframework` on libera.chat IRC.
|
||||
|
||||
You may also want to [follow the author on Twitter][twitter].
|
||||
|
||||
|
@ -182,7 +185,7 @@ Please see the [security policy][security-policy].
|
|||
[codecov]: https://codecov.io/github/encode/django-rest-framework?branch=master
|
||||
[pypi-version]: https://img.shields.io/pypi/v/djangorestframework.svg
|
||||
[pypi]: https://pypi.org/project/djangorestframework/
|
||||
[twitter]: https://twitter.com/_tomchristie
|
||||
[twitter]: https://twitter.com/starletdreaming
|
||||
[group]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework
|
||||
[sandbox]: https://restframework.herokuapp.com/
|
||||
|
||||
|
@ -191,17 +194,21 @@ Please see the [security policy][security-policy].
|
|||
|
||||
[sentry-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/sentry-readme.png
|
||||
[stream-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/stream-readme.png
|
||||
[rollbar-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/rollbar-readme.png
|
||||
[esg-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/esg-readme.png
|
||||
[spacinov-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/spacinov-readme.png
|
||||
[retool-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/retool-readme.png
|
||||
[bitio-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/bitio-readme.png
|
||||
[posthog-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/posthog-readme.png
|
||||
[cryptapi-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/cryptapi-readme.png
|
||||
[fezto-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/fezto-readme.png
|
||||
|
||||
[sentry-url]: https://getsentry.com/welcome/
|
||||
[stream-url]: https://getstream.io/try-the-api/?utm_source=drf&utm_medium=banner&utm_campaign=drf
|
||||
[rollbar-url]: https://rollbar.com/?utm_source=django&utm_medium=sponsorship&utm_campaign=freetrial
|
||||
[esg-url]: https://software.esg-usa.com/
|
||||
[stream-url]: https://getstream.io/?utm_source=DjangoRESTFramework&utm_medium=Webpage_Logo_Ad&utm_content=Developer&utm_campaign=DjangoRESTFramework_Jan2022_HomePage
|
||||
[spacinov-url]: https://www.spacinov.com/
|
||||
[retool-url]: https://retool.com/?utm_source=djangorest&utm_medium=sponsorship
|
||||
[bitio-url]: https://bit.io/jobs?utm_source=DRF&utm_medium=sponsor&utm_campaign=DRF_sponsorship
|
||||
[posthog-url]: https://posthog.com?utm_source=drf&utm_medium=sponsorship&utm_campaign=open-source-sponsorship
|
||||
[cryptapi-url]: https://cryptapi.io
|
||||
[fezto-url]: https://www.fezto.xyz/?utm_source=DjangoRESTFramework
|
||||
|
||||
[oauth1-section]: https://www.django-rest-framework.org/api-guide/authentication/#django-rest-framework-oauth
|
||||
[oauth2-section]: https://www.django-rest-framework.org/api-guide/authentication/#django-oauth-toolkit
|
||||
|
|
|
@ -2,8 +2,8 @@
|
|||
|
||||
## Reporting a Vulnerability
|
||||
|
||||
If you believe you've found something in Django REST framework which has security implications, please **do not raise the issue in a public forum**.
|
||||
Security issues are handled under the supervision of the [Django security team](https://www.djangoproject.com/foundation/teams/#security-team).
|
||||
|
||||
Send a description of the issue via email to [rest-framework-security@googlegroups.com][security-mail]. The project maintainers will then work with you to resolve any issues where required, prior to any public disclosure.
|
||||
**Please report security issues by emailing security@djangoproject.com**.
|
||||
|
||||
[security-mail]: mailto:rest-framework-security@googlegroups.com
|
||||
The project maintainers will then work with you to resolve any issues where required, prior to any public disclosure.
|
||||
|
|
|
@ -11,9 +11,9 @@ source:
|
|||
|
||||
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 schemes out of the box, and also allows you to implement custom schemes.
|
||||
REST framework provides several authentication schemes out of the box, and also allows you to implement custom schemes.
|
||||
|
||||
Authentication is always run at the very start of the view, before the permission and throttling checks occur, and before any other code is allowed to proceed.
|
||||
Authentication always runs at the very start of the view, before the permission and throttling checks occur, and before any other code is allowed to proceed.
|
||||
|
||||
The `request.user` property will typically be set to an instance of the `contrib.auth` package's `User` class.
|
||||
|
||||
|
@ -23,7 +23,7 @@ The `request.auth` property is used for any additional authentication informatio
|
|||
|
||||
**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].
|
||||
For information on how to set up the permission policies for your API please see the [permissions documentation][permission].
|
||||
|
||||
---
|
||||
|
||||
|
@ -120,6 +120,14 @@ Unauthenticated responses that are denied permission will result in an `HTTP 401
|
|||
|
||||
## TokenAuthentication
|
||||
|
||||
---
|
||||
|
||||
**Note:** The token authentication provided by Django REST framework is a fairly simple implementation.
|
||||
|
||||
For an implementation which allows more than one token per user, has some tighter security implementation details, and supports token expiry, please see the [Django REST Knox][django-rest-knox] third party package.
|
||||
|
||||
---
|
||||
|
||||
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` scheme you'll need to [configure the authentication classes](#setting-the-authentication-scheme) to include `TokenAuthentication`, and additionally include `rest_framework.authtoken` in your `INSTALLED_APPS` setting:
|
||||
|
@ -129,11 +137,9 @@ To use the `TokenAuthentication` scheme you'll need to [configure the authentica
|
|||
'rest_framework.authtoken'
|
||||
]
|
||||
|
||||
---
|
||||
Make sure to run `manage.py migrate` after changing your settings.
|
||||
|
||||
**Note:** Make sure to run `manage.py migrate` after changing your settings. The `rest_framework.authtoken` app provides Django database migrations.
|
||||
|
||||
---
|
||||
The `rest_framework.authtoken` app provides Django database migrations.
|
||||
|
||||
You'll also need to create tokens for your users.
|
||||
|
||||
|
@ -146,7 +152,7 @@ For clients to authenticate, the token key should be included in the `Authorizat
|
|||
|
||||
Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b
|
||||
|
||||
**Note:** If you want to use a different keyword in the header, such as `Bearer`, simply subclass `TokenAuthentication` and set the `keyword` class variable.
|
||||
*If you want to use a different keyword in the header, such as `Bearer`, simply subclass `TokenAuthentication` and set the `keyword` class variable.*
|
||||
|
||||
If successfully authenticated, `TokenAuthentication` provides the following credentials.
|
||||
|
||||
|
@ -167,9 +173,9 @@ The `curl` command line tool may be useful for testing token authenticated APIs.
|
|||
|
||||
---
|
||||
|
||||
#### Generating Tokens
|
||||
### Generating Tokens
|
||||
|
||||
##### By using signals
|
||||
#### By using signals
|
||||
|
||||
If you want every user to have an automatically generated Token, you can simply catch the User's `post_save` signal.
|
||||
|
||||
|
@ -193,7 +199,7 @@ If you've already created some users, you can generate tokens for all existing u
|
|||
for user in User.objects.all():
|
||||
Token.objects.get_or_create(user=user)
|
||||
|
||||
##### By exposing an api endpoint
|
||||
#### By exposing an api endpoint
|
||||
|
||||
When using `TokenAuthentication`, you may want to provide a mechanism for clients to obtain a token given the username and password. REST framework provides a built-in view to provide this behavior. To use it, add the `obtain_auth_token` view to your URLconf:
|
||||
|
||||
|
@ -210,7 +216,7 @@ The `obtain_auth_token` view will return a JSON response when valid `username` a
|
|||
|
||||
Note that the default `obtain_auth_token` view explicitly uses JSON requests and responses, rather than using default renderer and parser classes in your settings.
|
||||
|
||||
By default there are no permissions or throttling applied to the `obtain_auth_token` view. If you do wish to apply throttling you'll need to override the view class,
|
||||
By default, there are no permissions or throttling applied to the `obtain_auth_token` view. If you do wish to apply throttling you'll need to override the view class,
|
||||
and include them using the `throttle_classes` attribute.
|
||||
|
||||
If you need a customized version of the `obtain_auth_token` view, you can do so by subclassing the `ObtainAuthToken` view class, and using that in your url conf instead.
|
||||
|
@ -242,9 +248,9 @@ And in your `urls.py`:
|
|||
]
|
||||
|
||||
|
||||
##### With Django admin
|
||||
#### With Django admin
|
||||
|
||||
It is also possible to create Tokens manually through admin interface. In case you are using a large user base, we recommend that you monkey patch the `TokenAdmin` class to customize it to your needs, more specifically by declaring the `user` field as `raw_field`.
|
||||
It is also possible to create Tokens manually through the admin interface. In case you are using a large user base, we recommend that you monkey patch the `TokenAdmin` class to customize it to your needs, more specifically by declaring the `user` field as `raw_field`.
|
||||
|
||||
`your_app/admin.py`:
|
||||
|
||||
|
@ -279,11 +285,11 @@ If successfully authenticated, `SessionAuthentication` provides the following cr
|
|||
|
||||
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.
|
||||
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.
|
||||
|
||||
**Warning**: Always use Django's standard login view when creating login pages. This will ensure your login views are properly protected.
|
||||
|
||||
CSRF validation in REST framework works slightly differently to standard Django due to the need to support both session and non-session based authentication to the same views. This means that only authenticated requests require CSRF tokens, and anonymous requests may be sent without CSRF tokens. This behaviour is not suitable for login views, which should always have CSRF validation applied.
|
||||
CSRF validation in REST framework works slightly differently from standard Django due to the need to support both session and non-session based authentication to the same views. This means that only authenticated requests require CSRF tokens, and anonymous requests may be sent without CSRF tokens. This behavior is not suitable for login views, which should always have CSRF validation applied.
|
||||
|
||||
|
||||
## RemoteUserAuthentication
|
||||
|
@ -293,7 +299,7 @@ environment variable.
|
|||
|
||||
To use it, you must have `django.contrib.auth.backends.RemoteUserBackend` (or a subclass) in your
|
||||
`AUTHENTICATION_BACKENDS` setting. By default, `RemoteUserBackend` creates `User` objects for usernames that don't
|
||||
already exist. To change this and other behaviour, consult the
|
||||
already exist. To change this and other behavior, consult the
|
||||
[Django documentation](https://docs.djangoproject.com/en/stable/howto/auth-remote-user/).
|
||||
|
||||
If successfully authenticated, `RemoteUserAuthentication` provides the following credentials:
|
||||
|
@ -301,7 +307,7 @@ If successfully authenticated, `RemoteUserAuthentication` provides the following
|
|||
* `request.user` will be a Django `User` instance.
|
||||
* `request.auth` will be `None`.
|
||||
|
||||
Consult your web server's documentation for information about configuring an authentication method, e.g.:
|
||||
Consult your web server's documentation for information about configuring an authentication method, for example:
|
||||
|
||||
* [Apache Authentication How-To](https://httpd.apache.org/docs/2.4/howto/auth.html)
|
||||
* [NGINX (Restricting Access)](https://docs.nginx.com/nginx/admin-guide/security-controls/configuring-http-basic-authentication/)
|
||||
|
@ -316,7 +322,7 @@ In some circumstances instead of returning `None`, you may want to raise an `Aut
|
|||
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, regardless of any permissions checks, and without checking any other authentication schemes.
|
||||
* If authentication is attempted but fails, raise an `AuthenticationFailed` exception. An error response will be returned immediately, regardless of any permissions checks, and without checking any other authentication schemes.
|
||||
|
||||
You *may* also override the `.authenticate_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.
|
||||
|
||||
|
@ -332,7 +338,7 @@ If the `.authenticate_header()` method is not overridden, the authentication sch
|
|||
|
||||
The following example will authenticate any incoming request as the user given by the username in a custom request header named 'X-USERNAME'.
|
||||
|
||||
from django.contrib.auth.models import User
|
||||
from django.contrib.auth.models import User
|
||||
from rest_framework import authentication
|
||||
from rest_framework import exceptions
|
||||
|
||||
|
@ -353,13 +359,17 @@ The following example will authenticate any incoming request as the user given b
|
|||
|
||||
# Third party packages
|
||||
|
||||
The following third party packages are also available.
|
||||
The following third-party packages are also available.
|
||||
|
||||
## django-rest-knox
|
||||
|
||||
[Django-rest-knox][django-rest-knox] library provides models and views to handle token-based authentication in a more secure and extensible way than the built-in TokenAuthentication scheme - with Single Page Applications and Mobile clients in mind. It provides per-client tokens, and views to generate them when provided some other authentication (usually basic authentication), to delete the token (providing a server enforced logout) and to delete all tokens (logs out all clients that a user is logged into).
|
||||
|
||||
## Django OAuth Toolkit
|
||||
|
||||
The [Django OAuth Toolkit][django-oauth-toolkit] package provides OAuth 2.0 support and works with Python 3.4+. The package is maintained by [jazzband][jazzband] and uses the excellent [OAuthLib][oauthlib]. The package is well documented, and well supported and is currently our **recommended package for OAuth 2.0 support**.
|
||||
|
||||
#### Installation & configuration
|
||||
### Installation & configuration
|
||||
|
||||
Install using `pip`.
|
||||
|
||||
|
@ -384,9 +394,9 @@ For more details see the [Django REST framework - Getting started][django-oauth-
|
|||
|
||||
The [Django REST framework OAuth][django-rest-framework-oauth] package provides both OAuth1 and OAuth2 support for REST framework.
|
||||
|
||||
This package was previously included directly in REST framework but is now supported and maintained as a third party package.
|
||||
This package was previously included directly in the REST framework but is now supported and maintained as a third-party package.
|
||||
|
||||
#### Installation & configuration
|
||||
### Installation & configuration
|
||||
|
||||
Install the package using `pip`.
|
||||
|
||||
|
@ -408,7 +418,7 @@ HTTP Signature (currently a [IETF draft][http-signature-ietf-draft]) provides a
|
|||
|
||||
## Djoser
|
||||
|
||||
[Djoser][djoser] library provides a set of views to handle basic actions such as registration, login, logout, password reset and account activation. The package works with a custom user model and it uses token based authentication. This is a ready to use REST implementation of Django authentication system.
|
||||
[Djoser][djoser] library provides a set of views to handle basic actions such as registration, login, logout, password reset and account activation. The package works with a custom user model and uses token-based authentication. This is a ready to use REST implementation of the Django authentication system.
|
||||
|
||||
## django-rest-auth / dj-rest-auth
|
||||
|
||||
|
@ -420,21 +430,17 @@ There are currently two forks of this project.
|
|||
* [Django-rest-auth][django-rest-auth] is the original project, [but is not currently receiving updates](https://github.com/Tivix/django-rest-auth/issues/568).
|
||||
* [Dj-rest-auth][dj-rest-auth] is a newer fork of the project.
|
||||
|
||||
## django-rest-framework-social-oauth2
|
||||
## drf-social-oauth2
|
||||
|
||||
[Django-rest-framework-social-oauth2][django-rest-framework-social-oauth2] library provides an easy way to integrate social plugins (facebook, twitter, google, etc.) to your authentication system and an easy oauth2 setup. With this library, you will be able to authenticate users based on external tokens (e.g. facebook access token), convert these tokens to "in-house" oauth2 tokens and use and generate oauth2 tokens to authenticate your users.
|
||||
|
||||
## django-rest-knox
|
||||
|
||||
[Django-rest-knox][django-rest-knox] library provides models and views to handle token based authentication in a more secure and extensible way than the built-in TokenAuthentication scheme - with Single Page Applications and Mobile clients in mind. It provides per-client tokens, and views to generate them when provided some other authentication (usually basic authentication), to delete the token (providing a server enforced logout) and to delete all tokens (logs out all clients that a user is logged into).
|
||||
[Drf-social-oauth2][drf-social-oauth2] is a framework that helps you authenticate with major social oauth2 vendors, such as Facebook, Google, Twitter, Orcid, etc. It generates tokens in a JWTed way with an easy setup.
|
||||
|
||||
## drfpasswordless
|
||||
|
||||
[drfpasswordless][drfpasswordless] adds (Medium, Square Cash inspired) passwordless support to Django REST Framework's own TokenAuthentication scheme. Users log in and sign up with a token sent to a contact point like an email address or a mobile number.
|
||||
[drfpasswordless][drfpasswordless] adds (Medium, Square Cash inspired) passwordless support to Django REST Framework's TokenAuthentication scheme. Users log in and sign up with a token sent to a contact point like an email address or a mobile number.
|
||||
|
||||
## django-rest-authemail
|
||||
|
||||
[django-rest-authemail][django-rest-authemail] provides a RESTful API interface for user signup and authentication. Email addresses are used for authentication, rather than usernames. API endpoints are available for signup, signup email verification, login, logout, password reset, password reset verification, email change, email change verification, password change, and user detail. A fully-functional example project and detailed instructions are included.
|
||||
[django-rest-authemail][django-rest-authemail] provides a RESTful API interface for user signup and authentication. Email addresses are used for authentication, rather than usernames. API endpoints are available for signup, signup email verification, login, logout, password reset, password reset verification, email change, email change verification, password change, and user detail. A fully functional example project and detailed instructions are included.
|
||||
|
||||
## Django-Rest-Durin
|
||||
|
||||
|
@ -473,7 +479,7 @@ More information can be found in the [Documentation](https://django-rest-durin.r
|
|||
[djoser]: https://github.com/sunscrapers/djoser
|
||||
[django-rest-auth]: https://github.com/Tivix/django-rest-auth
|
||||
[dj-rest-auth]: https://github.com/jazzband/dj-rest-auth
|
||||
[django-rest-framework-social-oauth2]: https://github.com/PhilipGarnero/django-rest-framework-social-oauth2
|
||||
[drf-social-oauth2]: https://github.com/wagnerdelima/drf-social-oauth2
|
||||
[django-rest-knox]: https://github.com/James1345/django-rest-knox
|
||||
[drfpasswordless]: https://github.com/aaronn/django-rest-framework-passwordless
|
||||
[django-rest-authemail]: https://github.com/celiao/django-rest-authemail
|
||||
|
|
|
@ -82,7 +82,7 @@ The default content negotiation class may be set globally, using the `DEFAULT_CO
|
|||
|
||||
You can also set the content negotiation used for an individual view, or viewset, using the `APIView` class-based views.
|
||||
|
||||
from myapp.negotiation import IgnoreClientContentNegotiation
|
||||
from myapp.negotiation import IgnoreClientContentNegotiation
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.views import APIView
|
||||
|
||||
|
|
|
@ -217,11 +217,10 @@ By default this exception results in a response with the HTTP status code "429 T
|
|||
|
||||
## ValidationError
|
||||
|
||||
**Signature:** `ValidationError(detail, code=None)`
|
||||
**Signature:** `ValidationError(detail=None, code=None)`
|
||||
|
||||
The `ValidationError` exception is slightly different from the other `APIException` classes:
|
||||
|
||||
* The `detail` argument is mandatory, not optional.
|
||||
* The `detail` argument may be a list or dictionary of error details, and may also be a nested data structure. By using a dictionary, you can specify field-level errors while performing object-level validation in the `validate()` method of a serializer. For example. `raise serializers.ValidationError({'name': 'Please enter a valid name.'})`
|
||||
* By convention you should import the serializers module and use a fully qualified `ValidationError` style, in order to differentiate it from Django's built-in validation error. For example. `raise serializers.ValidationError('This field must be an integer value.')`
|
||||
|
||||
|
@ -260,6 +259,15 @@ Set as `handler400`:
|
|||
|
||||
handler400 = 'rest_framework.exceptions.bad_request'
|
||||
|
||||
# Third party packages
|
||||
|
||||
The following third-party packages are also available.
|
||||
|
||||
## DRF Standardized Errors
|
||||
|
||||
The [drf-standardized-errors][drf-standardized-errors] package provides an exception handler that generates the same format for all 4xx and 5xx responses. It is a drop-in replacement for the default exception handler and allows customizing the error response format without rewriting the whole exception handler. The standardized error response format is easier to document and easier to handle by API consumers.
|
||||
|
||||
[cite]: https://doughellmann.com/blog/2009/06/19/python-exception-handling-techniques/
|
||||
[authentication]: authentication.md
|
||||
[django-custom-error-views]: https://docs.djangoproject.com/en/dev/topics/http/views/#customizing-error-views
|
||||
[drf-standardized-errors]: https://github.com/ghazi-git/drf-standardized-errors
|
||||
|
|
|
@ -42,11 +42,11 @@ Set to false if this field is not required to be present during deserialization.
|
|||
|
||||
Setting this to `False` also allows the object attribute or dictionary key to be omitted from output when serializing the instance. If the key is not present it will simply not be included in the output representation.
|
||||
|
||||
Defaults to `True`.
|
||||
Defaults to `True`. If you're using [Model Serializer](https://www.django-rest-framework.org/api-guide/serializers/#modelserializer) default value will be `False` if you have specified `blank=True` or `default` or `null=True` at your field in your `Model`.
|
||||
|
||||
### `default`
|
||||
|
||||
If set, this gives the default value that will be used for the field if no input value is supplied. If not set the default behaviour is to not populate the attribute at all.
|
||||
If set, this gives the default value that will be used for the field if no input value is supplied. If not set the default behavior is to not populate the attribute at all.
|
||||
|
||||
The `default` is not applied during partial update operations. In the partial update case only fields that are provided in the incoming data will have a validated value returned.
|
||||
|
||||
|
@ -78,7 +78,14 @@ Defaults to `False`
|
|||
|
||||
### `source`
|
||||
|
||||
The name of the attribute that will be used to populate the field. May be a method that only takes a `self` argument, such as `URLField(source='get_absolute_url')`, or may use dotted notation to traverse attributes, such as `EmailField(source='user.email')`. When serializing fields with dotted notation, it may be necessary to provide a `default` value if any object is not present or is empty during attribute traversal.
|
||||
The name of the attribute that will be used to populate the field. May be a method that only takes a `self` argument, such as `URLField(source='get_absolute_url')`, or may use dotted notation to traverse attributes, such as `EmailField(source='user.email')`.
|
||||
|
||||
When serializing fields with dotted notation, it may be necessary to provide a `default` value if any object is not present or is empty during attribute traversal. Beware of possible n+1 problems when using source attribute if you are accessing a relational orm model. For example:
|
||||
|
||||
class CommentSerializer(serializers.Serializer):
|
||||
email = serializers.EmailField(source="user.email")
|
||||
|
||||
This case would require user object to be fetched from database when it is not prefetched. If that is not wanted, be sure to be using `prefetch_related` and `select_related` methods appropriately. For more information about the methods refer to [django documentation][django-docs-select-related].
|
||||
|
||||
The value `source='*'` has a special meaning, and is used to indicate that the entire object should be passed through to the field. This can be useful for creating nested representations, or for fields which require access to the complete object in order to determine the output representation.
|
||||
|
||||
|
@ -144,7 +151,7 @@ Prior to Django 2.1 `models.BooleanField` fields were always `blank=True`. Thus
|
|||
since Django 2.1 default `serializers.BooleanField` instances will be generated
|
||||
without the `required` kwarg (i.e. equivalent to `required=True`) whereas with
|
||||
previous versions of Django, default `BooleanField` instances will be generated
|
||||
with a `required=False` option. If you want to control this behaviour manually,
|
||||
with a `required=False` option. If you want to control this behavior manually,
|
||||
explicitly declare the `BooleanField` on the serializer class, or use the
|
||||
`extra_kwargs` option to set the `required` flag.
|
||||
|
||||
|
@ -152,14 +159,6 @@ Corresponds to `django.db.models.fields.BooleanField`.
|
|||
|
||||
**Signature:** `BooleanField()`
|
||||
|
||||
## NullBooleanField
|
||||
|
||||
A boolean representation that also accepts `None` as a valid value.
|
||||
|
||||
Corresponds to `django.db.models.fields.NullBooleanField`.
|
||||
|
||||
**Signature:** `NullBooleanField()`
|
||||
|
||||
---
|
||||
|
||||
# String fields
|
||||
|
@ -172,10 +171,10 @@ Corresponds to `django.db.models.fields.CharField` or `django.db.models.fields.T
|
|||
|
||||
**Signature:** `CharField(max_length=None, min_length=None, allow_blank=False, trim_whitespace=True)`
|
||||
|
||||
- `max_length` - Validates that the input contains no more than this number of characters.
|
||||
- `min_length` - Validates that the input contains no fewer than this number of characters.
|
||||
- `allow_blank` - If set to `True` then the empty string should be considered a valid value. If set to `False` then the empty string is considered invalid and will raise a validation error. Defaults to `False`.
|
||||
- `trim_whitespace` - If set to `True` then leading and trailing whitespace is trimmed. Defaults to `True`.
|
||||
* `max_length` - Validates that the input contains no more than this number of characters.
|
||||
* `min_length` - Validates that the input contains no fewer than this number of characters.
|
||||
* `allow_blank` - If set to `True` then the empty string should be considered a valid value. If set to `False` then the empty string is considered invalid and will raise a validation error. Defaults to `False`.
|
||||
* `trim_whitespace` - If set to `True` then leading and trailing whitespace is trimmed. Defaults to `True`.
|
||||
|
||||
The `allow_null` option is also available for string fields, although its usage is discouraged in favor of `allow_blank`. It is valid to set both `allow_blank=True` and `allow_null=True`, but doing so means that there will be two differing types of empty value permissible for string representations, which can lead to data inconsistencies and subtle application bugs.
|
||||
|
||||
|
@ -223,11 +222,11 @@ A field that ensures the input is a valid UUID string. The `to_internal_value` m
|
|||
|
||||
**Signature:** `UUIDField(format='hex_verbose')`
|
||||
|
||||
- `format`: Determines the representation format of the uuid value
|
||||
- `'hex_verbose'` - The canonical hex representation, including hyphens: `"5ce0e9a5-5ffa-654b-cee0-1238041fb31a"`
|
||||
- `'hex'` - The compact hex representation of the UUID, not including hyphens: `"5ce0e9a55ffa654bcee01238041fb31a"`
|
||||
- `'int'` - A 128 bit integer representation of the UUID: `"123456789012312313134124512351145145114"`
|
||||
- `'urn'` - RFC 4122 URN representation of the UUID: `"urn:uuid:5ce0e9a5-5ffa-654b-cee0-1238041fb31a"`
|
||||
* `format`: Determines the representation format of the uuid value
|
||||
* `'hex_verbose'` - The canonical hex representation, including hyphens: `"5ce0e9a5-5ffa-654b-cee0-1238041fb31a"`
|
||||
* `'hex'` - The compact hex representation of the UUID, not including hyphens: `"5ce0e9a55ffa654bcee01238041fb31a"`
|
||||
* `'int'` - A 128 bit integer representation of the UUID: `"123456789012312313134124512351145145114"`
|
||||
* `'urn'` - RFC 4122 URN representation of the UUID: `"urn:uuid:5ce0e9a5-5ffa-654b-cee0-1238041fb31a"`
|
||||
Changing the `format` parameters only affects representation values. All formats are accepted by `to_internal_value`
|
||||
|
||||
## FilePathField
|
||||
|
@ -238,11 +237,11 @@ Corresponds to `django.forms.fields.FilePathField`.
|
|||
|
||||
**Signature:** `FilePathField(path, match=None, recursive=False, allow_files=True, allow_folders=False, required=None, **kwargs)`
|
||||
|
||||
- `path` - The absolute filesystem path to a directory from which this FilePathField should get its choice.
|
||||
- `match` - A regular expression, as a string, that FilePathField will use to filter filenames.
|
||||
- `recursive` - Specifies whether all subdirectories of path should be included. Default is `False`.
|
||||
- `allow_files` - Specifies whether files in the specified location should be included. Default is `True`. Either this or `allow_folders` must be `True`.
|
||||
- `allow_folders` - Specifies whether folders in the specified location should be included. Default is `False`. Either this or `allow_files` must be `True`.
|
||||
* `path` - The absolute filesystem path to a directory from which this FilePathField should get its choice.
|
||||
* `match` - A regular expression, as a string, that FilePathField will use to filter filenames.
|
||||
* `recursive` - Specifies whether all subdirectories of path should be included. Default is `False`.
|
||||
* `allow_files` - Specifies whether files in the specified location should be included. Default is `True`. Either this or `allow_folders` must be `True`.
|
||||
* `allow_folders` - Specifies whether folders in the specified location should be included. Default is `False`. Either this or `allow_files` must be `True`.
|
||||
|
||||
## IPAddressField
|
||||
|
||||
|
@ -252,8 +251,8 @@ Corresponds to `django.forms.fields.IPAddressField` and `django.forms.fields.Gen
|
|||
|
||||
**Signature**: `IPAddressField(protocol='both', unpack_ipv4=False, **options)`
|
||||
|
||||
- `protocol` Limits valid inputs to the specified protocol. Accepted values are 'both' (default), 'IPv4' or 'IPv6'. Matching is case insensitive.
|
||||
- `unpack_ipv4` Unpacks IPv4 mapped addresses like ::ffff:192.0.2.1. If this option is enabled that address would be unpacked to 192.0.2.1. Default is disabled. Can only be used when protocol is set to 'both'.
|
||||
* `protocol` Limits valid inputs to the specified protocol. Accepted values are 'both' (default), 'IPv4' or 'IPv6'. Matching is case insensitive.
|
||||
* `unpack_ipv4` Unpacks IPv4 mapped addresses like ::ffff:192.0.2.1. If this option is enabled that address would be unpacked to 192.0.2.1. Default is disabled. Can only be used when protocol is set to 'both'.
|
||||
|
||||
---
|
||||
|
||||
|
@ -267,8 +266,8 @@ Corresponds to `django.db.models.fields.IntegerField`, `django.db.models.fields.
|
|||
|
||||
**Signature**: `IntegerField(max_value=None, min_value=None)`
|
||||
|
||||
- `max_value` Validate that the number provided is no greater than this value.
|
||||
- `min_value` Validate that the number provided is no less than this value.
|
||||
* `max_value` Validate that the number provided is no greater than this value.
|
||||
* `min_value` Validate that the number provided is no less than this value.
|
||||
|
||||
## FloatField
|
||||
|
||||
|
@ -278,8 +277,8 @@ Corresponds to `django.db.models.fields.FloatField`.
|
|||
|
||||
**Signature**: `FloatField(max_value=None, min_value=None)`
|
||||
|
||||
- `max_value` Validate that the number provided is no greater than this value.
|
||||
- `min_value` Validate that the number provided is no less than this value.
|
||||
* `max_value` Validate that the number provided is no greater than this value.
|
||||
* `min_value` Validate that the number provided is no less than this value.
|
||||
|
||||
## DecimalField
|
||||
|
||||
|
@ -289,13 +288,14 @@ Corresponds to `django.db.models.fields.DecimalField`.
|
|||
|
||||
**Signature**: `DecimalField(max_digits, decimal_places, coerce_to_string=None, max_value=None, min_value=None)`
|
||||
|
||||
- `max_digits` The maximum number of digits allowed in the number. It must be either `None` or an integer greater than or equal to `decimal_places`.
|
||||
- `decimal_places` The number of decimal places to store with the number.
|
||||
- `coerce_to_string` Set to `True` if string values should be returned for the representation, or `False` if `Decimal` objects should be returned. Defaults to the same value as the `COERCE_DECIMAL_TO_STRING` settings key, which will be `True` unless overridden. If `Decimal` objects are returned by the serializer, then the final output format will be determined by the renderer. Note that setting `localize` will force the value to `True`.
|
||||
- `max_value` Validate that the number provided is no greater than this value.
|
||||
- `min_value` Validate that the number provided is no less than this value.
|
||||
- `localize` Set to `True` to enable localization of input and output based on the current locale. This will also force `coerce_to_string` to `True`. Defaults to `False`. Note that data formatting is enabled if you have set `USE_L10N=True` in your settings file.
|
||||
- `rounding` Sets the rounding mode used when quantising to the configured precision. Valid values are [`decimal` module rounding modes][python-decimal-rounding-modes]. Defaults to `None`.
|
||||
* `max_digits` The maximum number of digits allowed in the number. It must be either `None` or an integer greater than or equal to `decimal_places`.
|
||||
* `decimal_places` The number of decimal places to store with the number.
|
||||
* `coerce_to_string` Set to `True` if string values should be returned for the representation, or `False` if `Decimal` objects should be returned. Defaults to the same value as the `COERCE_DECIMAL_TO_STRING` settings key, which will be `True` unless overridden. If `Decimal` objects are returned by the serializer, then the final output format will be determined by the renderer. Note that setting `localize` will force the value to `True`.
|
||||
* `max_value` Validate that the number provided is no greater than this value.
|
||||
* `min_value` Validate that the number provided is no less than this value.
|
||||
* `localize` Set to `True` to enable localization of input and output based on the current locale. This will also force `coerce_to_string` to `True`. Defaults to `False`. Note that data formatting is enabled if you have set `USE_L10N=True` in your settings file.
|
||||
* `rounding` Sets the rounding mode used when quantising to the configured precision. Valid values are [`decimal` module rounding modes][python-decimal-rounding-modes]. Defaults to `None`.
|
||||
* `normalize_output` Will normalize the decimal value when serialized. This will strip all trailing zeroes and change the value's precision to the minimum required precision to be able to represent the value without loosing data. Defaults to `False`.
|
||||
|
||||
#### Example usage
|
||||
|
||||
|
@ -307,10 +307,6 @@ And to validate numbers up to anything less than one billion with a resolution o
|
|||
|
||||
serializers.DecimalField(max_digits=19, decimal_places=10)
|
||||
|
||||
This field also takes an optional argument, `coerce_to_string`. If set to `True` the representation will be output as a string. If set to `False` the representation will be left as a `Decimal` instance and the final representation will be determined by the renderer.
|
||||
|
||||
If unset, this will default to the same value as the `COERCE_DECIMAL_TO_STRING` setting, which is `True` unless set otherwise.
|
||||
|
||||
---
|
||||
|
||||
# Date and time fields
|
||||
|
@ -325,7 +321,7 @@ Corresponds to `django.db.models.fields.DateTimeField`.
|
|||
|
||||
* `format` - A string representing the output format. If not specified, this defaults to the same value as the `DATETIME_FORMAT` settings key, which will be `'iso-8601'` unless set. Setting to a format string indicates that `to_representation` return values should be coerced to string output. Format strings are described below. Setting this value to `None` indicates that Python `datetime` objects should be returned by `to_representation`. 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']`.
|
||||
* `default_timezone` - A `pytz.timezone` representing the timezone. If not specified and the `USE_TZ` setting is enabled, this defaults to the [current timezone][django-current-timezone]. If `USE_TZ` is disabled, then datetime objects will be naive.
|
||||
* `default_timezone` - A `tzinfo` subclass (`zoneinfo` or `pytz`) prepresenting the timezone. If not specified and the `USE_TZ` setting is enabled, this defaults to the [current timezone][django-current-timezone]. If `USE_TZ` is disabled, then datetime objects will be naive.
|
||||
|
||||
#### `DateTimeField` format strings.
|
||||
|
||||
|
@ -385,8 +381,8 @@ The representation is a string following this format `'[DD] [HH:[MM:]]ss[.uuuuuu
|
|||
|
||||
**Signature:** `DurationField(max_value=None, min_value=None)`
|
||||
|
||||
- `max_value` Validate that the duration provided is no greater than this value.
|
||||
- `min_value` Validate that the duration provided is no less than this value.
|
||||
* `max_value` Validate that the duration provided is no greater than this value.
|
||||
* `min_value` Validate that the duration provided is no less than this value.
|
||||
|
||||
---
|
||||
|
||||
|
@ -400,10 +396,10 @@ Used by `ModelSerializer` to automatically generate fields if the corresponding
|
|||
|
||||
**Signature:** `ChoiceField(choices)`
|
||||
|
||||
- `choices` - A list of valid values, or a list of `(key, display_name)` tuples.
|
||||
- `allow_blank` - If set to `True` then the empty string should be considered a valid value. If set to `False` then the empty string is considered invalid and will raise a validation error. Defaults to `False`.
|
||||
- `html_cutoff` - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to `None`.
|
||||
- `html_cutoff_text` - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to `"More than {count} items…"`
|
||||
* `choices` - A list of valid values, or a list of `(key, display_name)` tuples.
|
||||
* `allow_blank` - If set to `True` then the empty string should be considered a valid value. If set to `False` then the empty string is considered invalid and will raise a validation error. Defaults to `False`.
|
||||
* `html_cutoff` - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to `None`.
|
||||
* `html_cutoff_text` - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to `"More than {count} items…"`
|
||||
|
||||
Both the `allow_blank` and `allow_null` are valid options on `ChoiceField`, although it is highly recommended that you only use one and not both. `allow_blank` should be preferred for textual choices, and `allow_null` should be preferred for numeric or other non-textual choices.
|
||||
|
||||
|
@ -413,10 +409,10 @@ A field that can accept a set of zero, one or many values, chosen from a limited
|
|||
|
||||
**Signature:** `MultipleChoiceField(choices)`
|
||||
|
||||
- `choices` - A list of valid values, or a list of `(key, display_name)` tuples.
|
||||
- `allow_blank` - If set to `True` then the empty string should be considered a valid value. If set to `False` then the empty string is considered invalid and will raise a validation error. Defaults to `False`.
|
||||
- `html_cutoff` - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to `None`.
|
||||
- `html_cutoff_text` - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to `"More than {count} items…"`
|
||||
* `choices` - A list of valid values, or a list of `(key, display_name)` tuples.
|
||||
* `allow_blank` - If set to `True` then the empty string should be considered a valid value. If set to `False` then the empty string is considered invalid and will raise a validation error. Defaults to `False`.
|
||||
* `html_cutoff` - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to `None`.
|
||||
* `html_cutoff_text` - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to `"More than {count} items…"`
|
||||
|
||||
As with `ChoiceField`, both the `allow_blank` and `allow_null` options are valid, although it is highly recommended that you only use one and not both. `allow_blank` should be preferred for textual choices, and `allow_null` should be preferred for numeric or other non-textual choices.
|
||||
|
||||
|
@ -437,9 +433,9 @@ Corresponds to `django.forms.fields.FileField`.
|
|||
|
||||
**Signature:** `FileField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)`
|
||||
|
||||
- `max_length` - Designates the maximum length for the file name.
|
||||
- `allow_empty_file` - Designates if empty files are allowed.
|
||||
- `use_url` - If set to `True` then URL string values will be used for the output representation. If set to `False` then filename string values will be used for the output representation. Defaults to the value of the `UPLOADED_FILES_USE_URL` settings key, which is `True` unless set otherwise.
|
||||
* `max_length` - Designates the maximum length for the file name.
|
||||
* `allow_empty_file` - Designates if empty files are allowed.
|
||||
* `use_url` - If set to `True` then URL string values will be used for the output representation. If set to `False` then filename string values will be used for the output representation. Defaults to the value of the `UPLOADED_FILES_USE_URL` settings key, which is `True` unless set otherwise.
|
||||
|
||||
## ImageField
|
||||
|
||||
|
@ -449,9 +445,9 @@ Corresponds to `django.forms.fields.ImageField`.
|
|||
|
||||
**Signature:** `ImageField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)`
|
||||
|
||||
- `max_length` - Designates the maximum length for the file name.
|
||||
- `allow_empty_file` - Designates if empty files are allowed.
|
||||
- `use_url` - If set to `True` then URL string values will be used for the output representation. If set to `False` then filename string values will be used for the output representation. Defaults to the value of the `UPLOADED_FILES_USE_URL` settings key, which is `True` unless set otherwise.
|
||||
* `max_length` - Designates the maximum length for the file name.
|
||||
* `allow_empty_file` - Designates if empty files are allowed.
|
||||
* `use_url` - If set to `True` then URL string values will be used for the output representation. If set to `False` then filename string values will be used for the output representation. Defaults to the value of the `UPLOADED_FILES_USE_URL` settings key, which is `True` unless set otherwise.
|
||||
|
||||
Requires either the `Pillow` package or `PIL` package. The `Pillow` package is recommended, as `PIL` is no longer actively maintained.
|
||||
|
||||
|
@ -465,10 +461,10 @@ A field class that validates a list of objects.
|
|||
|
||||
**Signature**: `ListField(child=<A_FIELD_INSTANCE>, allow_empty=True, min_length=None, max_length=None)`
|
||||
|
||||
- `child` - A field instance that should be used for validating the objects in the list. If this argument is not provided then objects in the list will not be validated.
|
||||
- `allow_empty` - Designates if empty lists are allowed.
|
||||
- `min_length` - Validates that the list contains no fewer than this number of elements.
|
||||
- `max_length` - Validates that the list contains no more than this number of elements.
|
||||
* `child` - A field instance that should be used for validating the objects in the list. If this argument is not provided then objects in the list will not be validated.
|
||||
* `allow_empty` - Designates if empty lists are allowed.
|
||||
* `min_length` - Validates that the list contains no fewer than this number of elements.
|
||||
* `max_length` - Validates that the list contains no more than this number of elements.
|
||||
|
||||
For example, to validate a list of integers you might use something like the following:
|
||||
|
||||
|
@ -489,8 +485,8 @@ A field class that validates a dictionary of objects. The keys in `DictField` ar
|
|||
|
||||
**Signature**: `DictField(child=<A_FIELD_INSTANCE>, allow_empty=True)`
|
||||
|
||||
- `child` - A field instance that should be used for validating the values in the dictionary. If this argument is not provided then values in the mapping will not be validated.
|
||||
- `allow_empty` - Designates if empty dictionaries are allowed.
|
||||
* `child` - A field instance that should be used for validating the values in the dictionary. If this argument is not provided then values in the mapping will not be validated.
|
||||
* `allow_empty` - Designates if empty dictionaries are allowed.
|
||||
|
||||
For example, to create a field that validates a mapping of strings to strings, you would write something like this:
|
||||
|
||||
|
@ -507,8 +503,8 @@ A preconfigured `DictField` that is compatible with Django's postgres `HStoreFie
|
|||
|
||||
**Signature**: `HStoreField(child=<A_FIELD_INSTANCE>, allow_empty=True)`
|
||||
|
||||
- `child` - A field instance that is used for validating the values in the dictionary. The default child field accepts both empty strings and null values.
|
||||
- `allow_empty` - Designates if empty dictionaries are allowed.
|
||||
* `child` - A field instance that is used for validating the values in the dictionary. The default child field accepts both empty strings and null values.
|
||||
* `allow_empty` - Designates if empty dictionaries are allowed.
|
||||
|
||||
Note that the child field **must** be an instance of `CharField`, as the hstore extension stores values as strings.
|
||||
|
||||
|
@ -518,8 +514,8 @@ A field class that validates that the incoming data structure consists of valid
|
|||
|
||||
**Signature**: `JSONField(binary, encoder)`
|
||||
|
||||
- `binary` - If set to `True` then the field will output and validate a JSON encoded string, rather than a primitive data structure. Defaults to `False`.
|
||||
- `encoder` - Use this JSON encoder to serialize input object. Defaults to `None`.
|
||||
* `binary` - If set to `True` then the field will output and validate a JSON encoded string, rather than a primitive data structure. Defaults to `False`.
|
||||
* `encoder` - Use this JSON encoder to serialize input object. Defaults to `None`.
|
||||
|
||||
---
|
||||
|
||||
|
@ -570,7 +566,7 @@ This is a read-only field. It gets its value by calling a method on the serializ
|
|||
|
||||
**Signature**: `SerializerMethodField(method_name=None)`
|
||||
|
||||
- `method_name` - The name of the method on the serializer to be called. If not included this defaults to `get_<field_name>`.
|
||||
* `method_name` - The name of the method on the serializer to be called. If not included this defaults to `get_<field_name>`.
|
||||
|
||||
The serializer method referred to by the `method_name` argument 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:
|
||||
|
||||
|
@ -776,7 +772,7 @@ Here the mapping between the target and source attribute pairs (`x` and
|
|||
`x_coordinate`, `y` and `y_coordinate`) is handled in the `IntegerField`
|
||||
declarations. It's our `NestedCoordinateSerializer` that takes `source='*'`.
|
||||
|
||||
Our new `DataPointSerializer` exhibits the same behaviour as the custom field
|
||||
Our new `DataPointSerializer` exhibits the same behavior as the custom field
|
||||
approach.
|
||||
|
||||
Serializing:
|
||||
|
@ -836,7 +832,7 @@ the [djangorestframework-recursive][djangorestframework-recursive] package provi
|
|||
|
||||
## django-rest-framework-gis
|
||||
|
||||
The [django-rest-framework-gis][django-rest-framework-gis] package provides geographic addons for django rest framework like a `GeometryField` field and a GeoJSON serializer.
|
||||
The [django-rest-framework-gis][django-rest-framework-gis] package provides geographic addons for django rest framework like a `GeometryField` field and a GeoJSON serializer.
|
||||
|
||||
## django-rest-framework-hstore
|
||||
|
||||
|
@ -855,3 +851,4 @@ The [django-rest-framework-hstore][django-rest-framework-hstore] package provide
|
|||
[django-hstore]: https://github.com/djangonauts/django-hstore
|
||||
[python-decimal-rounding-modes]: https://docs.python.org/3/library/decimal.html#rounding-modes
|
||||
[django-current-timezone]: https://docs.djangoproject.com/en/stable/topics/i18n/timezones/#default-time-zone-and-current-time-zone
|
||||
[django-docs-select-related]: https://docs.djangoproject.com/en/3.1/ref/models/querysets/#django.db.models.query.QuerySet.select_related
|
||||
|
|
|
@ -224,7 +224,7 @@ The search behavior may be restricted by prepending various characters to the `s
|
|||
|
||||
* '^' Starts-with search.
|
||||
* '=' Exact matches.
|
||||
* '@' Full-text search. (Currently only supported Django's [PostgreSQL backend](https://docs.djangoproject.com/en/dev/ref/contrib/postgres/search/).)
|
||||
* '@' Full-text search. (Currently only supported Django's [PostgreSQL backend][postgres-search].)
|
||||
* '$' Regex search.
|
||||
|
||||
For example:
|
||||
|
@ -241,7 +241,7 @@ To dynamically change search fields based on request content, it's possible to s
|
|||
def get_search_fields(self, view, request):
|
||||
if request.query_params.get('title_only'):
|
||||
return ['title']
|
||||
return super(CustomSearchFilter, self).get_search_fields(view, request)
|
||||
return super().get_search_fields(view, request)
|
||||
|
||||
For more details, see the [Django documentation][search-django-admin].
|
||||
|
||||
|
@ -335,15 +335,6 @@ Generic filters may also present an interface in the browsable API. To do so you
|
|||
|
||||
The method should return a rendered HTML string.
|
||||
|
||||
## Pagination & schemas
|
||||
|
||||
You can also make the filter controls available to the schema autogeneration
|
||||
that REST framework provides, by implementing a `get_schema_fields()` method. This method should have the following signature:
|
||||
|
||||
`get_schema_fields(self, view)`
|
||||
|
||||
The method should return a list of `coreapi.Field` instances.
|
||||
|
||||
# Third party packages
|
||||
|
||||
The following third party packages provide additional filter implementations.
|
||||
|
@ -374,3 +365,4 @@ The [djangorestframework-word-filter][django-rest-framework-word-search-filter]
|
|||
[drf-url-filter]: https://github.com/manjitkumar/drf-url-filters
|
||||
[HStoreField]: https://docs.djangoproject.com/en/3.0/ref/contrib/postgres/fields/#hstorefield
|
||||
[JSONField]: https://docs.djangoproject.com/en/3.0/ref/contrib/postgres/fields/#jsonfield
|
||||
[postgres-search]: https://docs.djangoproject.com/en/stable/ref/contrib/postgres/search/
|
||||
|
|
|
@ -23,8 +23,8 @@ Returns a URL pattern list which includes format suffix patterns appended to eac
|
|||
Arguments:
|
||||
|
||||
* **urlpatterns**: Required. A URL pattern list.
|
||||
* **suffix_required**: Optional. A boolean indicating if suffixes in the URLs should be optional or mandatory. Defaults to `False`, meaning that suffixes are optional by default.
|
||||
* **allowed**: Optional. A list or tuple of valid format suffixes. If not provided, a wildcard format suffix pattern will be used.
|
||||
* **suffix_required**: Optional. A boolean indicating if suffixes in the URLs should be optional or mandatory. Defaults to `False`, meaning that suffixes are optional by default.
|
||||
* **allowed**: Optional. A list or tuple of valid format suffixes. If not provided, a wildcard format suffix pattern will be used.
|
||||
|
||||
Example:
|
||||
|
||||
|
@ -62,7 +62,7 @@ Also note that `format_suffix_patterns` does not support descending into `includ
|
|||
|
||||
If using the `i18n_patterns` function provided by Django, as well as `format_suffix_patterns` you should make sure that the `i18n_patterns` function is applied as the final, or outermost function. For example:
|
||||
|
||||
url patterns = [
|
||||
urlpatterns = [
|
||||
…
|
||||
]
|
||||
|
||||
|
|
|
@ -65,7 +65,7 @@ The following attributes control the basic view behavior.
|
|||
|
||||
* `queryset` - The queryset that should be used for returning objects from this view. Typically, you must either set this attribute, or override the `get_queryset()` method. If you are overriding a view method, it is important that you call `get_queryset()` instead of accessing this property directly, as `queryset` will get evaluated once, and those results will be cached for all subsequent requests.
|
||||
* `serializer_class` - The serializer class that should be used for validating and deserializing input, and for serializing output. Typically, you must either set this attribute, or override the `get_serializer_class()` method.
|
||||
* `lookup_field` - The model field that should be used to for performing object lookup of individual model instances. Defaults to `'pk'`. Note that when using hyperlinked APIs you'll need to ensure that *both* the API views *and* the serializer classes set the lookup fields if you need to use a custom value.
|
||||
* `lookup_field` - The model field that should be used for performing object lookup of individual model instances. Defaults to `'pk'`. Note that when using hyperlinked APIs you'll need to ensure that *both* the API views *and* the serializer classes set the lookup fields if you need to use a custom value.
|
||||
* `lookup_url_kwarg` - The URL keyword argument that should be used for object lookup. The URL conf should include a keyword argument corresponding to this value. If unset this defaults to using the same value as `lookup_field`.
|
||||
|
||||
**Pagination**:
|
||||
|
@ -96,6 +96,12 @@ For example:
|
|||
user = self.request.user
|
||||
return user.accounts.all()
|
||||
|
||||
---
|
||||
|
||||
**Note:** If the `serializer_class` used in the generic view spans orm relations, leading to an n+1 problem, you could optimize your queryset in this method using `select_related` and `prefetch_related`. To get more information about n+1 problem and use cases of the mentioned methods refer to related section in [django documentation][django-docs-select-related].
|
||||
|
||||
---
|
||||
|
||||
#### `get_object(self)`
|
||||
|
||||
Returns an object instance that should be used for detail views. Defaults to using the `lookup_field` parameter to filter the base queryset.
|
||||
|
@ -211,7 +217,7 @@ If the request data provided for creating the object was invalid, a `400 Bad Req
|
|||
|
||||
Provides a `.retrieve(request, *args, **kwargs)` method, that implements returning an existing model instance in a response.
|
||||
|
||||
If an object can be retrieved this returns a `200 OK` response, with a serialized representation of the object as the body of the response. Otherwise it will return a `404 Not Found`.
|
||||
If an object can be retrieved this returns a `200 OK` response, with a serialized representation of the object as the body of the response. Otherwise, it will return a `404 Not Found`.
|
||||
|
||||
## UpdateModelMixin
|
||||
|
||||
|
@ -329,7 +335,7 @@ For example, if you need to lookup objects based on multiple fields in the URL c
|
|||
queryset = self.filter_queryset(queryset) # Apply any filter backends
|
||||
filter = {}
|
||||
for field in self.lookup_fields:
|
||||
if self.kwargs[field]: # Ignore empty fields.
|
||||
if self.kwargs.get(field): # Ignore empty fields.
|
||||
filter[field] = self.kwargs[field]
|
||||
obj = get_object_or_404(queryset, **filter) # Lookup the object
|
||||
self.check_object_permissions(self.request, obj)
|
||||
|
@ -389,3 +395,4 @@ The following third party packages provide additional generic view implementatio
|
|||
[UpdateModelMixin]: #updatemodelmixin
|
||||
[DestroyModelMixin]: #destroymodelmixin
|
||||
[django-rest-multiple-models]: https://github.com/MattBroach/DjangoRestMultipleModels
|
||||
[django-docs-select-related]: https://docs.djangoproject.com/en/3.1/ref/models/querysets/#django.db.models.query.QuerySet.select_related
|
||||
|
|
|
@ -78,7 +78,7 @@ This pagination style accepts a single number page number in the request query p
|
|||
|
||||
HTTP 200 OK
|
||||
{
|
||||
"count": 1023
|
||||
"count": 1023,
|
||||
"next": "https://api.example.org/accounts/?page=5",
|
||||
"previous": "https://api.example.org/accounts/?page=3",
|
||||
"results": [
|
||||
|
@ -126,7 +126,7 @@ This pagination style mirrors the syntax used when looking up multiple database
|
|||
|
||||
HTTP 200 OK
|
||||
{
|
||||
"count": 1023
|
||||
"count": 1023,
|
||||
"next": "https://api.example.org/accounts/?limit=100&offset=500",
|
||||
"previous": "https://api.example.org/accounts/?limit=100&offset=300",
|
||||
"results": [
|
||||
|
@ -227,7 +227,7 @@ Note that the `paginate_queryset` method may set state on the pagination instanc
|
|||
|
||||
## Example
|
||||
|
||||
Suppose we want to replace the default pagination output style with a modified format that includes the next and previous links under in a nested 'links' key. We could specify a custom pagination class like so:
|
||||
Suppose we want to replace the default pagination output style with a modified format that includes the next and previous links under in a nested 'links' key. We could specify a custom pagination class like so:
|
||||
|
||||
class CustomPagination(pagination.PageNumberPagination):
|
||||
def get_paginated_response(self, data):
|
||||
|
@ -264,15 +264,6 @@ API responses for list endpoints will now include a `Link` header, instead of in
|
|||
|
||||
*A custom pagination style, using the 'Link' header'*
|
||||
|
||||
## Pagination & schemas
|
||||
|
||||
You can also make the pagination controls available to the schema autogeneration
|
||||
that REST framework provides, by implementing a `get_schema_fields()` method. This method should have the following signature:
|
||||
|
||||
`get_schema_fields(self, view)`
|
||||
|
||||
The method should return a list of `coreapi.Field` instances.
|
||||
|
||||
---
|
||||
|
||||
# HTML pagination controls
|
||||
|
@ -312,7 +303,7 @@ The [`drf-proxy-pagination` package][drf-proxy-pagination] includes a `ProxyPagi
|
|||
|
||||
## link-header-pagination
|
||||
|
||||
The [`django-rest-framework-link-header-pagination` package][drf-link-header-pagination] includes a `LinkHeaderPagination` class which provides pagination via an HTTP `Link` header as described in [Github's developer documentation](github-link-pagination).
|
||||
The [`django-rest-framework-link-header-pagination` package][drf-link-header-pagination] includes a `LinkHeaderPagination` class which provides pagination via an HTTP `Link` header as described in [GitHub REST API documentation][github-traversing-with-pagination].
|
||||
|
||||
[cite]: https://docs.djangoproject.com/en/stable/topics/pagination/
|
||||
[link-header]: ../img/link-header-pagination.png
|
||||
|
@ -322,3 +313,4 @@ The [`django-rest-framework-link-header-pagination` package][drf-link-header-pag
|
|||
[drf-link-header-pagination]: https://github.com/tbeadle/django-rest-framework-link-header-pagination
|
||||
[disqus-cursor-api]: https://cra.mr/2011/03/08/building-cursors-for-the-disqus-api
|
||||
[float_cursor_pagination_example]: https://gist.github.com/keturn/8bc88525a183fd41c73ffb729b8865be#file-fpcursorpagination-py
|
||||
[github-traversing-with-pagination]: https://docs.github.com/en/rest/guides/traversing-with-pagination
|
||||
|
|
|
@ -15,7 +15,7 @@ REST framework includes a number of built in Parser classes, that allow you to a
|
|||
|
||||
## How the parser is determined
|
||||
|
||||
The set of valid parsers for a view is always defined as a list of classes. When `request.data` is accessed, REST framework will examine the `Content-Type` header on the incoming request, and determine which parser to use to parse the request content.
|
||||
The set of valid parsers for a view is always defined as a list of classes. When `request.data` 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.
|
||||
|
||||
---
|
||||
|
||||
|
@ -87,7 +87,7 @@ You will typically want to use both `FormParser` and `MultiPartParser` together
|
|||
|
||||
## MultiPartParser
|
||||
|
||||
Parses multipart HTML form content, which supports file uploads. Both `request.data` will be populated with a `QueryDict`.
|
||||
Parses multipart HTML form content, which supports file uploads. `request.data` and `request.FILES` will be populated with a `QueryDict` and `MultiValueDict` respectively.
|
||||
|
||||
You will typically want to use both `FormParser` and `MultiPartParser` together in order to fully support HTML form data.
|
||||
|
||||
|
|
|
@ -24,9 +24,9 @@ A slightly less strict style of permission would be to allow full access to auth
|
|||
Permissions in REST framework are always defined as a list of permission classes.
|
||||
|
||||
Before running the main body of the view each permission in the list is checked.
|
||||
If any permission check fails an `exceptions.PermissionDenied` or `exceptions.NotAuthenticated` exception will be raised, and the main body of the view will not run.
|
||||
If any permission check fails, an `exceptions.PermissionDenied` or `exceptions.NotAuthenticated` exception will be raised, and the main body of the view will not run.
|
||||
|
||||
When the permissions checks fail either a "403 Forbidden" or a "401 Unauthorized" response will be returned, according to the following rules:
|
||||
When the permission checks fail, either a "403 Forbidden" or a "401 Unauthorized" response will be returned, according to the following rules:
|
||||
|
||||
* The request was successfully authenticated, but permission was denied. *— An HTTP 403 Forbidden response will be returned.*
|
||||
* The request was not successfully authenticated, and the highest priority authentication class *does not* use `WWW-Authenticate` headers. *— An HTTP 403 Forbidden response will be returned.*
|
||||
|
@ -171,13 +171,14 @@ This permission is suitable if you want to your API to allow read permissions to
|
|||
|
||||
## DjangoModelPermissions
|
||||
|
||||
This permission class ties into Django's standard `django.contrib.auth` [model permissions][contribauth]. This permission must only be applied to views that have a `.queryset` property or `get_queryset()` method. Authorization will only be granted if the user *is authenticated* and has the *relevant model permissions* assigned.
|
||||
This permission class ties into Django's standard `django.contrib.auth` [model permissions][contribauth]. This permission must only be applied to views that have a `.queryset` property or `get_queryset()` method. Authorization will only be granted if the user *is authenticated* and has the *relevant model permissions* assigned. The appropriate model is determined by checking `get_queryset().model` or `queryset.model`.
|
||||
|
||||
* `GET` requests require the user to have the `view` or `change` permission on the model
|
||||
* `POST` requests require the user to have the `add` permission on the model.
|
||||
* `PUT` and `PATCH` requests require the user to have the `change` permission on the model.
|
||||
* `DELETE` requests require the user to have the `delete` permission on the model.
|
||||
|
||||
The default behaviour can also be overridden to support custom model permissions. For example, you might want to include a `view` model permission for `GET` requests.
|
||||
The default behaviour can also be overridden to support custom model permissions.
|
||||
|
||||
To use custom model permissions, override `DjangoModelPermissions` and set the `.perms_map` property. Refer to the source code for details.
|
||||
|
||||
|
@ -201,7 +202,7 @@ As with `DjangoModelPermissions` you can use custom model permissions by overrid
|
|||
|
||||
---
|
||||
|
||||
**Note**: If you need object level `view` permissions for `GET`, `HEAD` and `OPTIONS` requests and are using django-guardian for your object-level permissions backend, you'll want to consider using the `DjangoObjectPermissionsFilter` class provided by the [`djangorestframework-guardian` package][django-rest-framework-guardian]. It ensures that list endpoints only return results including objects for which the user has appropriate view permissions.
|
||||
**Note**: If you need object level `view` permissions for `GET`, `HEAD` and `OPTIONS` requests and are using django-guardian for your object-level permissions backend, you'll want to consider using the `DjangoObjectPermissionsFilter` class provided by the [`djangorestframework-guardian2` package][django-rest-framework-guardian2]. It ensures that list endpoints only return results including objects for which the user has appropriate view permissions.
|
||||
|
||||
---
|
||||
|
||||
|
@ -286,7 +287,7 @@ The following table lists the access restriction methods and the level of contro
|
|||
|
||||
| | `queryset` | `permission_classes` | `serializer_class` |
|
||||
|------------------------------------|------------|----------------------|--------------------|
|
||||
| Action: list | global | no | object-level* |
|
||||
| Action: list | global | global | object-level* |
|
||||
| Action: create | no | global | object-level |
|
||||
| Action: retrieve | global | object-level | object-level |
|
||||
| Action: update | global | object-level | object-level |
|
||||
|
@ -324,6 +325,10 @@ The [DRY Rest Permissions][dry-rest-permissions] package provides the ability to
|
|||
|
||||
The [Django Rest Framework Roles][django-rest-framework-roles] package makes it easier to parameterize your API over multiple types of users.
|
||||
|
||||
## Rest Framework Roles
|
||||
|
||||
The [Rest Framework Roles][rest-framework-roles] makes it super easy to protect views based on roles. Most importantly allows you to decouple accessibility logic from models and views in a clean human-readable way.
|
||||
|
||||
## Django REST Framework API Key
|
||||
|
||||
The [Django REST Framework API Key][djangorestframework-api-key] package provides permissions classes, models and helpers to add API key authorization to your API. It can be used to authorize internal or third-party backends and services (i.e. _machines_) which do not have a user account. API keys are stored securely using Django's password hashing infrastructure, and they can be viewed, edited and revoked at anytime in the Django admin.
|
||||
|
@ -349,8 +354,9 @@ The [Django Rest Framework PSQ][drf-psq] package is an extension that gives supp
|
|||
[rest-condition]: https://github.com/caxap/rest_condition
|
||||
[dry-rest-permissions]: https://github.com/FJNR-inc/dry-rest-permissions
|
||||
[django-rest-framework-roles]: https://github.com/computer-lab/django-rest-framework-roles
|
||||
[rest-framework-roles]: https://github.com/Pithikos/rest-framework-roles
|
||||
[djangorestframework-api-key]: https://florimondmanca.github.io/djangorestframework-api-key/
|
||||
[django-rest-framework-role-filters]: https://github.com/allisson/django-rest-framework-role-filters
|
||||
[django-rest-framework-guardian]: https://github.com/rpkilby/django-rest-framework-guardian
|
||||
[django-rest-framework-guardian2]: https://github.com/johnthagen/django-rest-framework-guardian2
|
||||
[drf-access-policy]: https://github.com/rsinger86/drf-access-policy
|
||||
[drf-psq]: https://github.com/drf-psq/drf-psq
|
||||
|
|
|
@ -17,6 +17,37 @@ Relational fields are used to represent model relationships. They can be applie
|
|||
|
||||
---
|
||||
|
||||
---
|
||||
|
||||
**Note:** REST Framework does not attempt to automatically optimize querysets passed to serializers in terms of `select_related` and `prefetch_related` since it would be too much magic. A serializer with a field spanning an orm relation through its source attribute could require an additional database hit to fetch related objects from the database. It is the programmer's responsibility to optimize queries to avoid additional database hits which could occur while using such a serializer.
|
||||
|
||||
For example, the following serializer would lead to a database hit each time evaluating the tracks field if it is not prefetched:
|
||||
|
||||
class AlbumSerializer(serializers.ModelSerializer):
|
||||
tracks = serializers.SlugRelatedField(
|
||||
many=True,
|
||||
read_only=True,
|
||||
slug_field='title'
|
||||
)
|
||||
|
||||
class Meta:
|
||||
model = Album
|
||||
fields = ['album_name', 'artist', 'tracks']
|
||||
|
||||
# For each album object, tracks should be fetched from database
|
||||
qs = Album.objects.all()
|
||||
print(AlbumSerializer(qs, many=True).data)
|
||||
|
||||
If `AlbumSerializer` is used to serialize a fairly large queryset with `many=True` then it could be a serious performance problem. Optimizing the queryset passed to `AlbumSerializer` with:
|
||||
|
||||
qs = Album.objects.prefetch_related('tracks')
|
||||
# No additional database hits required
|
||||
print(AlbumSerializer(qs, many=True).data)
|
||||
|
||||
would solve the issue.
|
||||
|
||||
---
|
||||
|
||||
#### Inspecting relationships.
|
||||
|
||||
When using the `ModelSerializer` class, serializer fields and relationships will be automatically generated for you. Inspecting these automatically generated fields can be a useful tool for determining how to customize the relationship style.
|
||||
|
@ -215,7 +246,7 @@ When using `SlugRelatedField` as a read-write field, you will normally want to e
|
|||
|
||||
## HyperlinkedIdentityField
|
||||
|
||||
This field can be applied as an identity relationship, such as the `'url'` field on a HyperlinkedModelSerializer. It can also be used for an attribute on the object. For example, the following serializer:
|
||||
This field can be applied as an identity relationship, such as the `'url'` field on a HyperlinkedModelSerializer. It can also be used for an attribute on the object. For example, the following serializer:
|
||||
|
||||
class AlbumSerializer(serializers.HyperlinkedModelSerializer):
|
||||
track_listing = serializers.HyperlinkedIdentityField(view_name='track-list')
|
||||
|
@ -247,7 +278,7 @@ This field is always read-only.
|
|||
|
||||
As opposed to previously discussed _references_ to another entity, the referred entity can instead also be embedded or _nested_
|
||||
in the representation of the object that refers to it.
|
||||
Such nested relationships can be expressed by using serializers as fields.
|
||||
Such nested relationships can be expressed by using serializers as fields.
|
||||
|
||||
If the field is used to represent a to-many relationship, you should add the `many=True` flag to the serializer field.
|
||||
|
||||
|
@ -463,8 +494,8 @@ This behavior is intended to prevent a template from being unable to render in a
|
|||
|
||||
There are two keyword arguments you can use to control this behavior:
|
||||
|
||||
- `html_cutoff` - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Set to `None` to disable any limiting. Defaults to `1000`.
|
||||
- `html_cutoff_text` - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to `"More than {count} items…"`
|
||||
* `html_cutoff` - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Set to `None` to disable any limiting. Defaults to `1000`.
|
||||
* `html_cutoff_text` - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to `"More than {count} items…"`
|
||||
|
||||
You can also control these globally using the settings `HTML_SELECT_CUTOFF` and `HTML_SELECT_CUTOFF_TEXT`.
|
||||
|
||||
|
|
|
@ -105,7 +105,7 @@ The TemplateHTMLRenderer will create a `RequestContext`, using the `response.dat
|
|||
|
||||
---
|
||||
|
||||
**Note:** When used with a view that makes use of a serializer the `Response` sent for rendering may not be a dictionay and will need to be wrapped in a dict before returning to allow the TemplateHTMLRenderer to render it. For example:
|
||||
**Note:** When used with a view that makes use of a serializer the `Response` sent for rendering may not be a dictionary and will need to be wrapped in a dict before returning to allow the `TemplateHTMLRenderer` to render it. For example:
|
||||
|
||||
```
|
||||
response.data = {'results': response.data}
|
||||
|
@ -192,7 +192,7 @@ By default the response content will be rendered with the highest priority rende
|
|||
def get_default_renderer(self, view):
|
||||
return JSONRenderer()
|
||||
|
||||
## AdminRenderer
|
||||
## AdminRenderer
|
||||
|
||||
Renders data into HTML for an admin-like display:
|
||||
|
||||
|
@ -257,7 +257,7 @@ This renderer is used for rendering HTML multipart form data. **It is not suita
|
|||
|
||||
# Custom renderers
|
||||
|
||||
To implement a custom renderer, you should override `BaseRenderer`, set the `.media_type` and `.format` properties, and implement the `.render(self, data, media_type=None, renderer_context=None)` method.
|
||||
To implement a custom renderer, you should override `BaseRenderer`, set the `.media_type` and `.format` properties, and implement the `.render(self, data, accepted_media_type=None, renderer_context=None)` method.
|
||||
|
||||
The method should return a bytestring, which will be used as the body of the HTTP response.
|
||||
|
||||
|
@ -267,7 +267,7 @@ The arguments passed to the `.render()` method are:
|
|||
|
||||
The request data, as set by the `Response()` instantiation.
|
||||
|
||||
### `media_type=None`
|
||||
### `accepted_media_type=None`
|
||||
|
||||
Optional. If provided, this is the accepted media type, as determined by the content negotiation stage.
|
||||
|
||||
|
@ -291,7 +291,7 @@ The following is an example plaintext renderer that will return a response with
|
|||
media_type = 'text/plain'
|
||||
format = 'txt'
|
||||
|
||||
def render(self, data, media_type=None, renderer_context=None):
|
||||
def render(self, data, accepted_media_type=None, renderer_context=None):
|
||||
return smart_text(data, encoding=self.charset)
|
||||
|
||||
## Setting the character set
|
||||
|
@ -303,7 +303,7 @@ By default renderer classes are assumed to be using the `UTF-8` encoding. To us
|
|||
format = 'txt'
|
||||
charset = 'iso-8859-1'
|
||||
|
||||
def render(self, data, media_type=None, renderer_context=None):
|
||||
def render(self, data, accepted_media_type=None, renderer_context=None):
|
||||
return data.encode(self.charset)
|
||||
|
||||
Note that if a renderer class returns a unicode string, then the response content will be coerced into a bytestring by the `Response` class, with the `charset` attribute set on the renderer used to determine the encoding.
|
||||
|
@ -318,7 +318,7 @@ In some cases you may also want to set the `render_style` attribute to `'binary'
|
|||
charset = None
|
||||
render_style = 'binary'
|
||||
|
||||
def render(self, data, media_type=None, renderer_context=None):
|
||||
def render(self, data, accepted_media_type=None, renderer_context=None):
|
||||
return data
|
||||
|
||||
---
|
||||
|
@ -332,7 +332,7 @@ You can do some pretty flexible things using REST framework's renderers. Some e
|
|||
* Specify multiple types of HTML representation for API clients to use.
|
||||
* Underspecify a renderer's media type, such as using `media_type = 'image/*'`, and use the `Accept` header to vary the encoding of the response.
|
||||
|
||||
## Varying behaviour by media type
|
||||
## Varying behavior by media type
|
||||
|
||||
In some cases you might want your view to use different serialization styles depending on the accepted media type. If you need to do this you can access `request.accepted_renderer` to determine the negotiated renderer that will be used for the response.
|
||||
|
||||
|
@ -470,15 +470,15 @@ Modify your REST framework settings.
|
|||
|
||||
[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.
|
||||
|
||||
## XLSX (Binary Spreadsheet Endpoints)
|
||||
## Microsoft Excel: XLSX (Binary Spreadsheet Endpoints)
|
||||
|
||||
XLSX is the world's most popular binary spreadsheet format. [Tim Allen][flipperpa] of [The Wharton School][wharton] maintains [drf-renderer-xlsx][drf-renderer-xlsx], which renders an endpoint as an XLSX spreadsheet using OpenPyXL, and allows the client to download it. Spreadsheets can be styled on a per-view basis.
|
||||
XLSX is the world's most popular binary spreadsheet format. [Tim Allen][flipperpa] of [The Wharton School][wharton] maintains [drf-excel][drf-excel], which renders an endpoint as an XLSX spreadsheet using OpenPyXL, and allows the client to download it. Spreadsheets can be styled on a per-view basis.
|
||||
|
||||
#### Installation & configuration
|
||||
|
||||
Install using pip.
|
||||
|
||||
$ pip install drf-renderer-xlsx
|
||||
$ pip install drf-excel
|
||||
|
||||
Modify your REST framework settings.
|
||||
|
||||
|
@ -488,15 +488,15 @@ Modify your REST framework settings.
|
|||
'DEFAULT_RENDERER_CLASSES': [
|
||||
'rest_framework.renderers.JSONRenderer',
|
||||
'rest_framework.renderers.BrowsableAPIRenderer',
|
||||
'drf_renderer_xlsx.renderers.XLSXRenderer',
|
||||
'drf_excel.renderers.XLSXRenderer',
|
||||
],
|
||||
}
|
||||
|
||||
To avoid having a file streamed without a filename (which the browser will often default to the filename "download", with no extension), we need to use a mixin to override the `Content-Disposition` header. If no filename is provided, it will default to `export.xlsx`. For example:
|
||||
|
||||
from rest_framework.viewsets import ReadOnlyModelViewSet
|
||||
from drf_renderer_xlsx.mixins import XLSXFileMixin
|
||||
from drf_renderer_xlsx.renderers import XLSXRenderer
|
||||
from drf_excel.mixins import XLSXFileMixin
|
||||
from drf_excel.renderers import XLSXRenderer
|
||||
|
||||
from .models import MyExampleModel
|
||||
from .serializers import MyExampleSerializer
|
||||
|
@ -528,7 +528,7 @@ Comma-separated values are a plain-text tabular data format, that can be easily
|
|||
[Rest Framework Latex] provides a renderer that outputs PDFs using Laulatex. It is maintained by [Pebble (S/F Software)][mypebble].
|
||||
|
||||
|
||||
[cite]: https://docs.djangoproject.com/en/stable/stable/template-response/#the-rendering-process
|
||||
[cite]: https://docs.djangoproject.com/en/stable/ref/template-response/#the-rendering-process
|
||||
[conneg]: content-negotiation.md
|
||||
[html-and-forms]: ../topics/html-and-forms.md
|
||||
[browser-accept-headers]: http://www.gethifi.com/blog/browser-rest-http-accept-headers
|
||||
|
@ -549,7 +549,7 @@ Comma-separated values are a plain-text tabular data format, that can be easily
|
|||
[mjumbewu]: https://github.com/mjumbewu
|
||||
[flipperpa]: https://github.com/flipperpa
|
||||
[wharton]: https://github.com/wharton
|
||||
[drf-renderer-xlsx]: https://github.com/wharton/drf-renderer-xlsx
|
||||
[drf-excel]: https://github.com/wharton/drf-excel
|
||||
[vbabiy]: https://github.com/vbabiy
|
||||
[rest-framework-yaml]: https://jpadilla.github.io/django-rest-framework-yaml/
|
||||
[rest-framework-xml]: https://jpadilla.github.io/django-rest-framework-xml/
|
||||
|
|
|
@ -49,7 +49,7 @@ If a client sends a request with a content-type that cannot be parsed then a `Un
|
|||
|
||||
# Content negotiation
|
||||
|
||||
The request exposes some properties that allow you to determine the result of the content negotiation stage. This allows you to implement behaviour such as selecting a different serialization schemes for different media types.
|
||||
The request exposes some properties that allow you to determine the result of the content negotiation stage. This allows you to implement behavior such as selecting a different serialization schemes for different media types.
|
||||
|
||||
## .accepted_renderer
|
||||
|
||||
|
|
|
@ -32,16 +32,16 @@ You should **include the request as a keyword argument** to the function, for ex
|
|||
|
||||
from rest_framework.reverse import reverse
|
||||
from rest_framework.views import APIView
|
||||
from django.utils.timezone import now
|
||||
from django.utils.timezone import now
|
||||
|
||||
class APIRootView(APIView):
|
||||
def get(self, request):
|
||||
year = now().year
|
||||
data = {
|
||||
...
|
||||
'year-summary-url': reverse('year-summary', args=[year], request=request)
|
||||
class APIRootView(APIView):
|
||||
def get(self, request):
|
||||
year = now().year
|
||||
data = {
|
||||
...
|
||||
'year-summary-url': reverse('year-summary', args=[year], request=request)
|
||||
}
|
||||
return Response(data)
|
||||
return Response(data)
|
||||
|
||||
## reverse_lazy
|
||||
|
||||
|
|
|
@ -167,12 +167,23 @@ This behavior can be modified by setting the `trailing_slash` argument to `False
|
|||
|
||||
Trailing slashes are conventional in Django, but are not used by default in some other frameworks such as Rails. Which style you choose to use is largely a matter of preference, although some javascript frameworks may expect a particular routing style.
|
||||
|
||||
The router will match lookup values containing any characters except slashes and period characters. For a more restrictive (or lenient) lookup pattern, set the `lookup_value_regex` attribute on the viewset. For example, you can limit the lookup to valid UUIDs:
|
||||
By default the URLs created by `SimpleRouter` use regular expressions. This behavior can be modified by setting the `use_regex_path` argument to `False` when instantiating the router, in this case [path converters][path-converters-topic-reference] are used. For example:
|
||||
|
||||
router = SimpleRouter(use_regex_path=False)
|
||||
|
||||
**Note**: `use_regex_path=False` only works with Django 2.x or above, since this feature was introduced in 2.0.0. See [release note][simplified-routing-release-note]
|
||||
|
||||
|
||||
The router will match lookup values containing any characters except slashes and period characters. For a more restrictive (or lenient) lookup pattern, set the `lookup_value_regex` attribute on the viewset or `lookup_value_converter` if using path converters. For example, you can limit the lookup to valid UUIDs:
|
||||
|
||||
class MyModelViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet):
|
||||
lookup_field = 'my_model_id'
|
||||
lookup_value_regex = '[0-9a-f]{32}'
|
||||
|
||||
class MyPathModelViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet):
|
||||
lookup_field = 'my_model_uuid'
|
||||
lookup_value_converter = 'uuid'
|
||||
|
||||
## DefaultRouter
|
||||
|
||||
This router is similar to `SimpleRouter` as above, but additionally includes a default API root view, that returns a response containing hyperlinks to all the list views. It also generates routes for optional `.json` style format suffixes.
|
||||
|
@ -338,5 +349,7 @@ The [`DRF-extensions` package][drf-extensions] provides [routers][drf-extensions
|
|||
[drf-extensions-nested-viewsets]: https://chibisov.github.io/drf-extensions/docs/#nested-routes
|
||||
[drf-extensions-collection-level-controllers]: https://chibisov.github.io/drf-extensions/docs/#collection-level-controllers
|
||||
[drf-extensions-customizable-endpoint-names]: https://chibisov.github.io/drf-extensions/docs/#controller-endpoint-name
|
||||
[url-namespace-docs]: https://docs.djangoproject.com/en/1.11/topics/http/urls/#url-namespaces
|
||||
[include-api-reference]: https://docs.djangoproject.com/en/2.0/ref/urls/#include
|
||||
[url-namespace-docs]: https://docs.djangoproject.com/en/4.0/topics/http/urls/#url-namespaces
|
||||
[include-api-reference]: https://docs.djangoproject.com/en/4.0/ref/urls/#include
|
||||
[simplified-routing-release-note]: https://docs.djangoproject.com/en/2.0/releases/2.0/#simplified-url-routing-syntax
|
||||
[path-converters-topic-reference]: https://docs.djangoproject.com/en/2.0/topics/http/urls/#path-converters
|
||||
|
|
|
@ -9,6 +9,23 @@ source:
|
|||
>
|
||||
> — Heroku, [JSON Schema for the Heroku Platform API][cite]
|
||||
|
||||
---
|
||||
|
||||
**Deprecation notice:**
|
||||
|
||||
REST framework's built-in support for generating OpenAPI schemas is
|
||||
**deprecated** in favor of 3rd party packages that can provide this
|
||||
functionality instead. The built-in support will be moved into a separate
|
||||
package and then subsequently retired over the next releases.
|
||||
|
||||
As a full-fledged replacement, we recommend the [drf-spectacular] package.
|
||||
It has extensive support for generating OpenAPI 3 schemas from
|
||||
REST framework APIs, with both automatic and customisable options available.
|
||||
For further information please refer to
|
||||
[Documenting your API](../topics/documenting-your-api.md#drf-spectacular).
|
||||
|
||||
---
|
||||
|
||||
API schemas are a useful tool that allow for a range of use cases, including
|
||||
generating reference documentation, or driving dynamic client libraries that
|
||||
can interact with your API.
|
||||
|
@ -122,6 +139,7 @@ The `get_schema_view()` helper takes the following keyword arguments:
|
|||
url='https://www.example.org/api/',
|
||||
patterns=schema_url_patterns,
|
||||
)
|
||||
* `public`: May be used to specify if schema should bypass views permissions. Default to False
|
||||
|
||||
* `generator_class`: May be used to specify a `SchemaGenerator` subclass to be
|
||||
passed to the `SchemaView`.
|
||||
|
@ -165,7 +183,7 @@ In order to customize the top-level schema, subclass
|
|||
as an argument to the `generateschema` command or `get_schema_view()` helper
|
||||
function.
|
||||
|
||||
### get_schema(self, request)
|
||||
### get_schema(self, request=None, public=False)
|
||||
|
||||
Returns a dictionary that represents the OpenAPI schema:
|
||||
|
||||
|
@ -292,7 +310,7 @@ class CustomView(APIView):
|
|||
|
||||
This saves you having to create a custom subclass per-view for a commonly used option.
|
||||
|
||||
Not all `AutoSchema` methods expose related `__init__()` kwargs, but those for
|
||||
Not all `AutoSchema` methods expose related `__init__()` kwargs, but those for
|
||||
the more commonly needed options do.
|
||||
|
||||
### `AutoSchema` methods
|
||||
|
@ -300,7 +318,7 @@ the more commonly needed options do.
|
|||
#### `get_components()`
|
||||
|
||||
Generates the OpenAPI components that describe request and response bodies,
|
||||
deriving their properties from the serializer.
|
||||
deriving their properties from the serializer.
|
||||
|
||||
Returns a dictionary mapping the component name to the generated
|
||||
representation. By default this has just a single pair but you may override
|
||||
|
@ -313,6 +331,11 @@ Computes the component's name from the serializer.
|
|||
|
||||
You may see warnings if your API has duplicate component names. If so you can override `get_component_name()` or pass the `component_name` `__init__()` kwarg (see below) to provide different names.
|
||||
|
||||
#### `get_reference()`
|
||||
|
||||
Returns a reference to the serializer component. This may be useful if you override `get_schema()`.
|
||||
|
||||
|
||||
#### `map_serializer()`
|
||||
|
||||
Maps serializers to their OpenAPI representations.
|
||||
|
@ -432,3 +455,4 @@ create a base `AutoSchema` subclass for your project that takes additional
|
|||
[openapi-generator]: https://github.com/OpenAPITools/openapi-generator
|
||||
[swagger-codegen]: https://github.com/swagger-api/swagger-codegen
|
||||
[info-object]: https://swagger.io/specification/#infoObject
|
||||
[drf-spectacular]: https://drf-spectacular.readthedocs.io/en/latest/readme.html
|
||||
|
|
|
@ -116,7 +116,7 @@ Calling `.save()` will either create a new instance, or update an existing insta
|
|||
# .save() will update the existing `comment` instance.
|
||||
serializer = CommentSerializer(comment, data=data)
|
||||
|
||||
Both the `.create()` and `.update()` methods are optional. You can implement either neither, one, or both of them, depending on the use-case for your serializer class.
|
||||
Both the `.create()` and `.update()` methods are optional. You can implement either none, one, or both of them, depending on the use-case for your serializer class.
|
||||
|
||||
#### Passing additional attributes to `.save()`
|
||||
|
||||
|
@ -226,7 +226,7 @@ Individual fields on a serializer can include validators, by declaring them on t
|
|||
raise serializers.ValidationError('Not a multiple of ten')
|
||||
|
||||
class GameRecord(serializers.Serializer):
|
||||
score = IntegerField(validators=[multiple_of_ten])
|
||||
score = serializers.IntegerField(validators=[multiple_of_ten])
|
||||
...
|
||||
|
||||
Serializer classes can also include reusable validators that are applied to the complete set of field data. These validators are included by declaring them on an inner `Meta` class, like so:
|
||||
|
@ -524,6 +524,7 @@ You can add extra fields to a `ModelSerializer` or override the default fields b
|
|||
|
||||
class Meta:
|
||||
model = Account
|
||||
fields = ['url', 'groups']
|
||||
|
||||
Extra fields can correspond to any property or callable on the model.
|
||||
|
||||
|
@ -593,15 +594,15 @@ The ModelSerializer class also exposes an API that you can override in order to
|
|||
|
||||
Normally if a `ModelSerializer` does not generate the fields you need by default then you should either add them to the class explicitly, or simply use a regular `Serializer` class instead. However in some cases you may want to create a new base class that defines how the serializer fields are created for any given model.
|
||||
|
||||
### `.serializer_field_mapping`
|
||||
### `serializer_field_mapping`
|
||||
|
||||
A mapping of Django model fields to REST framework serializer fields. You can override this mapping to alter the default serializer fields that should be used for each model field.
|
||||
|
||||
### `.serializer_related_field`
|
||||
### `serializer_related_field`
|
||||
|
||||
This property should be the serializer field class, that is used for relational fields by default.
|
||||
|
||||
For `ModelSerializer` this defaults to `PrimaryKeyRelatedField`.
|
||||
For `ModelSerializer` this defaults to `serializers.PrimaryKeyRelatedField`.
|
||||
|
||||
For `HyperlinkedModelSerializer` this defaults to `serializers.HyperlinkedRelatedField`.
|
||||
|
||||
|
@ -621,13 +622,13 @@ Defaults to `serializers.ChoiceField`
|
|||
|
||||
The following methods are called to determine the class and keyword arguments for each field that should be automatically included on the serializer. Each of these methods should return a two tuple of `(field_class, field_kwargs)`.
|
||||
|
||||
### `.build_standard_field(self, field_name, model_field)`
|
||||
### `build_standard_field(self, field_name, model_field)`
|
||||
|
||||
Called to generate a serializer field that maps to a standard model field.
|
||||
|
||||
The default implementation returns a serializer class based on the `serializer_field_mapping` attribute.
|
||||
|
||||
### `.build_relational_field(self, field_name, relation_info)`
|
||||
### `build_relational_field(self, field_name, relation_info)`
|
||||
|
||||
Called to generate a serializer field that maps to a relational model field.
|
||||
|
||||
|
@ -635,7 +636,7 @@ The default implementation returns a serializer class based on the `serializer_r
|
|||
|
||||
The `relation_info` argument is a named tuple, that contains `model_field`, `related_model`, `to_many` and `has_through_model` properties.
|
||||
|
||||
### `.build_nested_field(self, field_name, relation_info, nested_depth)`
|
||||
### `build_nested_field(self, field_name, relation_info, nested_depth)`
|
||||
|
||||
Called to generate a serializer field that maps to a relational model field, when the `depth` option has been set.
|
||||
|
||||
|
@ -645,17 +646,17 @@ The `nested_depth` will be the value of the `depth` option, minus one.
|
|||
|
||||
The `relation_info` argument is a named tuple, that contains `model_field`, `related_model`, `to_many` and `has_through_model` properties.
|
||||
|
||||
### `.build_property_field(self, field_name, model_class)`
|
||||
### `build_property_field(self, field_name, model_class)`
|
||||
|
||||
Called to generate a serializer field that maps to a property or zero-argument method on the model class.
|
||||
|
||||
The default implementation returns a `ReadOnlyField` class.
|
||||
|
||||
### `.build_url_field(self, field_name, model_class)`
|
||||
### `build_url_field(self, field_name, model_class)`
|
||||
|
||||
Called to generate a serializer field for the serializer's own `url` field. The default implementation returns a `HyperlinkedIdentityField` class.
|
||||
|
||||
### `.build_unknown_field(self, field_name, model_class)`
|
||||
### `build_unknown_field(self, field_name, model_class)`
|
||||
|
||||
Called when the field name did not map to any model field or model property.
|
||||
The default implementation raises an error, although subclasses may customize this behavior.
|
||||
|
@ -755,6 +756,14 @@ The following argument can also be passed to a `ListSerializer` field or a seria
|
|||
|
||||
This is `True` by default, but can be set to `False` if you want to disallow empty lists as valid input.
|
||||
|
||||
### `max_length`
|
||||
|
||||
This is `None` by default, but can be set to a positive integer if you want to validates that the list contains no more than this number of elements.
|
||||
|
||||
### `min_length`
|
||||
|
||||
This is `None` by default, but can be set to a positive integer if you want to validates that the list contains no fewer than this number of elements.
|
||||
|
||||
### Customizing `ListSerializer` behavior
|
||||
|
||||
There *are* a few use cases when you might want to customize the `ListSerializer` behavior. For example:
|
||||
|
@ -877,7 +886,7 @@ Because this class provides the same interface as the `Serializer` class, you ca
|
|||
|
||||
The only difference you'll notice when doing so is the `BaseSerializer` classes will not generate HTML forms in the browsable API. This is because the data they return does not include all the field information that would allow each field to be rendered into a suitable HTML input.
|
||||
|
||||
##### Read-only `BaseSerializer` classes
|
||||
#### Read-only `BaseSerializer` classes
|
||||
|
||||
To implement a read-only serializer using the `BaseSerializer` class, we just need to override the `.to_representation()` method. Let's take a look at an example using a simple Django model:
|
||||
|
||||
|
@ -901,7 +910,7 @@ We can now use this class to serialize single `HighScore` instances:
|
|||
def high_score(request, pk):
|
||||
instance = HighScore.objects.get(pk=pk)
|
||||
serializer = HighScoreSerializer(instance)
|
||||
return Response(serializer.data)
|
||||
return Response(serializer.data)
|
||||
|
||||
Or use it to serialize multiple instances:
|
||||
|
||||
|
@ -909,9 +918,9 @@ Or use it to serialize multiple instances:
|
|||
def all_high_scores(request):
|
||||
queryset = HighScore.objects.order_by('-score')
|
||||
serializer = HighScoreSerializer(queryset, many=True)
|
||||
return Response(serializer.data)
|
||||
return Response(serializer.data)
|
||||
|
||||
##### Read-write `BaseSerializer` classes
|
||||
#### Read-write `BaseSerializer` classes
|
||||
|
||||
To create a read-write serializer we first need to implement a `.to_internal_value()` method. This method returns the validated values that will be used to construct the object instance, and may raise a `serializers.ValidationError` if the supplied data is in an incorrect format.
|
||||
|
||||
|
@ -940,8 +949,8 @@ Here's a complete example of our previous `HighScoreSerializer`, that's been upd
|
|||
'player_name': 'May not be more than 10 characters.'
|
||||
})
|
||||
|
||||
# Return the validated values. This will be available as
|
||||
# the `.validated_data` property.
|
||||
# Return the validated values. This will be available as
|
||||
# the `.validated_data` property.
|
||||
return {
|
||||
'score': int(score),
|
||||
'player_name': player_name
|
||||
|
@ -960,7 +969,7 @@ Here's a complete example of our previous `HighScoreSerializer`, that's been upd
|
|||
|
||||
The `BaseSerializer` class is also useful if you want to implement new generic serializer classes for dealing with particular serialization styles, or for integrating with alternative storage backends.
|
||||
|
||||
The following class is an example of a generic serializer that can handle coercing arbitrary objects into primitive representations.
|
||||
The following class is an example of a generic serializer that can handle coercing arbitrary complex objects into primitive representations.
|
||||
|
||||
class ObjectSerializer(serializers.BaseSerializer):
|
||||
"""
|
||||
|
@ -1012,7 +1021,7 @@ Some reasons this might be useful include...
|
|||
|
||||
The signatures for these methods are as follows:
|
||||
|
||||
#### `.to_representation(self, instance)`
|
||||
#### `to_representation(self, instance)`
|
||||
|
||||
Takes the object instance that requires serialization, and should return a primitive representation. Typically this means returning a structure of built-in Python datatypes. The exact types that can be handled will depend on the render classes you have configured for your API.
|
||||
|
||||
|
@ -1024,7 +1033,7 @@ May be overridden in order to modify the representation style. For example:
|
|||
ret['username'] = ret['username'].lower()
|
||||
return ret
|
||||
|
||||
#### ``.to_internal_value(self, data)``
|
||||
#### ``to_internal_value(self, data)``
|
||||
|
||||
Takes the unvalidated incoming data as input and should return the validated data that will be made available as `serializer.validated_data`. The return value will also be passed to the `.create()` or `.update()` methods if `.save()` is called on the serializer class.
|
||||
|
||||
|
@ -1087,7 +1096,7 @@ For example, if you wanted to be able to set which fields should be used by a se
|
|||
fields = kwargs.pop('fields', None)
|
||||
|
||||
# Instantiate the superclass normally
|
||||
super(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs)
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
if fields is not None:
|
||||
# Drop any fields that are not specified in the `fields` argument.
|
||||
|
@ -1180,7 +1189,7 @@ The [drf-writable-nested][drf-writable-nested] package provides writable nested
|
|||
|
||||
## DRF Encrypt Content
|
||||
|
||||
The [drf-encrypt-content][drf-encrypt-content] package helps you encrypt your data, serialized through ModelSerializer. It also contains some helper functions. Which helps you to encrypt your data.
|
||||
The [drf-encrypt-content][drf-encrypt-content] package helps you encrypt your data, serialized through ModelSerializer. It also contains some helper functions. Which helps you to encrypt your data.
|
||||
|
||||
|
||||
[cite]: https://groups.google.com/d/topic/django-users/sVFaOfQi4wY/discussion
|
||||
|
|
|
@ -41,6 +41,8 @@ This class of status code indicates a provisional response. There are no 1xx st
|
|||
|
||||
HTTP_100_CONTINUE
|
||||
HTTP_101_SWITCHING_PROTOCOLS
|
||||
HTTP_102_PROCESSING
|
||||
HTTP_103_EARLY_HINTS
|
||||
|
||||
## Successful - 2xx
|
||||
|
||||
|
@ -93,9 +95,11 @@ The 4xx class of status code is intended for cases in which the client seems to
|
|||
HTTP_415_UNSUPPORTED_MEDIA_TYPE
|
||||
HTTP_416_REQUESTED_RANGE_NOT_SATISFIABLE
|
||||
HTTP_417_EXPECTATION_FAILED
|
||||
HTTP_421_MISDIRECTED_REQUEST
|
||||
HTTP_422_UNPROCESSABLE_ENTITY
|
||||
HTTP_423_LOCKED
|
||||
HTTP_424_FAILED_DEPENDENCY
|
||||
HTTP_425_TOO_EARLY
|
||||
HTTP_426_UPGRADE_REQUIRED
|
||||
HTTP_428_PRECONDITION_REQUIRED
|
||||
HTTP_429_TOO_MANY_REQUESTS
|
||||
|
|
|
@ -234,7 +234,7 @@ If you're using `SessionAuthentication` then you'll need to include a CSRF token
|
|||
for any `POST`, `PUT`, `PATCH` or `DELETE` requests.
|
||||
|
||||
You can do so by following the same flow that a JavaScript based client would use.
|
||||
First make a `GET` request in order to obtain a CRSF token, then present that
|
||||
First, make a `GET` request in order to obtain a CSRF token, then present that
|
||||
token in the following request.
|
||||
|
||||
For example...
|
||||
|
@ -259,7 +259,7 @@ With careful usage both the `RequestsClient` and the `CoreAPIClient` provide
|
|||
the ability to write test cases that can run either in development, or be run
|
||||
directly against your staging server or production environment.
|
||||
|
||||
Using this style to create basic tests of a few core piece of functionality is
|
||||
Using this style to create basic tests of a few core pieces of functionality is
|
||||
a powerful way to validate your live service. Doing so may require some careful
|
||||
attention to setup and teardown to ensure that the tests run in a way that they
|
||||
do not directly affect customer data.
|
||||
|
@ -299,7 +299,7 @@ similar way as with `RequestsClient`.
|
|||
|
||||
# API Test cases
|
||||
|
||||
REST framework includes the following test case classes, that mirror the existing Django test case classes, but use `APIClient` instead of Django's default `Client`.
|
||||
REST framework includes the following test case classes, that mirror the existing [Django's test case classes][provided_test_case_classes], but use `APIClient` instead of Django's default `Client`.
|
||||
|
||||
* `APISimpleTestCase`
|
||||
* `APITransactionTestCase`
|
||||
|
@ -413,5 +413,6 @@ For example, to add support for using `format='html'` in test requests, you migh
|
|||
[client]: https://docs.djangoproject.com/en/stable/topics/testing/tools/#the-test-client
|
||||
[requestfactory]: https://docs.djangoproject.com/en/stable/topics/testing/advanced/#django.test.client.RequestFactory
|
||||
[configuration]: #configuration
|
||||
[refresh_from_db_docs]: https://docs.djangoproject.com/en/1.11/ref/models/instances/#django.db.models.Model.refresh_from_db
|
||||
[refresh_from_db_docs]: https://docs.djangoproject.com/en/stable/ref/models/instances/#django.db.models.Model.refresh_from_db
|
||||
[session_objects]: https://requests.readthedocs.io/en/master/user/advanced/#session-objects
|
||||
[provided_test_case_classes]: https://docs.djangoproject.com/en/stable/topics/testing/tools/#provided-test-case-classes
|
||||
|
|
|
@ -19,6 +19,10 @@ Multiple throttles can also be used if you want to impose both burst throttling
|
|||
|
||||
Throttles do not necessarily only refer to rate-limiting requests. For example a storage service might also need to throttle against bandwidth, and a paid data service might want to throttle against a certain number of a records being accessed.
|
||||
|
||||
**The application-level throttling that REST framework provides should not be considered a security measure or protection against brute forcing or denial-of-service attacks. Deliberately malicious actors will always be able to spoof IP origins. In addition to this, the built-in throttling implementations are implemented using Django's cache framework, and use non-atomic operations to determine the request rate, which may sometimes result in some fuzziness.
|
||||
|
||||
The application-level throttling provided by REST framework is intended for implementing policies such as different business tiers and basic protections against service over-use.**
|
||||
|
||||
## How throttling is determined
|
||||
|
||||
As with permissions and authentication, throttling in REST framework is always defined as a list of classes.
|
||||
|
@ -46,9 +50,9 @@ The rate descriptions used in `DEFAULT_THROTTLE_RATES` may include `second`, `mi
|
|||
You can also set the throttling policy on a per-view or per-viewset basis,
|
||||
using the `APIView` class-based views.
|
||||
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.throttling import UserRateThrottle
|
||||
from rest_framework.views import APIView
|
||||
from rest_framework.views import APIView
|
||||
|
||||
class ExampleView(APIView):
|
||||
throttle_classes = [UserRateThrottle]
|
||||
|
@ -79,7 +83,7 @@ Throttle classes set in this way will override any viewset level class settings.
|
|||
}
|
||||
return Response(content)
|
||||
|
||||
## How clients are identified
|
||||
## How clients are identified
|
||||
|
||||
The `X-Forwarded-For` HTTP header and `REMOTE_ADDR` WSGI variable are used to uniquely identify client IP addresses for throttling. If the `X-Forwarded-For` header is present then it will be used, otherwise the value of the `REMOTE_ADDR` variable from the WSGI environment will be used.
|
||||
|
||||
|
@ -102,6 +106,12 @@ If you need to use a cache other than `'default'`, you can do so by creating a c
|
|||
|
||||
You'll need to remember to also set your custom throttle class in the `'DEFAULT_THROTTLE_CLASSES'` settings key, or using the `throttle_classes` view attribute.
|
||||
|
||||
## A note on concurrency
|
||||
|
||||
The built-in throttle implementations are open to [race conditions][race], so under high concurrency they may allow a few extra requests through.
|
||||
|
||||
If your project relies on guaranteeing the number of requests during concurrent requests, you will need to implement your own throttle class. See [issue #5181][gh5181] for more details.
|
||||
|
||||
---
|
||||
|
||||
# API Reference
|
||||
|
@ -210,3 +220,5 @@ The following is an example of a rate throttle, that will randomly throttle 1 in
|
|||
[identifying-clients]: http://oxpedia.org/wiki/index.php?title=AppSuite:Grizzly#Multiple_Proxies_in_front_of_the_cluster
|
||||
[cache-setting]: https://docs.djangoproject.com/en/stable/ref/settings/#caches
|
||||
[cache-docs]: https://docs.djangoproject.com/en/stable/topics/cache/#setting-up-the-cache
|
||||
[gh5181]: https://github.com/encode/django-rest-framework/issues/5181
|
||||
[race]: https://en.wikipedia.org/wiki/Race_condition#Data_race
|
||||
|
|
|
@ -20,7 +20,7 @@ Validation in Django REST framework serializers is handled a little differently
|
|||
With `ModelForm` the validation is performed partially on the form, and partially on the model instance. With REST framework the validation is performed entirely on the serializer class. This is advantageous for the following reasons:
|
||||
|
||||
* It introduces a proper separation of concerns, making your code behavior more obvious.
|
||||
* It is easy to switch between using shortcut `ModelSerializer` classes and using explicit `Serializer` classes. Any validation behavior being used for `ModelSerializer` is simple to replicate.
|
||||
* It is easy to switch between using shortcut `ModelSerializer` classes and using explicit `Serializer` classes. Any validation behavior being used for `ModelSerializer` is simple to replicate.
|
||||
* Printing the `repr` of a serializer instance will show you exactly what validation rules it applies. There's no extra hidden validation behavior being called on the model instance.
|
||||
|
||||
When you're using `ModelSerializer` all of this is handled automatically for you. If you want to drop down to using `Serializer` classes instead, then you need to define the validation rules explicitly.
|
||||
|
@ -208,7 +208,7 @@ by specifying an empty list for the serializer `Meta.validators` attribute.
|
|||
|
||||
By default "unique together" validation enforces that all fields be
|
||||
`required=True`. In some cases, you might want to explicit apply
|
||||
`required=False` to one of the fields, in which case the desired behaviour
|
||||
`required=False` to one of the fields, in which case the desired behavior
|
||||
of the validation is ambiguous.
|
||||
|
||||
In this case you will typically need to exclude the validator from the
|
||||
|
@ -238,7 +238,7 @@ In the case of update operations on *nested* serializers there's no way of
|
|||
applying this exclusion, because the instance is not available.
|
||||
|
||||
Again, you'll probably want to explicitly remove the validator from the
|
||||
serializer class, and write the code the for the validation constraint
|
||||
serializer class, and write the code for the validation constraint
|
||||
explicitly, in a `.validate()` method, or in the view.
|
||||
|
||||
## Debugging complex cases
|
||||
|
|
|
@ -145,6 +145,7 @@ REST framework also allows you to work with regular function based views. It pr
|
|||
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
|
||||
from rest_framework.response import Response
|
||||
|
||||
@api_view()
|
||||
def hello_world(request):
|
||||
|
@ -152,7 +153,7 @@ The core of this functionality is the `api_view` decorator, which takes a list o
|
|||
|
||||
This view will use the default renderers, parsers, authentication classes etc specified in the [settings].
|
||||
|
||||
By default only `GET` methods will be accepted. Other methods will respond with "405 Method Not Allowed". To alter this behaviour, specify which methods the view allows, like so:
|
||||
By default only `GET` methods will be accepted. Other methods will respond with "405 Method Not Allowed". To alter this behavior, specify which methods the view allows, like so:
|
||||
|
||||
@api_view(['GET', 'POST'])
|
||||
def hello_world(request):
|
||||
|
|
|
@ -116,7 +116,7 @@ During dispatch, the following attributes are available on the `ViewSet`.
|
|||
* `name` - the display name for the viewset. This argument is mutually exclusive to `suffix`.
|
||||
* `description` - the display description for the individual view of a viewset.
|
||||
|
||||
You may inspect these attributes to adjust behaviour based on the current action. For example, you could restrict permissions to everything except the `list` action similar to this:
|
||||
You may inspect these attributes to adjust behavior based on the current action. For example, you could restrict permissions to everything except the `list` action similar to this:
|
||||
|
||||
def get_permissions(self):
|
||||
"""
|
||||
|
@ -125,7 +125,7 @@ You may inspect these attributes to adjust behaviour based on the current action
|
|||
if self.action == 'list':
|
||||
permission_classes = [IsAuthenticated]
|
||||
else:
|
||||
permission_classes = [IsAdmin]
|
||||
permission_classes = [IsAdminUser]
|
||||
return [permission() for permission in permission_classes]
|
||||
|
||||
## Marking extra actions for routing
|
||||
|
@ -247,7 +247,7 @@ In order to use a `GenericViewSet` class you'll override the class and either mi
|
|||
|
||||
The `ModelViewSet` class inherits from `GenericAPIView` and includes implementations for various actions, by mixing in the behavior of the various mixin classes.
|
||||
|
||||
The actions provided by the `ModelViewSet` class are `.list()`, `.retrieve()`, `.create()`, `.update()`, `.partial_update()`, and `.destroy()`.
|
||||
The actions provided by the `ModelViewSet` class are `.list()`, `.retrieve()`, `.create()`, `.update()`, `.partial_update()`, and `.destroy()`.
|
||||
|
||||
#### Example
|
||||
|
||||
|
|
|
@ -24,7 +24,7 @@ Notable features of this new release include:
|
|||
* Support for overriding how validation errors are handled by your API.
|
||||
* A metadata API that allows you to customize how `OPTIONS` requests are handled by your API.
|
||||
* A more compact JSON output with unicode style encoding turned on by default.
|
||||
* Templated based HTML form rendering for serializers. This will be finalized as public API in the upcoming 3.1 release.
|
||||
* Templated based HTML form rendering for serializers. This will be finalized as public API in the upcoming 3.1 release.
|
||||
|
||||
Significant new functionality continues to be planned for the 3.1 and 3.2 releases. These releases will correspond to the two [Kickstarter stretch goals](https://www.kickstarter.com/projects/tomchristie/django-rest-framework-3) - "Feature improvements" and "Admin interface". Further 3.x releases will present simple upgrades, without the same level of fundamental API changes necessary for the 3.0 release.
|
||||
|
||||
|
@ -632,7 +632,7 @@ The `MultipleChoiceField` class has been added. This field acts like `ChoiceFiel
|
|||
|
||||
The `from_native(self, value)` and `to_native(self, data)` method names have been replaced with the more obviously named `to_internal_value(self, data)` and `to_representation(self, value)`.
|
||||
|
||||
The `field_from_native()` and `field_to_native()` methods are removed. Previously you could use these methods if you wanted to customise the behaviour in a way that did not simply lookup the field value from the object. For example...
|
||||
The `field_from_native()` and `field_to_native()` methods are removed. Previously you could use these methods if you wanted to customise the behavior in a way that did not simply lookup the field value from the object. For example...
|
||||
|
||||
def field_to_native(self, obj, field_name):
|
||||
"""A custom read-only field that returns the class name."""
|
||||
|
|
|
@ -142,6 +142,6 @@ continued development by **[signing up for a paid plan][funding]**.
|
|||
|
||||
*Many thanks to all our [wonderful sponsors][sponsors], and in particular to our premium backers, [Sentry](https://getsentry.com/welcome/), [Stream](https://getstream.io/?utm_source=drf&utm_medium=banner&utm_campaign=drf), [ESG](https://software.esg-usa.com/), [Rollbar](https://rollbar.com/?utm_source=django&utm_medium=sponsorship&utm_campaign=freetrial), [Cadre](https://cadre.com), [Kloudless](https://hubs.ly/H0f30Lf0), and [Lights On Software](https://lightsonsoftware.com).*
|
||||
|
||||
[legacy-core-api-docs]:https://github.com/encode/django-rest-framework/blob/master/docs/coreapi/index.md
|
||||
[legacy-core-api-docs]:https://github.com/encode/django-rest-framework/blob/3.14.0/docs/coreapi/index.md
|
||||
[sponsors]: https://fund.django-rest-framework.org/topics/funding/#our-sponsors
|
||||
[funding]: funding.md
|
||||
|
|
|
@ -30,12 +30,12 @@ in the URL path.
|
|||
|
||||
For example...
|
||||
|
||||
Method | Path | Tags
|
||||
Method | Path | Tags
|
||||
--------------------------------|-----------------|-------------
|
||||
`GET`, `PUT`, `PATCH`, `DELETE` | `/users/{id}/` | `['users']`
|
||||
`GET`, `POST` | `/users/` | `['users']`
|
||||
`GET`, `PUT`, `PATCH`, `DELETE` | `/orders/{id}/` | `['orders']`
|
||||
`GET`, `POST` | `/orders/` | `['orders']`
|
||||
`GET`, `PUT`, `PATCH`, `DELETE` | `/users/{id}/` | `['users']`
|
||||
`GET`, `POST` | `/users/` | `['users']`
|
||||
`GET`, `PUT`, `PATCH`, `DELETE` | `/orders/{id}/` | `['orders']`
|
||||
`GET`, `POST` | `/orders/` | `['orders']`
|
||||
|
||||
The tags used for a particular view may also be overridden...
|
||||
|
||||
|
|
55
docs/community/3.13-announcement.md
Normal file
|
@ -0,0 +1,55 @@
|
|||
<style>
|
||||
.promo li a {
|
||||
float: left;
|
||||
width: 130px;
|
||||
height: 20px;
|
||||
text-align: center;
|
||||
margin: 10px 30px;
|
||||
padding: 150px 0 0 0;
|
||||
background-position: 0 50%;
|
||||
background-size: 130px auto;
|
||||
background-repeat: no-repeat;
|
||||
font-size: 120%;
|
||||
color: black;
|
||||
}
|
||||
.promo li {
|
||||
list-style: none;
|
||||
}
|
||||
</style>
|
||||
|
||||
# Django REST framework 3.13
|
||||
|
||||
## Django 4.0 support
|
||||
|
||||
The latest release now fully supports Django 4.0.
|
||||
|
||||
Our requirements are now:
|
||||
|
||||
* Python 3.6+
|
||||
* Django 4.0, 3.2, 3.1, 2.2 (LTS)
|
||||
|
||||
## Fields arguments are now keyword-only
|
||||
|
||||
When instantiating fields on serializers, you should always use keyword arguments,
|
||||
such as `serializers.CharField(max_length=200)`. This has always been the case,
|
||||
and all the examples that we have in the documentation use keyword arguments,
|
||||
rather than positional arguments.
|
||||
|
||||
From REST framework 3.13 onwards, this is now *explicitly enforced*.
|
||||
|
||||
The most feasible cases where users might be accidentally omitting the keyword arguments
|
||||
are likely in the composite fields, `ListField` and `DictField`. For instance...
|
||||
|
||||
```python
|
||||
aliases = serializers.ListField(serializers.CharField())
|
||||
```
|
||||
|
||||
They must now use the more explicit keyword argument style...
|
||||
|
||||
```python
|
||||
aliases = serializers.ListField(child=serializers.CharField())
|
||||
```
|
||||
|
||||
This change has been made because using positional arguments here *does not* result in the expected behaviour.
|
||||
|
||||
See Pull Request [#7632](https://github.com/encode/django-rest-framework/pull/7632) for more details.
|
62
docs/community/3.14-announcement.md
Normal file
|
@ -0,0 +1,62 @@
|
|||
<style>
|
||||
.promo li a {
|
||||
float: left;
|
||||
width: 130px;
|
||||
height: 20px;
|
||||
text-align: center;
|
||||
margin: 10px 30px;
|
||||
padding: 150px 0 0 0;
|
||||
background-position: 0 50%;
|
||||
background-size: 130px auto;
|
||||
background-repeat: no-repeat;
|
||||
font-size: 120%;
|
||||
color: black;
|
||||
}
|
||||
.promo li {
|
||||
list-style: none;
|
||||
}
|
||||
</style>
|
||||
|
||||
# Django REST framework 3.14
|
||||
|
||||
## Django 4.1 support
|
||||
|
||||
The latest release now fully supports Django 4.1, and drops support for Django 2.2.
|
||||
|
||||
Our requirements are now:
|
||||
|
||||
* Python 3.6+
|
||||
* Django 4.1, 4.0, 3.2, 3.1, 3.0
|
||||
|
||||
## `raise_exceptions` argument for `is_valid` is now keyword-only.
|
||||
|
||||
Calling `serializer_instance.is_valid(True)` is no longer acceptable syntax.
|
||||
If you'd like to use the `raise_exceptions` argument, you must use it as a
|
||||
keyword argument.
|
||||
|
||||
See Pull Request [#7952](https://github.com/encode/django-rest-framework/pull/7952) for more details.
|
||||
|
||||
## `ManyRelatedField` supports returning the default when the source attribute doesn't exist.
|
||||
|
||||
Previously, if you used a serializer field with `many=True` with a dot notated source field
|
||||
that didn't exist, it would raise an `AttributeError`. Now it will return the default or be
|
||||
skipped depending on the other arguments.
|
||||
|
||||
See Pull Request [#7574](https://github.com/encode/django-rest-framework/pull/7574) for more details.
|
||||
|
||||
|
||||
## Make Open API `get_reference` public.
|
||||
|
||||
Returns a reference to the serializer component. This may be useful if you override `get_schema()`.
|
||||
|
||||
## Change semantic of OR of two permission classes.
|
||||
|
||||
When OR-ing two permissions, the request has to pass either class's `has_permission() and has_object_permission()`.
|
||||
|
||||
Previously, both class's `has_permission()` was ignored when OR-ing two permissions together.
|
||||
|
||||
See Pull Request [#7522](https://github.com/encode/django-rest-framework/pull/7522) for more details.
|
||||
|
||||
## Minor fixes and improvements
|
||||
|
||||
There are a number of minor fixes and improvements in this release. See the [release notes](release-notes.md) page for a complete listing.
|
|
@ -64,7 +64,7 @@ These are a little subtle and probably won't affect most users, but are worth un
|
|||
|
||||
### ManyToMany fields and blank=True
|
||||
|
||||
We've now added an `allow_empty` argument, which can be used with `ListSerializer`, or with `many=True` relationships. This is `True` by default, but can be set to `False` if you want to disallow empty lists as valid input.
|
||||
We've now added an `allow_empty` argument, which can be used with `ListSerializer`, or with `many=True` relationships. This is `True` by default, but can be set to `False` if you want to disallow empty lists as valid input.
|
||||
|
||||
As a follow-up to this we are now able to properly mirror the behavior of Django's `ModelForm` with respect to how many-to-many fields are validated.
|
||||
|
||||
|
|
|
@ -38,7 +38,7 @@ The AJAX based support for the browsable API means that there are a number of in
|
|||
|
||||
* To support form based `PUT` and `DELETE`, or to support form content types such as JSON, you should now use the [AJAX forms][ajax-form] javascript library. This replaces the previous 'method and content type overloading' that required significant internal complexity to the request class.
|
||||
* The `accept` query parameter is no longer supported by the default content negotiation class. If you require it then you'll need to [use a custom content negotiation class][accept-headers].
|
||||
* The custom `HTTP_X_HTTP_METHOD_OVERRIDE` header is no longer supported by default. If you require it then you'll need to [use custom middleware][method-override].
|
||||
* The custom `HTTP_X_HTTP_METHOD_OVERRIDE` header is no longer supported by default. If you require it then you'll need to [use custom middleware][method-override].
|
||||
|
||||
The following pagination view attributes and settings have been moved into attributes on the pagination class since 3.1. Their usage was formerly deprecated, and has now been removed entirely, in line with the deprecation policy.
|
||||
|
||||
|
|
|
@ -89,7 +89,7 @@ Name | Support | PyPI pa
|
|||
---------------------------------|-------------------------------------|--------------------------------
|
||||
[Core JSON][core-json] | Schema generation & client support. | Built-in support in `coreapi`.
|
||||
[Swagger / OpenAPI][swagger] | Schema generation & client support. | The `openapi-codec` package.
|
||||
[JSON Hyper-Schema][hyperschema] | Currently client support only. | The `hyperschema-codec` package.
|
||||
[JSON Hyper-Schema][hyperschema] | Currently client support only. | The `hyperschema-codec` package.
|
||||
[API Blueprint][api-blueprint] | Not yet available. | Not yet available.
|
||||
|
||||
---
|
||||
|
@ -187,7 +187,7 @@ The full set of itemized release notes [are available here][release-notes].
|
|||
[api-blueprint]: https://apiblueprint.org/
|
||||
[tut-7]: ../tutorial/7-schemas-and-client-libraries/
|
||||
[schema-generation]: ../api-guide/schemas/
|
||||
[api-clients]: ../topics/api-clients.md
|
||||
[api-clients]: https://github.com/encode/django-rest-framework/blob/3.14.0/docs/topics/api-clients.md
|
||||
[milestone]: https://github.com/encode/django-rest-framework/milestone/35
|
||||
[release-notes]: release-notes#34
|
||||
[metadata]: ../api-guide/metadata/#custom-metadata-classes
|
||||
|
|
|
@ -195,5 +195,5 @@ on realtime support, for the 3.7 release.
|
|||
[sponsors]: https://fund.django-rest-framework.org/topics/funding/#our-sponsors
|
||||
[funding]: funding.md
|
||||
[api-docs]: ../topics/documenting-your-api.md
|
||||
[js-docs]: ../topics/api-clients.md#javascript-client-library
|
||||
[py-docs]: ../topics/api-clients.md#python-client-library
|
||||
[js-docs]: https://github.com/encode/django-rest-framework/blob/3.14.0/docs/topics/api-clients.md#javascript-client-library
|
||||
[py-docs]: https://github.com/encode/django-rest-framework/blob/3.14.0/docs/topics/api-clients.md#python-client-library
|
||||
|
|
|
@ -89,7 +89,7 @@ for a complete listing.
|
|||
|
||||
We're currently working towards moving to using [OpenAPI][openapi] as our default schema output. We'll also be revisiting our API documentation generation and client libraries.
|
||||
|
||||
We're doing some consolidation in order to make this happen. It's planned that 3.9 will drop the `coreapi` and `coreschema` libraries, and instead use `apistar` for the API documentation generation, schema generation, and API client libraries.
|
||||
We're doing some consolidation in order to make this happen. It's planned that 3.9 will drop the `coreapi` and `coreschema` libraries, and instead use `apistar` for the API documentation generation, schema generation, and API client libraries.
|
||||
|
||||
[funding]: funding.md
|
||||
[gh5886]: https://github.com/encode/django-rest-framework/issues/5886
|
||||
|
|
|
@ -110,7 +110,7 @@ You can now compose permission classes using the and/or operators, `&` and `|`.
|
|||
For example...
|
||||
|
||||
```python
|
||||
permission_classes = [IsAuthenticated & (ReadOnly | IsAdmin)]
|
||||
permission_classes = [IsAuthenticated & (ReadOnly | IsAdminUser)]
|
||||
```
|
||||
|
||||
If you're using custom permission classes then make sure that you are subclassing
|
||||
|
|
|
@ -6,6 +6,12 @@
|
|||
|
||||
There are many ways you can contribute to Django REST framework. We'd like it to be a community-led project, so please get involved and help shape the future of the project.
|
||||
|
||||
---
|
||||
|
||||
**Note**: At this point in it's lifespan we consider Django REST framework to be essentially feature-complete. We may accept pull requests that track the continued development of Django versions, but would prefer not to accept new features or code formatting changes.
|
||||
|
||||
---
|
||||
|
||||
## Community
|
||||
|
||||
The most important thing you can do to help push the REST framework project forward is to be actively involved wherever possible. Code contributions are often overvalued as being the primary way to get involved in a project, we don't believe that needs to be the case.
|
||||
|
@ -26,14 +32,13 @@ The [Django code of conduct][code-of-conduct] gives a fuller set of guidelines f
|
|||
|
||||
# Issues
|
||||
|
||||
It's really helpful if you can make sure to address issues on the correct channel. Usage questions should be directed to the [discussion group][google-group]. Feature requests, bug reports and other issues should be raised on the GitHub [issue tracker][issues].
|
||||
Our contribution process is that the [GitHub discussions page](https://github.com/encode/django-rest-framework/discussions) should generally be your starting point. Please only raise an issue or pull request if you've been recommended to do so after discussion.
|
||||
|
||||
Some tips on good issue reporting:
|
||||
Some tips on good potential 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.
|
||||
* Feature requests will often be closed with a recommendation that they be implemented outside of the core REST framework library. Keeping new feature requests implemented as third party libraries allows us to keep down the maintenance overhead of REST framework, so that the focus can be on continued stability, bugfixes, and great documentation.
|
||||
* Search the GitHub project page for related items, and make sure you're running the latest version of REST framework before reporting an issue.
|
||||
* Feature requests will often be closed with a recommendation that they be implemented outside of the core REST framework library. Keeping new feature requests implemented as third party libraries allows us to keep down the maintenance overhead of REST framework, so that the focus can be on continued stability, bugfixes, and great documentation. At this point in it's lifespan we consider Django REST framework to be essentially feature-complete.
|
||||
* Closing an issue doesn't necessarily mean the end of a discussion. If you believe your issue has been closed incorrectly, explain why and we'll consider if it needs to be reopened.
|
||||
|
||||
## Triaging issues
|
||||
|
@ -75,7 +80,7 @@ To run the tests, clone the repository, and then:
|
|||
# Setup the virtual environment
|
||||
python3 -m venv env
|
||||
source env/bin/activate
|
||||
pip install django
|
||||
pip install -e .
|
||||
pip install -r requirements.txt
|
||||
|
||||
# Run the tests
|
||||
|
|
|
@ -124,7 +124,7 @@ REST framework continues to be open-source and permissively licensed, but we fir
|
|||
## What funding has enabled so far
|
||||
|
||||
* The [3.4](https://www.django-rest-framework.org/community/3.4-announcement/) and [3.5](https://www.django-rest-framework.org/community/3.5-announcement/) releases, including schema generation for both Swagger and RAML, a Python client library, a Command Line client, and addressing of a large number of outstanding issues.
|
||||
* The [3.6](https://www.django-rest-framework.org/community/3.6-announcement/) release, including JavaScript client library, and API documentation, complete with auto-generated code samples.
|
||||
* The [3.6](https://www.django-rest-framework.org/community/3.6-announcement/) release, including JavaScript client library, and API documentation, complete with auto-generated code samples.
|
||||
* The [3.7 release](https://www.django-rest-framework.org/community/3.7-announcement/), made possible due to our collaborative funding model, focuses on improvements to schema generation and the interactive API documentation.
|
||||
* The recent [3.8 release](https://www.django-rest-framework.org/community/3.8-announcement/).
|
||||
* Tom Christie, the creator of Django REST framework, working on the project full-time.
|
||||
|
@ -137,7 +137,7 @@ REST framework continues to be open-source and permissively licensed, but we fir
|
|||
## What future funding will enable
|
||||
|
||||
* Realtime API support, using WebSockets. This will consist of documentation and support for using REST framework together with Django Channels, plus integrating WebSocket support into the client libraries.
|
||||
* Better authentication defaults, possibly bringing JWT & CORs support into the core package.
|
||||
* Better authentication defaults, possibly bringing JWT & CORS support into the core package.
|
||||
* Securing the community & operations manager position long-term.
|
||||
* Opening up and securing a part-time position to focus on ticket triage and resolution.
|
||||
* Paying for development time on building API client libraries in a range of programming languages. These would be integrated directly into the upcoming API documentation.
|
||||
|
@ -154,13 +154,13 @@ Sign up for a paid plan today, and help ensure that REST framework becomes a sus
|
|||
|
||||
|
||||
|
||||
> The number one feature of the Python programming language is its community. Such a community is only possible because of the Open Source nature of the language and all the culture that comes from it. Building great Open Source projects require great minds. Given that, we at Vinta are not only proud to sponsor the team behind DRF but we also recognize the ROI that comes from it.
|
||||
> The number one feature of the Python programming language is its community. Such a community is only possible because of the Open Source nature of the language and all the culture that comes from it. Building great Open Source projects require great minds. Given that, we at Vinta are not only proud to sponsor the team behind DRF but we also recognize the ROI that comes from it.
|
||||
>
|
||||
> — Filipe Ximenes, Vinta Software
|
||||
|
||||
|
||||
|
||||
> It's really awesome that this project continues to endure. The code base is top notch and the maintainers are committed to the highest level of quality.
|
||||
> It's really awesome that this project continues to endure. The code base is top notch and the maintainers are committed to the highest level of quality.
|
||||
DRF is one of the core reasons why Django is top choice among web frameworks today. In my opinion, it sets the standard for rest frameworks for the development community at large.
|
||||
>
|
||||
> — Andrew Conti, Django REST framework user
|
||||
|
|
|
@ -11,11 +11,12 @@ Looking for a new Django REST Framework related role? On this site we provide a
|
|||
* [https://djangojobs.net/jobs/][django-jobs-net]
|
||||
* [https://findwork.dev/django-rest-framework-jobs][findwork-dev]
|
||||
* [https://www.indeed.com/q-Django-jobs.html][indeed-com]
|
||||
* [https://stackoverflow.com/jobs/developer-jobs-using-django][stackoverflow-com]
|
||||
* [https://stackoverflow.com/jobs/companies?tl=django][stackoverflow-com]
|
||||
* [https://www.upwork.com/o/jobs/browse/skill/django-framework/][upwork-com]
|
||||
* [https://www.technojobs.co.uk/django-jobs][technobjobs-co-uk]
|
||||
* [https://remoteok.io/remote-django-jobs][remoteok-io]
|
||||
* [https://remoteok.com/remote-django-jobs][remoteok-com]
|
||||
* [https://www.remotepython.com/jobs/][remotepython-com]
|
||||
* [https://www.pyjobs.com/][pyjobs-com]
|
||||
|
||||
|
||||
Know of any other great resources for Django REST Framework jobs that are missing in our list? Please [submit a pull request][submit-pr] or [email us][anna-email].
|
||||
|
@ -29,11 +30,12 @@ Wonder how else you can help? One of the best ways you can help Django REST Fram
|
|||
[django-jobs-net]: https://djangojobs.net/jobs/
|
||||
[findwork-dev]: https://findwork.dev/django-rest-framework-jobs
|
||||
[indeed-com]: https://www.indeed.com/q-Django-jobs.html
|
||||
[stackoverflow-com]: https://stackoverflow.com/jobs/developer-jobs-using-django
|
||||
[stackoverflow-com]: https://stackoverflow.com/jobs/companies?tl=django
|
||||
[upwork-com]: https://www.upwork.com/o/jobs/browse/skill/django-framework/
|
||||
[technobjobs-co-uk]: https://www.technojobs.co.uk/django-jobs
|
||||
[remoteok-io]: https://remoteok.io/remote-django-jobs
|
||||
[remoteok-com]: https://remoteok.com/remote-django-jobs
|
||||
[remotepython-com]: https://www.remotepython.com/jobs/
|
||||
[pyjobs-com]: https://www.pyjobs.com/
|
||||
[drf-funding]: https://fund.django-rest-framework.org/topics/funding/
|
||||
[submit-pr]: https://github.com/encode/django-rest-framework
|
||||
[anna-email]: mailto:anna@django-rest-framework.org
|
||||
|
|
|
@ -34,6 +34,47 @@ You can determine your currently installed version using `pip show`:
|
|||
|
||||
---
|
||||
|
||||
## 3.14.x series
|
||||
|
||||
### 3.14.0
|
||||
|
||||
Date: 22nd September 2022
|
||||
|
||||
* Django 2.2 is no longer supported. [[#8662](https://github.com/encode/django-rest-framework/pull/8662)]
|
||||
* Django 4.1 compatibility. [[#8591](https://github.com/encode/django-rest-framework/pull/8591)]
|
||||
* Add `--api-version` CLI option to `generateschema` management command. [[#8663](https://github.com/encode/django-rest-framework/pull/8663)]
|
||||
* Enforce `is_valid(raise_exception=False)` as a keyword-only argument. [[#7952](https://github.com/encode/django-rest-framework/pull/7952)]
|
||||
* Stop calling `set_context` on Validators. [[#8589](https://github.com/encode/django-rest-framework/pull/8589)]
|
||||
* Return `NotImplemented` from `ErrorDetails.__ne__`. [[#8538](https://github.com/encode/django-rest-framework/pull/8538)]
|
||||
* Don't evaluate `DateTimeField.default_timezone` when a custom timezone is set. [[#8531](https://github.com/encode/django-rest-framework/pull/8531)]
|
||||
* Make relative URLs clickable in Browseable API. [[#8464](https://github.com/encode/django-rest-framework/pull/8464)]
|
||||
* Support `ManyRelatedField` falling back to the default value when the attribute specified by dot notation doesn't exist. Matches `ManyRelatedField.get_attribute` to `Field.get_attribute`. [[#7574](https://github.com/encode/django-rest-framework/pull/7574)]
|
||||
* Make `schemas.openapi.get_reference` public. [[#7515](https://github.com/encode/django-rest-framework/pull/7515)]
|
||||
* Make `ReturnDict` support `dict` union operators on Python 3.9 and later. [[#8302](https://github.com/encode/django-rest-framework/pull/8302)]
|
||||
* Update throttling to check if `request.user` is set before checking if the user is authenticated. [[#8370](https://github.com/encode/django-rest-framework/pull/8370)]
|
||||
|
||||
## 3.13.x series
|
||||
|
||||
### 3.13.1
|
||||
|
||||
Date: 15th December 2021
|
||||
|
||||
* Revert schema naming changes with function based `@api_view`. [#8297]
|
||||
|
||||
### 3.13.0
|
||||
|
||||
Date: 13th December 2021
|
||||
|
||||
* Django 4.0 compatability. [#8178]
|
||||
* Add `max_length` and `min_length` options to `ListSerializer`. [#8165]
|
||||
* Add `get_request_serializer` and `get_response_serializer` hooks to `AutoSchema`. [#7424]
|
||||
* Fix OpenAPI representation of null-able read only fields. [#8116]
|
||||
* Respect `UNICODE_JSON` setting in API schema outputs. [#7991]
|
||||
* Fix for `RemoteUserAuthentication`. [#7158]
|
||||
* Make Field constructors keyword-only. [#7632]
|
||||
|
||||
---
|
||||
|
||||
## 3.12.x series
|
||||
|
||||
### 3.12.4
|
||||
|
|
|
@ -54,7 +54,7 @@ To submit new content, [open an issue][drf-create-issue] or [create a pull reque
|
|||
* [hawkrest][hawkrest] - Provides Hawk HTTP Authorization.
|
||||
* [djangorestframework-httpsignature][djangorestframework-httpsignature] - Provides an easy to use HTTP Signature Authentication mechanism.
|
||||
* [djoser][djoser] - Provides a set of views to handle basic actions such as registration, login, logout, password reset and account activation.
|
||||
* [django-rest-auth][django-rest-auth] - Provides a set of REST API endpoints for registration, authentication (including social media authentication), password reset, retrieve and update user details, etc.
|
||||
* [dj-rest-auth][dj-rest-auth] - Provides a set of REST API endpoints for registration, authentication (including social media authentication), password reset, retrieve and update user details, etc.
|
||||
* [drf-oidc-auth][drf-oidc-auth] - Implements OpenID Connect token authentication for DRF.
|
||||
* [drfpasswordless][drfpasswordless] - Adds (Medium, Square Cash inspired) passwordless logins and signups via email and mobile numbers.
|
||||
* [django-rest-authemail][django-rest-authemail] - Provides a RESTful API for user signup and authentication using email addresses.
|
||||
|
@ -106,6 +106,7 @@ To submit new content, [open an issue][drf-create-issue] or [create a pull reque
|
|||
* [djangorestframework-msgpack][djangorestframework-msgpack] - Provides MessagePack renderer and parser support.
|
||||
* [djangorestframework-jsonapi][djangorestframework-jsonapi] - Provides a parser, renderer, serializers, and other tools to help build an API that is compliant with the jsonapi.org spec.
|
||||
* [djangorestframework-camel-case][djangorestframework-camel-case] - Provides camel case JSON renderers and parsers.
|
||||
* [nested-multipart-parser][nested-multipart-parser] - Provides nested parser for http multipart request
|
||||
|
||||
### Renderers
|
||||
|
||||
|
@ -120,7 +121,7 @@ To submit new content, [open an issue][drf-create-issue] or [create a pull reque
|
|||
* [djangorestframework-chain][djangorestframework-chain] - Allows arbitrary chaining of both relations and lookup filters.
|
||||
* [django-url-filter][django-url-filter] - Allows a safe way to filter data via human-friendly URLs. It is a generic library which is not tied to DRF but it provides easy integration with DRF.
|
||||
* [drf-url-filter][drf-url-filter] is a simple Django app to apply filters on drf `ModelViewSet`'s `Queryset` in a clean, simple and configurable way. It also supports validations on incoming query params and their values.
|
||||
* [django-rest-framework-guardian][django-rest-framework-guardian] - Provides integration with django-guardian, including the `DjangoObjectPermissionsFilter` previously found in DRF.
|
||||
* [django-rest-framework-guardian2][django-rest-framework-guardian2] - Provides integration with django-guardian, including the `DjangoObjectPermissionsFilter` previously found in DRF.
|
||||
|
||||
### Misc
|
||||
|
||||
|
@ -147,6 +148,8 @@ To submit new content, [open an issue][drf-create-issue] or [create a pull reque
|
|||
* [django-elasticsearch-dsl-drf][django-elasticsearch-dsl-drf] - Integrate Elasticsearch DSL with Django REST framework. Package provides views, serializers, filter backends, pagination and other handy add-ons.
|
||||
* [django-api-client][django-api-client] - DRF client that groups the Endpoint response, for use in CBVs and FBV as if you were working with Django's Native Models..
|
||||
* [fast-drf] - A model based library for making API development faster and easier.
|
||||
* [django-requestlogs] - Providing middleware and other helpers for audit logging for REST framework.
|
||||
* [drf-standardized-errors][drf-standardized-errors] - DRF exception handler to standardize error responses for all API endpoints.
|
||||
|
||||
[cite]: http://www.software-ecosystems.com/Software_Ecosystems/Ecosystems.html
|
||||
[cookiecutter]: https://github.com/jpadilla/cookiecutter-django-rest-framework
|
||||
|
@ -183,6 +186,7 @@ To submit new content, [open an issue][drf-create-issue] or [create a pull reque
|
|||
[wq.db.rest]: https://wq.io/docs/about-rest
|
||||
[djangorestframework-msgpack]: https://github.com/juanriaza/django-rest-framework-msgpack
|
||||
[djangorestframework-camel-case]: https://github.com/vbabiy/djangorestframework-camel-case
|
||||
[nested-multipart-parser]: https://github.com/remigermain/nested-multipart-parser
|
||||
[djangorestframework-csv]: https://github.com/mjumbewu/django-rest-framework-csv
|
||||
[drf_ujson2]: https://github.com/Amertz08/drf_ujson2
|
||||
[rest-pandas]: https://github.com/wq/django-rest-pandas
|
||||
|
@ -193,7 +197,7 @@ To submit new content, [open an issue][drf-create-issue] or [create a pull reque
|
|||
[gaiarestframework]: https://github.com/AppsFuel/gaiarestframework
|
||||
[drf-extensions]: https://github.com/chibisov/drf-extensions
|
||||
[ember-django-adapter]: https://github.com/dustinfarris/ember-django-adapter
|
||||
[django-rest-auth]: https://github.com/Tivix/django-rest-auth/
|
||||
[dj-rest-auth]: https://github.com/iMerica/dj-rest-auth
|
||||
[django-versatileimagefield]: https://github.com/WGBH/django-versatileimagefield
|
||||
[django-versatileimagefield-drf-docs]:https://django-versatileimagefield.readthedocs.io/en/latest/drf_integration.html
|
||||
[drf-tracking]: https://github.com/aschn/drf-tracking
|
||||
|
@ -201,7 +205,7 @@ To submit new content, [open an issue][drf-create-issue] or [create a pull reque
|
|||
[dry-rest-permissions]: https://github.com/FJNR-inc/dry-rest-permissions
|
||||
[django-url-filter]: https://github.com/miki725/django-url-filter
|
||||
[drf-url-filter]: https://github.com/manjitkumar/drf-url-filters
|
||||
[cookiecutter-django-rest]: https://github.com/agconti/cookiecutter-django-rest
|
||||
[cookiecutter-django-rest]: https://github.com/agconti/cookiecutter-django-rest
|
||||
[drf-haystack]: https://drf-haystack.readthedocs.io/en/latest/
|
||||
[django-rest-framework-version-transforms]: https://github.com/mrhwick/django-rest-framework-version-transforms
|
||||
[djangorestframework-jsonapi]: https://github.com/django-json-api/django-rest-framework-json-api
|
||||
|
@ -225,7 +229,7 @@ To submit new content, [open an issue][drf-create-issue] or [create a pull reque
|
|||
[djangorestframework-dataclasses]: https://github.com/oxan/djangorestframework-dataclasses
|
||||
[django-restql]: https://github.com/yezyilomo/django-restql
|
||||
[djangorestframework-mvt]: https://github.com/corteva/djangorestframework-mvt
|
||||
[django-rest-framework-guardian]: https://github.com/rpkilby/django-rest-framework-guardian
|
||||
[django-rest-framework-guardian2]: https://github.com/johnthagen/django-rest-framework-guardian2
|
||||
[drf-viewset-profiler]: https://github.com/fvlima/drf-viewset-profiler
|
||||
[djangorestframework-features]: https://github.com/cloudcode-hungary/django-rest-framework-features/
|
||||
[django-elasticsearch-dsl-drf]: https://github.com/barseghyanartur/django-elasticsearch-dsl-drf
|
||||
|
@ -235,3 +239,5 @@ To submit new content, [open an issue][drf-create-issue] or [create a pull reque
|
|||
[graphwrap]: https://github.com/PaulGilmartin/graph_wrap
|
||||
[rest-framework-actions]: https://github.com/AlexisMunera98/rest-framework-actions
|
||||
[fast-drf]: https://github.com/iashraful/fast-drf
|
||||
[django-requestlogs]: https://github.com/Raekkeri/django-requestlogs
|
||||
[drf-standardized-errors]: https://github.com/ghazi-git/drf-standardized-errors
|
||||
|
|
|
@ -76,6 +76,7 @@ There are a wide range of resources available for learning and using Django REST
|
|||
* [Chatbot Using Django REST Framework + api.ai + Slack — Part 1/3][chatbot-using-drf-part1]
|
||||
* [New Django Admin with DRF and EmberJS... What are the News?][new-django-admin-with-drf-and-emberjs]
|
||||
* [Blog posts about Django REST Framework][medium-django-rest-framework]
|
||||
* [Implementing Rest APIs With Embedded Privacy][doordash-implementing-rest-apis]
|
||||
|
||||
### Documentations
|
||||
* [Classy Django REST Framework][cdrf.co]
|
||||
|
@ -128,3 +129,4 @@ Want your Django REST Framework talk/tutorial/article to be added to our website
|
|||
[anna-email]: mailto:anna@django-rest-framework.org
|
||||
[pycon-us-2017]: https://www.youtube.com/watch?v=Rk6MHZdust4
|
||||
[django-rest-react-valentinog]: https://www.valentinog.com/blog/tutorial-api-django-rest-react/
|
||||
[doordash-implementing-rest-apis]: https://doordash.engineering/2013/10/07/implementing-rest-apis-with-embedded-privacy/
|
||||
|
|
|
@ -1,231 +0,0 @@
|
|||
# Tutorial 7: Schemas & client libraries
|
||||
|
||||
A schema is a machine-readable document that describes the available API
|
||||
endpoints, their URLS, and what operations they support.
|
||||
|
||||
Schemas can be a useful tool for auto-generated documentation, and can also
|
||||
be used to drive dynamic client libraries that can interact with the API.
|
||||
|
||||
## Core API
|
||||
|
||||
In order to provide schema support REST framework uses [Core API][coreapi].
|
||||
|
||||
Core API is a document specification for describing APIs. It is used to provide
|
||||
an internal representation format of the available endpoints and possible
|
||||
interactions that an API exposes. It can either be used server-side, or
|
||||
client-side.
|
||||
|
||||
When used server-side, Core API allows an API to support rendering to a wide
|
||||
range of schema or hypermedia formats.
|
||||
|
||||
When used client-side, Core API allows for dynamically driven client libraries
|
||||
that can interact with any API that exposes a supported schema or hypermedia
|
||||
format.
|
||||
|
||||
## Adding a schema
|
||||
|
||||
REST framework supports either explicitly defined schema views, or
|
||||
automatically generated schemas. Since we're using viewsets and routers,
|
||||
we can simply use the automatic schema generation.
|
||||
|
||||
You'll need to install the `coreapi` python package in order to include an
|
||||
API schema, and `pyyaml` to render the schema into the commonly used
|
||||
YAML-based OpenAPI format.
|
||||
|
||||
$ pip install coreapi pyyaml
|
||||
|
||||
We can now include a schema for our API, by including an autogenerated schema
|
||||
view in our URL configuration.
|
||||
|
||||
```python
|
||||
from rest_framework.schemas import get_schema_view
|
||||
|
||||
schema_view = get_schema_view(title='Pastebin API')
|
||||
|
||||
urlpatterns = [
|
||||
path('schema/', schema_view),
|
||||
...
|
||||
]
|
||||
```
|
||||
|
||||
If you visit the `/schema/` endpoint in a browser you should now see `corejson`
|
||||
representation become available as an option.
|
||||
|
||||

|
||||
|
||||
We can also request the schema from the command line, by specifying the desired
|
||||
content type in the `Accept` header.
|
||||
|
||||
$ http http://127.0.0.1:8000/schema/ Accept:application/coreapi+json
|
||||
HTTP/1.0 200 OK
|
||||
Allow: GET, HEAD, OPTIONS
|
||||
Content-Type: application/coreapi+json
|
||||
|
||||
{
|
||||
"_meta": {
|
||||
"title": "Pastebin API"
|
||||
},
|
||||
"_type": "document",
|
||||
...
|
||||
|
||||
The default output style is to use the [Core JSON][corejson] encoding.
|
||||
|
||||
Other schema formats, such as [Open API][openapi] (formerly Swagger) are
|
||||
also supported.
|
||||
|
||||
## Using a command line client
|
||||
|
||||
Now that our API is exposing a schema endpoint, we can use a dynamic client
|
||||
library to interact with the API. To demonstrate this, let's use the
|
||||
Core API command line client.
|
||||
|
||||
The command line client is available as the `coreapi-cli` package:
|
||||
|
||||
$ pip install coreapi-cli
|
||||
|
||||
Now check that it is available on the command line...
|
||||
|
||||
$ coreapi
|
||||
Usage: coreapi [OPTIONS] COMMAND [ARGS]...
|
||||
|
||||
Command line client for interacting with CoreAPI services.
|
||||
|
||||
Visit https://www.coreapi.org/ for more information.
|
||||
|
||||
Options:
|
||||
--version Display the package version number.
|
||||
--help Show this message and exit.
|
||||
|
||||
Commands:
|
||||
...
|
||||
|
||||
First we'll load the API schema using the command line client.
|
||||
|
||||
$ coreapi get http://127.0.0.1:8000/schema/
|
||||
<Pastebin API "http://127.0.0.1:8000/schema/">
|
||||
snippets: {
|
||||
highlight(id)
|
||||
list()
|
||||
read(id)
|
||||
}
|
||||
users: {
|
||||
list()
|
||||
read(id)
|
||||
}
|
||||
|
||||
We haven't authenticated yet, so right now we're only able to see the read only
|
||||
endpoints, in line with how we've set up the permissions on the API.
|
||||
|
||||
Let's try listing the existing snippets, using the command line client:
|
||||
|
||||
$ coreapi action snippets list
|
||||
[
|
||||
{
|
||||
"url": "http://127.0.0.1:8000/snippets/1/",
|
||||
"id": 1,
|
||||
"highlight": "http://127.0.0.1:8000/snippets/1/highlight/",
|
||||
"owner": "lucy",
|
||||
"title": "Example",
|
||||
"code": "print('hello, world!')",
|
||||
"linenos": true,
|
||||
"language": "python",
|
||||
"style": "friendly"
|
||||
},
|
||||
...
|
||||
|
||||
Some of the API endpoints require named parameters. For example, to get back
|
||||
the highlight HTML for a particular snippet we need to provide an id.
|
||||
|
||||
$ coreapi action snippets highlight --param id=1
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
|
||||
|
||||
<html>
|
||||
<head>
|
||||
<title>Example</title>
|
||||
...
|
||||
|
||||
## Authenticating our client
|
||||
|
||||
If we want to be able to create, edit and delete snippets, we'll need to
|
||||
authenticate as a valid user. In this case we'll just use basic auth.
|
||||
|
||||
Make sure to replace the `<username>` and `<password>` below with your
|
||||
actual username and password.
|
||||
|
||||
$ coreapi credentials add 127.0.0.1 <username>:<password> --auth basic
|
||||
Added credentials
|
||||
127.0.0.1 "Basic <...>"
|
||||
|
||||
Now if we fetch the schema again, we should be able to see the full
|
||||
set of available interactions.
|
||||
|
||||
$ coreapi reload
|
||||
Pastebin API "http://127.0.0.1:8000/schema/">
|
||||
snippets: {
|
||||
create(code, [title], [linenos], [language], [style])
|
||||
delete(id)
|
||||
highlight(id)
|
||||
list()
|
||||
partial_update(id, [title], [code], [linenos], [language], [style])
|
||||
read(id)
|
||||
update(id, code, [title], [linenos], [language], [style])
|
||||
}
|
||||
users: {
|
||||
list()
|
||||
read(id)
|
||||
}
|
||||
|
||||
We're now able to interact with these endpoints. For example, to create a new
|
||||
snippet:
|
||||
|
||||
$ coreapi action snippets create --param title="Example" --param code="print('hello, world')"
|
||||
{
|
||||
"url": "http://127.0.0.1:8000/snippets/7/",
|
||||
"id": 7,
|
||||
"highlight": "http://127.0.0.1:8000/snippets/7/highlight/",
|
||||
"owner": "lucy",
|
||||
"title": "Example",
|
||||
"code": "print('hello, world')",
|
||||
"linenos": false,
|
||||
"language": "python",
|
||||
"style": "friendly"
|
||||
}
|
||||
|
||||
And to delete a snippet:
|
||||
|
||||
$ coreapi action snippets delete --param id=7
|
||||
|
||||
As well as the command line client, developers can also interact with your
|
||||
API using client libraries. The Python client library is the first of these
|
||||
to be available, and a Javascript client library is planned to be released
|
||||
soon.
|
||||
|
||||
For more details on customizing schema generation and using Core API
|
||||
client libraries you'll need to refer to the full documentation.
|
||||
|
||||
## Reviewing our work
|
||||
|
||||
With an incredibly small amount of code, we've now got a complete pastebin Web API, which is fully web browsable, includes a schema-driven client library, and comes complete with authentication, per-object permissions, and multiple renderer formats.
|
||||
|
||||
We've walked through each step of the design process, and seen how if we need to customize anything we can gradually work our way down to simply using regular Django views.
|
||||
|
||||
You can review the final [tutorial code][repo] on GitHub, or try out a live example in [the sandbox][sandbox].
|
||||
|
||||
## Onwards and upwards
|
||||
|
||||
We've reached the end of our tutorial. If you want to get more involved in the REST framework project, here are a few places you can start:
|
||||
|
||||
* Contribute on [GitHub][github] by reviewing and submitting issues, and making pull requests.
|
||||
* Join the [REST framework discussion group][group], and help build the community.
|
||||
* Follow [the author][twitter] on Twitter and say hi.
|
||||
|
||||
**Now go build awesome things.**
|
||||
|
||||
[coreapi]: https://www.coreapi.org/
|
||||
[corejson]: https://www.coreapi.org/specification/encoding/#core-json-encoding
|
||||
[openapi]: https://openapis.org/
|
||||
[repo]: https://github.com/encode/rest-framework-tutorial
|
||||
[sandbox]: https://restframework.herokuapp.com/
|
||||
[github]: https://github.com/encode/django-rest-framework
|
||||
[group]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework
|
||||
[twitter]: https://twitter.com/_tomchristie
|
|
@ -1,171 +0,0 @@
|
|||
|
||||
## Built-in API documentation
|
||||
|
||||
The built-in API documentation includes:
|
||||
|
||||
* Documentation of API endpoints.
|
||||
* Automatically generated code samples for each of the available API client libraries.
|
||||
* Support for API interaction.
|
||||
|
||||
### Installation
|
||||
|
||||
The `coreapi` library is required as a dependency for the API docs. Make sure
|
||||
to install the latest version. The `Pygments` and `Markdown` libraries
|
||||
are optional but recommended.
|
||||
|
||||
To install the API documentation, you'll need to include it in your project's URLconf:
|
||||
|
||||
from rest_framework.documentation import include_docs_urls
|
||||
|
||||
urlpatterns = [
|
||||
...
|
||||
path('docs/', include_docs_urls(title='My API title'))
|
||||
]
|
||||
|
||||
This will include two different views:
|
||||
|
||||
* `/docs/` - The documentation page itself.
|
||||
* `/docs/schema.js` - A JavaScript resource that exposes the API schema.
|
||||
|
||||
---
|
||||
|
||||
**Note**: By default `include_docs_urls` configures the underlying `SchemaView` to generate _public_ schemas.
|
||||
This means that views will not be instantiated with a `request` instance. i.e. Inside the view `self.request` will be `None`.
|
||||
|
||||
To be compatible with this behaviour, methods (such as `get_serializer` or `get_serializer_class` etc.) which inspect `self.request` or, particularly, `self.request.user` may need to be adjusted to handle this case.
|
||||
|
||||
You may ensure views are given a `request` instance by calling `include_docs_urls` with `public=False`:
|
||||
|
||||
from rest_framework.documentation import include_docs_urls
|
||||
|
||||
urlpatterns = [
|
||||
...
|
||||
# Generate schema with valid `request` instance:
|
||||
path('docs/', include_docs_urls(title='My API title', public=False))
|
||||
]
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
### Documenting your views
|
||||
|
||||
You can document your views by including docstrings that describe each of the available actions.
|
||||
For example:
|
||||
|
||||
class UserList(generics.ListAPIView):
|
||||
"""
|
||||
Return a list of all the existing users.
|
||||
"""
|
||||
|
||||
If a view supports multiple methods, you should split your documentation using `method:` style delimiters.
|
||||
|
||||
class UserList(generics.ListCreateAPIView):
|
||||
"""
|
||||
get:
|
||||
Return a list of all the existing users.
|
||||
|
||||
post:
|
||||
Create a new user instance.
|
||||
"""
|
||||
|
||||
When using viewsets, you should use the relevant action names as delimiters.
|
||||
|
||||
class UserViewSet(viewsets.ModelViewSet):
|
||||
"""
|
||||
retrieve:
|
||||
Return the given user.
|
||||
|
||||
list:
|
||||
Return a list of all the existing users.
|
||||
|
||||
create:
|
||||
Create a new user instance.
|
||||
"""
|
||||
|
||||
Custom actions on viewsets can also be documented in a similar way using the method names
|
||||
as delimiters or by attaching the documentation to action mapping methods.
|
||||
|
||||
class UserViewSet(viewsets.ModelViewset):
|
||||
...
|
||||
|
||||
@action(detail=False, methods=['get', 'post'])
|
||||
def some_action(self, request, *args, **kwargs):
|
||||
"""
|
||||
get:
|
||||
A description of the get method on the custom action.
|
||||
|
||||
post:
|
||||
A description of the post method on the custom action.
|
||||
"""
|
||||
|
||||
@some_action.mapping.put
|
||||
def put_some_action():
|
||||
"""
|
||||
A description of the put method on the custom action.
|
||||
"""
|
||||
|
||||
|
||||
### `documentation` API Reference
|
||||
|
||||
The `rest_framework.documentation` module provides three helper functions to help configure the interactive API documentation, `include_docs_urls` (usage shown above), `get_docs_view` and `get_schemajs_view`.
|
||||
|
||||
`include_docs_urls` employs `get_docs_view` and `get_schemajs_view` to generate the url patterns for the documentation page and JavaScript resource that exposes the API schema respectively. They expose the following options for customisation. (`get_docs_view` and `get_schemajs_view` ultimately call `rest_frameworks.schemas.get_schema_view()`, see the Schemas docs for more options there.)
|
||||
|
||||
#### `include_docs_urls`
|
||||
|
||||
* `title`: Default `None`. May be used to provide a descriptive title for the schema definition.
|
||||
* `description`: Default `None`. May be used to provide a description for the schema definition.
|
||||
* `schema_url`: Default `None`. May be used to pass a canonical base URL for the schema.
|
||||
* `public`: Default `True`. Should the schema be considered _public_? If `True` schema is generated without a `request` instance being passed to views.
|
||||
* `patterns`: Default `None`. A list of URLs to inspect when generating the schema. If `None` project's URL conf will be used.
|
||||
* `generator_class`: Default `rest_framework.schemas.SchemaGenerator`. May be used to specify a `SchemaGenerator` subclass to be passed to the `SchemaView`.
|
||||
* `authentication_classes`: Default `api_settings.DEFAULT_AUTHENTICATION_CLASSES`. May be used to pass custom authentication classes to the `SchemaView`.
|
||||
* `permission_classes`: Default `api_settings.DEFAULT_PERMISSION_CLASSES` May be used to pass custom permission classes to the `SchemaView`.
|
||||
* `renderer_classes`: Default `None`. May be used to pass custom renderer classes to the `SchemaView`.
|
||||
|
||||
#### `get_docs_view`
|
||||
|
||||
* `title`: Default `None`. May be used to provide a descriptive title for the schema definition.
|
||||
* `description`: Default `None`. May be used to provide a description for the schema definition.
|
||||
* `schema_url`: Default `None`. May be used to pass a canonical base URL for the schema.
|
||||
* `public`: Default `True`. If `True` schema is generated without a `request` instance being passed to views.
|
||||
* `patterns`: Default `None`. A list of URLs to inspect when generating the schema. If `None` project's URL conf will be used.
|
||||
* `generator_class`: Default `rest_framework.schemas.SchemaGenerator`. May be used to specify a `SchemaGenerator` subclass to be passed to the `SchemaView`.
|
||||
* `authentication_classes`: Default `api_settings.DEFAULT_AUTHENTICATION_CLASSES`. May be used to pass custom authentication classes to the `SchemaView`.
|
||||
* `permission_classes`: Default `api_settings.DEFAULT_PERMISSION_CLASSES`. May be used to pass custom permission classes to the `SchemaView`.
|
||||
* `renderer_classes`: Default `None`. May be used to pass custom renderer classes to the `SchemaView`. If `None` the `SchemaView` will be configured with `DocumentationRenderer` and `CoreJSONRenderer` renderers, corresponding to the (default) `html` and `corejson` formats.
|
||||
|
||||
#### `get_schemajs_view`
|
||||
|
||||
* `title`: Default `None`. May be used to provide a descriptive title for the schema definition.
|
||||
* `description`: Default `None`. May be used to provide a description for the schema definition.
|
||||
* `schema_url`: Default `None`. May be used to pass a canonical base URL for the schema.
|
||||
* `public`: Default `True`. If `True` schema is generated without a `request` instance being passed to views.
|
||||
* `patterns`: Default `None`. A list of URLs to inspect when generating the schema. If `None` project's URL conf will be used.
|
||||
* `generator_class`: Default `rest_framework.schemas.SchemaGenerator`. May be used to specify a `SchemaGenerator` subclass to be passed to the `SchemaView`.
|
||||
* `authentication_classes`: Default `api_settings.DEFAULT_AUTHENTICATION_CLASSES`. May be used to pass custom authentication classes to the `SchemaView`.
|
||||
* `permission_classes`: Default `api_settings.DEFAULT_PERMISSION_CLASSES` May be used to pass custom permission classes to the `SchemaView`.
|
||||
|
||||
|
||||
### Customising code samples
|
||||
|
||||
The built-in API documentation includes automatically generated code samples for
|
||||
each of the available API client libraries.
|
||||
|
||||
You may customise these samples by subclassing `DocumentationRenderer`, setting
|
||||
`languages` to the list of languages you wish to support:
|
||||
|
||||
from rest_framework.renderers import DocumentationRenderer
|
||||
|
||||
|
||||
class CustomRenderer(DocumentationRenderer):
|
||||
languages = ['ruby', 'go']
|
||||
|
||||
For each language you need to provide an `intro` template, detailing installation instructions and such,
|
||||
plus a generic template for making API requests, that can be filled with individual request details.
|
||||
See the [templates for the bundled languages][client-library-templates] for examples.
|
||||
|
||||
---
|
||||
|
||||
[client-library-templates]: https://github.com/encode/django-rest-framework/tree/master/rest_framework/templates/rest_framework/docs/langs
|
|
@ -1,29 +0,0 @@
|
|||
# Legacy CoreAPI Schemas Docs
|
||||
|
||||
Use of CoreAPI-based schemas were deprecated with the introduction of native OpenAPI-based schema generation in Django REST Framework v3.10.
|
||||
|
||||
See the [Version 3.10 Release Announcement](/community/3.10-announcement.md) for more details.
|
||||
|
||||
----
|
||||
|
||||
You can continue to use CoreAPI schemas by setting the appropriate default schema class:
|
||||
|
||||
```python
|
||||
# In settings.py
|
||||
REST_FRAMEWORK = {
|
||||
'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema',
|
||||
}
|
||||
```
|
||||
|
||||
Under-the-hood, any subclass of `coreapi.AutoSchema` here will trigger use of the old CoreAPI schemas.
|
||||
**Otherwise** you will automatically be opted-in to the new OpenAPI schemas.
|
||||
|
||||
All CoreAPI related code will be removed in Django REST Framework v3.12. Switch to OpenAPI schemas by then.
|
||||
|
||||
----
|
||||
|
||||
For reference this folder contains the old CoreAPI related documentation:
|
||||
|
||||
* [Tutorial 7: Schemas & client libraries](https://github.com/encode/django-rest-framework/blob/master/docs/coreapi//7-schemas-and-client-libraries.md).
|
||||
* [Excerpts from _Documenting your API_ topic page](https://github.com/encode/django-rest-framework/blob/master/docs/coreapi//from-documenting-your-api.md).
|
||||
* [`rest_framework.schemas` API Reference](https://github.com/encode/django-rest-framework/blob/master/docs/coreapi//schemas.md).
|
|
@ -1,846 +0,0 @@
|
|||
source: schemas.py
|
||||
|
||||
# Schemas
|
||||
|
||||
> A machine-readable [schema] describes what resources are available via the API, what their URLs are, how they are represented and what operations they support.
|
||||
>
|
||||
> — Heroku, [JSON Schema for the Heroku Platform API][cite]
|
||||
|
||||
API schemas are a useful tool that allow for a range of use cases, including
|
||||
generating reference documentation, or driving dynamic client libraries that
|
||||
can interact with your API.
|
||||
|
||||
## Install Core API & PyYAML
|
||||
|
||||
You'll need to install the `coreapi` package in order to add schema support
|
||||
for REST framework. You probably also want to install `pyyaml`, so that you
|
||||
can render the schema into the commonly used YAML-based OpenAPI format.
|
||||
|
||||
pip install coreapi pyyaml
|
||||
|
||||
## Quickstart
|
||||
|
||||
There are two different ways you can serve a schema description for your API.
|
||||
|
||||
### Generating a schema with the `generateschema` management command
|
||||
|
||||
To generate a static API schema, use the `generateschema` management command.
|
||||
|
||||
```shell
|
||||
$ python manage.py generateschema > schema.yml
|
||||
```
|
||||
|
||||
Once you've generated a schema in this way you can annotate it with any
|
||||
additional information that cannot be automatically inferred by the schema
|
||||
generator.
|
||||
|
||||
You might want to check your API schema into version control and update it
|
||||
with each new release, or serve the API schema from your site's static media.
|
||||
|
||||
### Adding a view with `get_schema_view`
|
||||
|
||||
To add a dynamically generated schema view to your API, use `get_schema_view`.
|
||||
|
||||
```python
|
||||
from rest_framework.schemas import get_schema_view
|
||||
from django.urls import path
|
||||
|
||||
schema_view = get_schema_view(title="Example API")
|
||||
|
||||
urlpatterns = [
|
||||
path('schema', schema_view),
|
||||
...
|
||||
]
|
||||
```
|
||||
|
||||
See below [for more details](#the-get_schema_view-shortcut) on customizing a
|
||||
dynamically generated schema view.
|
||||
|
||||
## Internal schema representation
|
||||
|
||||
REST framework uses [Core API][coreapi] in order to model schema information in
|
||||
a format-independent representation. This information can then be rendered
|
||||
into various different schema formats, or used to generate API documentation.
|
||||
|
||||
When using Core API, a schema is represented as a `Document` which is the
|
||||
top-level container object for information about the API. Available API
|
||||
interactions are represented using `Link` objects. Each link includes a URL,
|
||||
HTTP method, and may include a list of `Field` instances, which describe any
|
||||
parameters that may be accepted by the API endpoint. The `Link` and `Field`
|
||||
instances may also include descriptions, that allow an API schema to be
|
||||
rendered into user documentation.
|
||||
|
||||
Here's an example of an API description that includes a single `search`
|
||||
endpoint:
|
||||
|
||||
coreapi.Document(
|
||||
title='Flight Search API',
|
||||
url='https://api.example.org/',
|
||||
content={
|
||||
'search': coreapi.Link(
|
||||
url='/search/',
|
||||
action='get',
|
||||
fields=[
|
||||
coreapi.Field(
|
||||
name='from',
|
||||
required=True,
|
||||
location='query',
|
||||
description='City name or airport code.'
|
||||
),
|
||||
coreapi.Field(
|
||||
name='to',
|
||||
required=True,
|
||||
location='query',
|
||||
description='City name or airport code.'
|
||||
),
|
||||
coreapi.Field(
|
||||
name='date',
|
||||
required=True,
|
||||
location='query',
|
||||
description='Flight date in "YYYY-MM-DD" format.'
|
||||
)
|
||||
],
|
||||
description='Return flight availability and prices.'
|
||||
)
|
||||
}
|
||||
)
|
||||
|
||||
## Schema output formats
|
||||
|
||||
In order to be presented in an HTTP response, the internal representation
|
||||
has to be rendered into the actual bytes that are used in the response.
|
||||
|
||||
REST framework includes a few different renderers that you can use for
|
||||
encoding the API schema.
|
||||
|
||||
* `renderers.OpenAPIRenderer` - Renders into YAML-based [OpenAPI][open-api], the most widely used API schema format.
|
||||
* `renderers.JSONOpenAPIRenderer` - Renders into JSON-based [OpenAPI][open-api].
|
||||
* `renderers.CoreJSONRenderer` - Renders into [Core JSON][corejson], a format designed for
|
||||
use with the `coreapi` client library.
|
||||
|
||||
|
||||
[Core JSON][corejson] is designed as a canonical format for use with Core API.
|
||||
REST framework includes a renderer class for handling this media type, which
|
||||
is available as `renderers.CoreJSONRenderer`.
|
||||
|
||||
|
||||
## Schemas vs Hypermedia
|
||||
|
||||
It's worth pointing out here that Core API can also be used to model hypermedia
|
||||
responses, which present an alternative interaction style to API schemas.
|
||||
|
||||
With an API schema, the entire available interface is presented up-front
|
||||
as a single endpoint. Responses to individual API endpoints are then typically
|
||||
presented as plain data, without any further interactions contained in each
|
||||
response.
|
||||
|
||||
With Hypermedia, the client is instead presented with a document containing
|
||||
both data and available interactions. Each interaction results in a new
|
||||
document, detailing both the current state and the available interactions.
|
||||
|
||||
Further information and support on building Hypermedia APIs with REST framework
|
||||
is planned for a future version.
|
||||
|
||||
|
||||
---
|
||||
|
||||
# Creating a schema
|
||||
|
||||
REST framework includes functionality for auto-generating a schema,
|
||||
or allows you to specify one explicitly.
|
||||
|
||||
## Manual Schema Specification
|
||||
|
||||
To manually specify a schema you create a Core API `Document`, similar to the
|
||||
example above.
|
||||
|
||||
schema = coreapi.Document(
|
||||
title='Flight Search API',
|
||||
content={
|
||||
...
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
## Automatic Schema Generation
|
||||
|
||||
Automatic schema generation is provided by the `SchemaGenerator` class.
|
||||
|
||||
`SchemaGenerator` processes a list of routed URL patterns and compiles the
|
||||
appropriately structured Core API Document.
|
||||
|
||||
Basic usage is just to provide the title for your schema and call
|
||||
`get_schema()`:
|
||||
|
||||
generator = schemas.SchemaGenerator(title='Flight Search API')
|
||||
schema = generator.get_schema()
|
||||
|
||||
## Per-View Schema Customisation
|
||||
|
||||
By default, view introspection is performed by an `AutoSchema` instance
|
||||
accessible via the `schema` attribute on `APIView`. This provides the
|
||||
appropriate Core API `Link` object for the view, request method and path:
|
||||
|
||||
auto_schema = view.schema
|
||||
coreapi_link = auto_schema.get_link(...)
|
||||
|
||||
(In compiling the schema, `SchemaGenerator` calls `view.schema.get_link()` for
|
||||
each view, allowed method and path.)
|
||||
|
||||
---
|
||||
|
||||
**Note**: For basic `APIView` subclasses, default introspection is essentially
|
||||
limited to the URL kwarg path parameters. For `GenericAPIView`
|
||||
subclasses, which includes all the provided class based views, `AutoSchema` will
|
||||
attempt to introspect serializer, pagination and filter fields, as well as
|
||||
provide richer path field descriptions. (The key hooks here are the relevant
|
||||
`GenericAPIView` attributes and methods: `get_serializer`, `pagination_class`,
|
||||
`filter_backends` and so on.)
|
||||
|
||||
---
|
||||
|
||||
To customise the `Link` generation you may:
|
||||
|
||||
* Instantiate `AutoSchema` on your view with the `manual_fields` kwarg:
|
||||
|
||||
from rest_framework.views import APIView
|
||||
from rest_framework.schemas import AutoSchema
|
||||
|
||||
class CustomView(APIView):
|
||||
...
|
||||
schema = AutoSchema(
|
||||
manual_fields=[
|
||||
coreapi.Field("extra_field", ...),
|
||||
]
|
||||
)
|
||||
|
||||
This allows extension for the most common case without subclassing.
|
||||
|
||||
* Provide an `AutoSchema` subclass with more complex customisation:
|
||||
|
||||
from rest_framework.views import APIView
|
||||
from rest_framework.schemas import AutoSchema
|
||||
|
||||
class CustomSchema(AutoSchema):
|
||||
def get_link(...):
|
||||
# Implement custom introspection here (or in other sub-methods)
|
||||
|
||||
class CustomView(APIView):
|
||||
...
|
||||
schema = CustomSchema()
|
||||
|
||||
This provides complete control over view introspection.
|
||||
|
||||
* Instantiate `ManualSchema` on your view, providing the Core API `Fields` for
|
||||
the view explicitly:
|
||||
|
||||
from rest_framework.views import APIView
|
||||
from rest_framework.schemas import ManualSchema
|
||||
|
||||
class CustomView(APIView):
|
||||
...
|
||||
schema = ManualSchema(fields=[
|
||||
coreapi.Field(
|
||||
"first_field",
|
||||
required=True,
|
||||
location="path",
|
||||
schema=coreschema.String()
|
||||
),
|
||||
coreapi.Field(
|
||||
"second_field",
|
||||
required=True,
|
||||
location="path",
|
||||
schema=coreschema.String()
|
||||
),
|
||||
])
|
||||
|
||||
This allows manually specifying the schema for some views whilst maintaining
|
||||
automatic generation elsewhere.
|
||||
|
||||
You may disable schema generation for a view by setting `schema` to `None`:
|
||||
|
||||
class CustomView(APIView):
|
||||
...
|
||||
schema = None # Will not appear in schema
|
||||
|
||||
This also applies to extra actions for `ViewSet`s:
|
||||
|
||||
class CustomViewSet(viewsets.ModelViewSet):
|
||||
|
||||
@action(detail=True, schema=None)
|
||||
def extra_action(self, request, pk=None):
|
||||
...
|
||||
|
||||
---
|
||||
|
||||
**Note**: For full details on `SchemaGenerator` plus the `AutoSchema` and
|
||||
`ManualSchema` descriptors see the [API Reference below](#api-reference).
|
||||
|
||||
---
|
||||
|
||||
# Adding a schema view
|
||||
|
||||
There are a few different ways to add a schema view to your API, depending on
|
||||
exactly what you need.
|
||||
|
||||
## The get_schema_view shortcut
|
||||
|
||||
The simplest way to include a schema in your project is to use the
|
||||
`get_schema_view()` function.
|
||||
|
||||
from rest_framework.schemas import get_schema_view
|
||||
|
||||
schema_view = get_schema_view(title="Server Monitoring API")
|
||||
|
||||
urlpatterns = [
|
||||
path('', schema_view),
|
||||
...
|
||||
]
|
||||
|
||||
Once the view has been added, you'll be able to make API requests to retrieve
|
||||
the auto-generated schema definition.
|
||||
|
||||
$ http http://127.0.0.1:8000/ Accept:application/coreapi+json
|
||||
HTTP/1.0 200 OK
|
||||
Allow: GET, HEAD, OPTIONS
|
||||
Content-Type: application/vnd.coreapi+json
|
||||
|
||||
{
|
||||
"_meta": {
|
||||
"title": "Server Monitoring API"
|
||||
},
|
||||
"_type": "document",
|
||||
...
|
||||
}
|
||||
|
||||
The arguments to `get_schema_view()` are:
|
||||
|
||||
#### `title`
|
||||
|
||||
May be used to provide a descriptive title for the schema definition.
|
||||
|
||||
#### `url`
|
||||
|
||||
May be used to pass a canonical URL for the schema.
|
||||
|
||||
schema_view = get_schema_view(
|
||||
title='Server Monitoring API',
|
||||
url='https://www.example.org/api/'
|
||||
)
|
||||
|
||||
#### `urlconf`
|
||||
|
||||
A string representing the import path to the URL conf that you want
|
||||
to generate an API schema for. This defaults to the value of Django's
|
||||
ROOT_URLCONF setting.
|
||||
|
||||
schema_view = get_schema_view(
|
||||
title='Server Monitoring API',
|
||||
url='https://www.example.org/api/',
|
||||
urlconf='myproject.urls'
|
||||
)
|
||||
|
||||
#### `renderer_classes`
|
||||
|
||||
May be used to pass the set of renderer classes that can be used to render the API root endpoint.
|
||||
|
||||
from rest_framework.schemas import get_schema_view
|
||||
from rest_framework.renderers import JSONOpenAPIRenderer
|
||||
|
||||
schema_view = get_schema_view(
|
||||
title='Server Monitoring API',
|
||||
url='https://www.example.org/api/',
|
||||
renderer_classes=[JSONOpenAPIRenderer]
|
||||
)
|
||||
|
||||
#### `patterns`
|
||||
|
||||
List of url patterns to limit the schema introspection to. If you only want the `myproject.api` urls
|
||||
to be exposed in the schema:
|
||||
|
||||
schema_url_patterns = [
|
||||
path('api/', include('myproject.api.urls')),
|
||||
]
|
||||
|
||||
schema_view = get_schema_view(
|
||||
title='Server Monitoring API',
|
||||
url='https://www.example.org/api/',
|
||||
patterns=schema_url_patterns,
|
||||
)
|
||||
|
||||
#### `generator_class`
|
||||
|
||||
May be used to specify a `SchemaGenerator` subclass to be passed to the
|
||||
`SchemaView`.
|
||||
|
||||
#### `authentication_classes`
|
||||
|
||||
May be used to specify the list of authentication classes that will apply to the schema endpoint.
|
||||
Defaults to `settings.DEFAULT_AUTHENTICATION_CLASSES`
|
||||
|
||||
#### `permission_classes`
|
||||
|
||||
May be used to specify the list of permission classes that will apply to the schema endpoint.
|
||||
Defaults to `settings.DEFAULT_PERMISSION_CLASSES`
|
||||
|
||||
## Using an explicit schema view
|
||||
|
||||
If you need a little more control than the `get_schema_view()` shortcut gives you,
|
||||
then you can use the `SchemaGenerator` class directly to auto-generate the
|
||||
`Document` instance, and to return that from a view.
|
||||
|
||||
This option gives you the flexibility of setting up the schema endpoint
|
||||
with whatever behaviour you want. For example, you can apply different
|
||||
permission, throttling, or authentication policies to the schema endpoint.
|
||||
|
||||
Here's an example of using `SchemaGenerator` together with a view to
|
||||
return the schema.
|
||||
|
||||
**views.py:**
|
||||
|
||||
from rest_framework.decorators import api_view, renderer_classes
|
||||
from rest_framework import renderers, response, schemas
|
||||
|
||||
generator = schemas.SchemaGenerator(title='Bookings API')
|
||||
|
||||
@api_view()
|
||||
@renderer_classes([renderers.OpenAPIRenderer])
|
||||
def schema_view(request):
|
||||
schema = generator.get_schema(request)
|
||||
return response.Response(schema)
|
||||
|
||||
**urls.py:**
|
||||
|
||||
urlpatterns = [
|
||||
path('', schema_view),
|
||||
...
|
||||
]
|
||||
|
||||
You can also serve different schemas to different users, depending on the
|
||||
permissions they have available. This approach can be used to ensure that
|
||||
unauthenticated requests are presented with a different schema to
|
||||
authenticated requests, or to ensure that different parts of the API are
|
||||
made visible to different users depending on their role.
|
||||
|
||||
In order to present a schema with endpoints filtered by user permissions,
|
||||
you need to pass the `request` argument to the `get_schema()` method, like so:
|
||||
|
||||
@api_view()
|
||||
@renderer_classes([renderers.OpenAPIRenderer])
|
||||
def schema_view(request):
|
||||
generator = schemas.SchemaGenerator(title='Bookings API')
|
||||
return response.Response(generator.get_schema(request=request))
|
||||
|
||||
## Explicit schema definition
|
||||
|
||||
An alternative to the auto-generated approach is to specify the API schema
|
||||
explicitly, by declaring a `Document` object in your codebase. Doing so is a
|
||||
little more work, but ensures that you have full control over the schema
|
||||
representation.
|
||||
|
||||
import coreapi
|
||||
from rest_framework.decorators import api_view, renderer_classes
|
||||
from rest_framework import renderers, response
|
||||
|
||||
schema = coreapi.Document(
|
||||
title='Bookings API',
|
||||
content={
|
||||
...
|
||||
}
|
||||
)
|
||||
|
||||
@api_view()
|
||||
@renderer_classes([renderers.OpenAPIRenderer])
|
||||
def schema_view(request):
|
||||
return response.Response(schema)
|
||||
|
||||
---
|
||||
|
||||
# Schemas as documentation
|
||||
|
||||
One common usage of API schemas is to use them to build documentation pages.
|
||||
|
||||
The schema generation in REST framework uses docstrings to automatically
|
||||
populate descriptions in the schema document.
|
||||
|
||||
These descriptions will be based on:
|
||||
|
||||
* The corresponding method docstring if one exists.
|
||||
* A named section within the class docstring, which can be either single line or multi-line.
|
||||
* The class docstring.
|
||||
|
||||
## Examples
|
||||
|
||||
An `APIView`, with an explicit method docstring.
|
||||
|
||||
class ListUsernames(APIView):
|
||||
def get(self, request):
|
||||
"""
|
||||
Return a list of all user names in the system.
|
||||
"""
|
||||
usernames = [user.username for user in User.objects.all()]
|
||||
return Response(usernames)
|
||||
|
||||
A `ViewSet`, with an explicit action docstring.
|
||||
|
||||
class ListUsernames(ViewSet):
|
||||
def list(self, request):
|
||||
"""
|
||||
Return a list of all user names in the system.
|
||||
"""
|
||||
usernames = [user.username for user in User.objects.all()]
|
||||
return Response(usernames)
|
||||
|
||||
A generic view with sections in the class docstring, using single-line style.
|
||||
|
||||
class UserList(generics.ListCreateAPIView):
|
||||
"""
|
||||
get: List all the users.
|
||||
post: Create a new user.
|
||||
"""
|
||||
queryset = User.objects.all()
|
||||
serializer_class = UserSerializer
|
||||
permission_classes = [IsAdminUser]
|
||||
|
||||
A generic viewset with sections in the class docstring, using multi-line style.
|
||||
|
||||
class UserViewSet(viewsets.ModelViewSet):
|
||||
"""
|
||||
API endpoint that allows users to be viewed or edited.
|
||||
|
||||
retrieve:
|
||||
Return a user instance.
|
||||
|
||||
list:
|
||||
Return all users, ordered by most recently joined.
|
||||
"""
|
||||
queryset = User.objects.all().order_by('-date_joined')
|
||||
serializer_class = UserSerializer
|
||||
|
||||
---
|
||||
|
||||
# API Reference
|
||||
|
||||
## SchemaGenerator
|
||||
|
||||
A class that walks a list of routed URL patterns, requests the schema for each view,
|
||||
and collates the resulting CoreAPI Document.
|
||||
|
||||
Typically you'll instantiate `SchemaGenerator` with a single argument, like so:
|
||||
|
||||
generator = SchemaGenerator(title='Stock Prices API')
|
||||
|
||||
Arguments:
|
||||
|
||||
* `title` **required** - The name of the API.
|
||||
* `url` - The root URL of the API schema. This option is not required unless the schema is included under path prefix.
|
||||
* `patterns` - A list of URLs to inspect when generating the schema. Defaults to the project's URL conf.
|
||||
* `urlconf` - A URL conf module name to use when generating the schema. Defaults to `settings.ROOT_URLCONF`.
|
||||
|
||||
### get_schema(self, request)
|
||||
|
||||
Returns a `coreapi.Document` instance that represents the API schema.
|
||||
|
||||
@api_view
|
||||
@renderer_classes([renderers.OpenAPIRenderer])
|
||||
def schema_view(request):
|
||||
generator = schemas.SchemaGenerator(title='Bookings API')
|
||||
return Response(generator.get_schema())
|
||||
|
||||
The `request` argument is optional, and may be used if you want to apply per-user
|
||||
permissions to the resulting schema generation.
|
||||
|
||||
### get_links(self, request)
|
||||
|
||||
Return a nested dictionary containing all the links that should be included in the API schema.
|
||||
|
||||
This is a good point to override if you want to modify the resulting structure of the generated schema,
|
||||
as you can build a new dictionary with a different layout.
|
||||
|
||||
|
||||
## AutoSchema
|
||||
|
||||
A class that deals with introspection of individual views for schema generation.
|
||||
|
||||
`AutoSchema` is attached to `APIView` via the `schema` attribute.
|
||||
|
||||
The `AutoSchema` constructor takes a single keyword argument `manual_fields`.
|
||||
|
||||
**`manual_fields`**: a `list` of `coreapi.Field` instances that will be added to
|
||||
the generated fields. Generated fields with a matching `name` will be overwritten.
|
||||
|
||||
class CustomView(APIView):
|
||||
schema = AutoSchema(manual_fields=[
|
||||
coreapi.Field(
|
||||
"my_extra_field",
|
||||
required=True,
|
||||
location="path",
|
||||
schema=coreschema.String()
|
||||
),
|
||||
])
|
||||
|
||||
For more advanced customisation subclass `AutoSchema` to customise schema generation.
|
||||
|
||||
class CustomViewSchema(AutoSchema):
|
||||
"""
|
||||
Overrides `get_link()` to provide Custom Behavior X
|
||||
"""
|
||||
|
||||
def get_link(self, path, method, base_url):
|
||||
link = super().get_link(path, method, base_url)
|
||||
# Do something to customize link here...
|
||||
return link
|
||||
|
||||
class MyView(APIView):
|
||||
schema = CustomViewSchema()
|
||||
|
||||
The following methods are available to override.
|
||||
|
||||
### get_link(self, path, method, base_url)
|
||||
|
||||
Returns a `coreapi.Link` instance corresponding to the given view.
|
||||
|
||||
This is the main entry point.
|
||||
You can override this if you need to provide custom behaviors for particular views.
|
||||
|
||||
### get_description(self, path, method)
|
||||
|
||||
Returns a string to use as the link description. By default this is based on the
|
||||
view docstring as described in the "Schemas as Documentation" section above.
|
||||
|
||||
### get_encoding(self, path, method)
|
||||
|
||||
Returns a string to indicate the encoding for any request body, when interacting
|
||||
with the given view. Eg. `'application/json'`. May return a blank string for views
|
||||
that do not expect a request body.
|
||||
|
||||
### get_path_fields(self, path, method):
|
||||
|
||||
Return a list of `coreapi.Field()` instances. One for each path parameter in the URL.
|
||||
|
||||
### get_serializer_fields(self, path, method)
|
||||
|
||||
Return a list of `coreapi.Field()` instances. One for each field in the serializer class used by the view.
|
||||
|
||||
### get_pagination_fields(self, path, method)
|
||||
|
||||
Return a list of `coreapi.Field()` instances, as returned by the `get_schema_fields()` method on any pagination class used by the view.
|
||||
|
||||
### get_filter_fields(self, path, method)
|
||||
|
||||
Return a list of `coreapi.Field()` instances, as returned by the `get_schema_fields()` method of any filter classes used by the view.
|
||||
|
||||
### get_manual_fields(self, path, method)
|
||||
|
||||
Return a list of `coreapi.Field()` instances to be added to or replace generated fields. Defaults to (optional) `manual_fields` passed to `AutoSchema` constructor.
|
||||
|
||||
May be overridden to customise manual fields by `path` or `method`. For example, a per-method adjustment may look like this:
|
||||
|
||||
```python
|
||||
def get_manual_fields(self, path, method):
|
||||
"""Example adding per-method fields."""
|
||||
|
||||
extra_fields = []
|
||||
if method=='GET':
|
||||
extra_fields = # ... list of extra fields for GET ...
|
||||
if method=='POST':
|
||||
extra_fields = # ... list of extra fields for POST ...
|
||||
|
||||
manual_fields = super().get_manual_fields(path, method)
|
||||
return manual_fields + extra_fields
|
||||
```
|
||||
|
||||
### update_fields(fields, update_with)
|
||||
|
||||
Utility `staticmethod`. Encapsulates logic to add or replace fields from a list
|
||||
by `Field.name`. May be overridden to adjust replacement criteria.
|
||||
|
||||
|
||||
## ManualSchema
|
||||
|
||||
Allows manually providing a list of `coreapi.Field` instances for the schema,
|
||||
plus an optional description.
|
||||
|
||||
class MyView(APIView):
|
||||
schema = ManualSchema(fields=[
|
||||
coreapi.Field(
|
||||
"first_field",
|
||||
required=True,
|
||||
location="path",
|
||||
schema=coreschema.String()
|
||||
),
|
||||
coreapi.Field(
|
||||
"second_field",
|
||||
required=True,
|
||||
location="path",
|
||||
schema=coreschema.String()
|
||||
),
|
||||
]
|
||||
)
|
||||
|
||||
The `ManualSchema` constructor takes two arguments:
|
||||
|
||||
**`fields`**: A list of `coreapi.Field` instances. Required.
|
||||
|
||||
**`description`**: A string description. Optional.
|
||||
|
||||
**`encoding`**: Default `None`. A string encoding, e.g `application/json`. Optional.
|
||||
|
||||
---
|
||||
|
||||
## Core API
|
||||
|
||||
This documentation gives a brief overview of the components within the `coreapi`
|
||||
package that are used to represent an API schema.
|
||||
|
||||
Note that these classes are imported from the `coreapi` package, rather than
|
||||
from the `rest_framework` package.
|
||||
|
||||
### Document
|
||||
|
||||
Represents a container for the API schema.
|
||||
|
||||
#### `title`
|
||||
|
||||
A name for the API.
|
||||
|
||||
#### `url`
|
||||
|
||||
A canonical URL for the API.
|
||||
|
||||
#### `content`
|
||||
|
||||
A dictionary, containing the `Link` objects that the schema contains.
|
||||
|
||||
In order to provide more structure to the schema, the `content` dictionary
|
||||
may be nested, typically to a second level. For example:
|
||||
|
||||
content={
|
||||
"bookings": {
|
||||
"list": Link(...),
|
||||
"create": Link(...),
|
||||
...
|
||||
},
|
||||
"venues": {
|
||||
"list": Link(...),
|
||||
...
|
||||
},
|
||||
...
|
||||
}
|
||||
|
||||
### Link
|
||||
|
||||
Represents an individual API endpoint.
|
||||
|
||||
#### `url`
|
||||
|
||||
The URL of the endpoint. May be a URI template, such as `/users/{username}/`.
|
||||
|
||||
#### `action`
|
||||
|
||||
The HTTP method associated with the endpoint. Note that URLs that support
|
||||
more than one HTTP method, should correspond to a single `Link` for each.
|
||||
|
||||
#### `fields`
|
||||
|
||||
A list of `Field` instances, describing the available parameters on the input.
|
||||
|
||||
#### `description`
|
||||
|
||||
A short description of the meaning and intended usage of the endpoint.
|
||||
|
||||
### Field
|
||||
|
||||
Represents a single input parameter on a given API endpoint.
|
||||
|
||||
#### `name`
|
||||
|
||||
A descriptive name for the input.
|
||||
|
||||
#### `required`
|
||||
|
||||
A boolean, indicated if the client is required to included a value, or if
|
||||
the parameter can be omitted.
|
||||
|
||||
#### `location`
|
||||
|
||||
Determines how the information is encoded into the request. Should be one of
|
||||
the following strings:
|
||||
|
||||
**"path"**
|
||||
|
||||
Included in a templated URI. For example a `url` value of `/products/{product_code}/` could be used together with a `"path"` field, to handle API inputs in a URL path such as `/products/slim-fit-jeans/`.
|
||||
|
||||
These fields will normally correspond with [named arguments in the project URL conf][named-arguments].
|
||||
|
||||
**"query"**
|
||||
|
||||
Included as a URL query parameter. For example `?search=sale`. Typically for `GET` requests.
|
||||
|
||||
These fields will normally correspond with pagination and filtering controls on a view.
|
||||
|
||||
**"form"**
|
||||
|
||||
Included in the request body, as a single item of a JSON object or HTML form. For example `{"colour": "blue", ...}`. Typically for `POST`, `PUT` and `PATCH` requests. Multiple `"form"` fields may be included on a single link.
|
||||
|
||||
These fields will normally correspond with serializer fields on a view.
|
||||
|
||||
**"body"**
|
||||
|
||||
Included as the complete request body. Typically for `POST`, `PUT` and `PATCH` requests. No more than one `"body"` field may exist on a link. May not be used together with `"form"` fields.
|
||||
|
||||
These fields will normally correspond with views that use `ListSerializer` to validate the request input, or with file upload views.
|
||||
|
||||
#### `encoding`
|
||||
|
||||
**"application/json"**
|
||||
|
||||
JSON encoded request content. Corresponds to views using `JSONParser`.
|
||||
Valid only if either one or more `location="form"` fields, or a single
|
||||
`location="body"` field is included on the `Link`.
|
||||
|
||||
**"multipart/form-data"**
|
||||
|
||||
Multipart encoded request content. Corresponds to views using `MultiPartParser`.
|
||||
Valid only if one or more `location="form"` fields is included on the `Link`.
|
||||
|
||||
**"application/x-www-form-urlencoded"**
|
||||
|
||||
URL encoded request content. Corresponds to views using `FormParser`. Valid
|
||||
only if one or more `location="form"` fields is included on the `Link`.
|
||||
|
||||
**"application/octet-stream"**
|
||||
|
||||
Binary upload request content. Corresponds to views using `FileUploadParser`.
|
||||
Valid only if a `location="body"` field is included on the `Link`.
|
||||
|
||||
#### `description`
|
||||
|
||||
A short description of the meaning and intended usage of the input field.
|
||||
|
||||
|
||||
---
|
||||
|
||||
# Third party packages
|
||||
|
||||
## drf-yasg - Yet Another Swagger Generator
|
||||
|
||||
[drf-yasg][drf-yasg] generates [OpenAPI][open-api] documents suitable for code generation - nested schemas,
|
||||
named models, response bodies, enum/pattern/min/max validators, form parameters, etc.
|
||||
|
||||
|
||||
## drf-spectacular - Sane and flexible OpenAPI 3.0 schema generation for Django REST framework
|
||||
|
||||
[drf-spectacular][drf-spectacular] is a [OpenAPI 3][open-api] schema generation tool with explicit focus on extensibility,
|
||||
customizability and client generation. It's usage patterns are very similar to [drf-yasg][drf-yasg].
|
||||
|
||||
[cite]: https://blog.heroku.com/archives/2014/1/8/json_schema_for_heroku_platform_api
|
||||
[coreapi]: https://www.coreapi.org/
|
||||
[corejson]: https://www.coreapi.org/specification/encoding/#core-json-encoding
|
||||
[drf-yasg]: https://github.com/axnsan12/drf-yasg/
|
||||
[drf-spectacular]: https://github.com/tfranzel/drf-spectacular/
|
||||
[open-api]: https://openapis.org/
|
||||
[json-hyperschema]: https://json-schema.org/latest/json-schema-hypermedia.html
|
||||
[api-blueprint]: https://apiblueprint.org/
|
||||
[static-files]: https://docs.djangoproject.com/en/stable/howto/static-files/
|
||||
[named-arguments]: https://docs.djangoproject.com/en/stable/topics/http/urls/#named-groups
|
Before Width: | Height: | Size: 18 KiB After Width: | Height: | Size: 18 KiB |
BIN
docs/img/premium/cryptapi-readme.png
Normal file
After Width: | Height: | Size: 17 KiB |
BIN
docs/img/premium/fezto-readme.png
Normal file
After Width: | Height: | Size: 22 KiB |
BIN
docs/img/premium/posthog-readme.png
Normal file
After Width: | Height: | Size: 4.8 KiB |
Before Width: | Height: | Size: 8.8 KiB After Width: | Height: | Size: 8.7 KiB |
Before Width: | Height: | Size: 24 KiB After Width: | Height: | Size: 24 KiB |
BIN
docs/img/premium/spacinov-readme.png
Normal file
After Width: | Height: | Size: 56 KiB |
Before Width: | Height: | Size: 19 KiB After Width: | Height: | Size: 19 KiB |
Before Width: | Height: | Size: 38 KiB After Width: | Height: | Size: 27 KiB |
|
@ -67,15 +67,17 @@ continued development by **[signing up for a paid plan][funding]**.
|
|||
|
||||
<ul class="premium-promo promo">
|
||||
<li><a href="https://getsentry.com/welcome/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/sentry130.png)">Sentry</a></li>
|
||||
<li><a href="https://getstream.io/try-the-api/?utm_source=drf&utm_medium=banner&utm_campaign=drf" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/stream-130.png)">Stream</a></li>
|
||||
<li><a href="https://software.esg-usa.com" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/esg-new-logo.png)">ESG</a></li>
|
||||
<li><a href="https://rollbar.com" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/rollbar2.png)">Rollbar</a></li>
|
||||
<li><a href="https://getstream.io/?utm_source=DjangoRESTFramework&utm_medium=Webpage_Logo_Ad&utm_content=Developer&utm_campaign=DjangoRESTFramework_Jan2022_HomePage" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/stream-130.png)">Stream</a></li>
|
||||
<li><a href="https://www.spacinov.com/" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/spacinov.png)">Spacinov</a></li>
|
||||
<li><a href="https://retool.com/?utm_source=djangorest&utm_medium=sponsorship" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/retool-sidebar.png)">Retool</a></li>
|
||||
<li><a href="https://bit.io/jobs?utm_source=DRF&utm_medium=sponsor&utm_campaign=DRF_sponsorship" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/bitio_logo_gold_background.png)">bit.io</a></li>
|
||||
<li><a href="https://posthog.com?utm_source=DRF&utm_medium=sponsor&utm_campaign=DRF_sponsorship" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/135996800-d49fe024-32d9-441a-98d9-4c7596287a67.png)">PostHog</a></li>
|
||||
<li><a href="https://cryptapi.io" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/cryptapi.png)">CryptAPI</a></li>
|
||||
<li><a href="https://www.fezto.xyz/?utm_source=DjangoRESTFramework" style="background-image: url(https://fund-rest-framework.s3.amazonaws.com/fezto.png)">FEZTO</a></li>
|
||||
</ul>
|
||||
<div style="clear: both; padding-bottom: 20px;"></div>
|
||||
|
||||
*Many thanks to all our [wonderful sponsors][sponsors], and in particular to our premium backers, [Sentry](https://getsentry.com/welcome/), [Stream](https://getstream.io/?utm_source=drf&utm_medium=banner&utm_campaign=drf), [ESG](https://software.esg-usa.com/), [Rollbar](https://rollbar.com/?utm_source=django&utm_medium=sponsorship&utm_campaign=freetrial), [Cadre](https://cadre.com), [Kloudless](https://hubs.ly/H0f30Lf0), [Lights On Software](https://lightsonsoftware.com), [Retool](https://retool.com/?utm_source=djangorest&utm_medium=sponsorship), and [bit.io](https://bit.io/jobs?utm_source=DRF&utm_medium=sponsor&utm_campaign=DRF_sponsorship).*
|
||||
*Many thanks to all our [wonderful sponsors][sponsors], and in particular to our premium backers, [Sentry](https://getsentry.com/welcome/), [Stream](https://getstream.io/?utm_source=DjangoRESTFramework&utm_medium=Webpage_Logo_Ad&utm_content=Developer&utm_campaign=DjangoRESTFramework_Jan2022_HomePage), [Spacinov](https://www.spacinov.com/), [Retool](https://retool.com/?utm_source=djangorest&utm_medium=sponsorship), [bit.io](https://bit.io/jobs?utm_source=DRF&utm_medium=sponsor&utm_campaign=DRF_sponsorship), [PostHog](https://posthog.com?utm_source=DRF&utm_medium=sponsor&utm_campaign=DRF_sponsorship), [CryptAPI](https://cryptapi.io), and [FEZTO](https://www.fezto.xyz/?utm_source=DjangoRESTFramework).*
|
||||
|
||||
---
|
||||
|
||||
|
@ -83,8 +85,8 @@ continued development by **[signing up for a paid plan][funding]**.
|
|||
|
||||
REST framework requires the following:
|
||||
|
||||
* Python (3.5, 3.6, 3.7, 3.8, 3.9)
|
||||
* Django (2.2, 3.0, 3.1)
|
||||
* Python (3.6, 3.7, 3.8, 3.9, 3.10, 3.11)
|
||||
* Django (2.2, 3.0, 3.1, 3.2, 4.0, 4.1)
|
||||
|
||||
We **highly recommend** and only officially support the latest patch release of
|
||||
each Python and Django series.
|
||||
|
@ -186,15 +188,17 @@ Framework.
|
|||
|
||||
## Support
|
||||
|
||||
For support please see the [REST framework discussion group][group], try the `#restframework` channel on `irc.freenode.net`, search [the IRC archives][botbot], or raise a question on [Stack Overflow][stack-overflow], making sure to include the ['django-rest-framework'][django-rest-framework-tag] tag.
|
||||
For support please see the [REST framework discussion group][group], try the `#restframework` channel on `irc.libera.chat`, or raise a question on [Stack Overflow][stack-overflow], making sure to include the ['django-rest-framework'][django-rest-framework-tag] tag.
|
||||
|
||||
For priority support please sign up for a [professional or premium sponsorship plan](https://fund.django-rest-framework.org/topics/funding/).
|
||||
|
||||
## Security
|
||||
|
||||
If you believe you’ve found something in Django REST framework which has security implications, please **do not raise the issue in a public forum**.
|
||||
Security issues are handled under the supervision of the [Django security team](https://www.djangoproject.com/foundation/teams/#security-team).
|
||||
|
||||
Send a description of the issue via email to [rest-framework-security@googlegroups.com][security-mail]. The project maintainers will then work with you to resolve any issues where required, prior to any public disclosure.
|
||||
**Please report security issues by emailing security@djangoproject.com**.
|
||||
|
||||
The project maintainers will then work with you to resolve any issues where required, prior to any public disclosure.
|
||||
|
||||
## License
|
||||
|
||||
|
@ -257,7 +261,6 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|||
[funding]: community/funding.md
|
||||
|
||||
[group]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework
|
||||
[botbot]: https://botbot.me/freenode/restframework/
|
||||
[stack-overflow]: https://stackoverflow.com/
|
||||
[django-rest-framework-tag]: https://stackoverflow.com/questions/tagged/django-rest-framework
|
||||
[security-mail]: mailto:rest-framework-security@googlegroups.com
|
||||
|
|
|
@ -2,7 +2,7 @@
|
|||
|
||||
> "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]
|
||||
> — [Jeff Atwood][cite]
|
||||
|
||||
## Javascript clients
|
||||
|
||||
|
@ -31,11 +31,11 @@ In order to make AJAX requests, you need to include CSRF token in the HTTP heade
|
|||
|
||||
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.
|
||||
[Adam Johnson][adamchainz] maintains the [django-cors-headers] package, which is known to work correctly with REST framework APIs.
|
||||
|
||||
[cite]: https://blog.codinghorror.com/preventing-csrf-and-xsrf-attacks/
|
||||
[csrf]: https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)
|
||||
[csrf-ajax]: https://docs.djangoproject.com/en/stable/ref/csrf/#ajax
|
||||
[cors]: https://www.w3.org/TR/cors/
|
||||
[ottoyiu]: https://github.com/ottoyiu/
|
||||
[django-cors-headers]: https://github.com/ottoyiu/django-cors-headers/
|
||||
[adamchainz]: https://github.com/adamchainz
|
||||
[django-cors-headers]: https://github.com/adamchainz/django-cors-headers
|
||||
|
|
|
@ -1,527 +0,0 @@
|
|||
# API Clients
|
||||
|
||||
An API client handles the underlying details of how network requests are made
|
||||
and how responses are decoded. They present the developer with an application
|
||||
interface to work against, rather than working directly with the network interface.
|
||||
|
||||
The API clients documented here are not restricted to APIs built with Django REST framework.
|
||||
They can be used with any API that exposes a supported schema format.
|
||||
|
||||
For example, [the Heroku platform API][heroku-api] exposes a schema in the JSON
|
||||
Hyperschema format. As a result, the Core API command line client and Python
|
||||
client library can be [used to interact with the Heroku API][heroku-example].
|
||||
|
||||
## Client-side Core API
|
||||
|
||||
[Core API][core-api] is a document specification that can be used to describe APIs. It can
|
||||
be used either server-side, as is done with REST framework's [schema generation][schema-generation],
|
||||
or used client-side, as described here.
|
||||
|
||||
When used client-side, Core API allows for *dynamically driven client libraries*
|
||||
that can interact with any API that exposes a supported schema or hypermedia
|
||||
format.
|
||||
|
||||
Using a dynamically driven client has a number of advantages over interacting
|
||||
with an API by building HTTP requests directly.
|
||||
|
||||
#### More meaningful interaction
|
||||
|
||||
API interactions are presented in a more meaningful way. You're working at
|
||||
the application interface layer, rather than the network interface layer.
|
||||
|
||||
#### Resilience & evolvability
|
||||
|
||||
The client determines what endpoints are available, what parameters exist
|
||||
against each particular endpoint, and how HTTP requests are formed.
|
||||
|
||||
This also allows for a degree of API evolvability. URLs can be modified
|
||||
without breaking existing clients, or more efficient encodings can be used
|
||||
on-the-wire, with clients transparently upgrading.
|
||||
|
||||
#### Self-descriptive APIs
|
||||
|
||||
A dynamically driven client is able to present documentation on the API to the
|
||||
end user. This documentation allows the user to discover the available endpoints
|
||||
and parameters, and better understand the API they are working with.
|
||||
|
||||
Because this documentation is driven by the API schema it will always be fully
|
||||
up to date with the most recently deployed version of the service.
|
||||
|
||||
---
|
||||
|
||||
# Command line client
|
||||
|
||||
The command line client allows you to inspect and interact with any API that
|
||||
exposes a supported schema format.
|
||||
|
||||
## Getting started
|
||||
|
||||
To install the Core API command line client, use `pip`.
|
||||
|
||||
Note that the command-line client is a separate package to the
|
||||
python client library. Make sure to install `coreapi-cli`.
|
||||
|
||||
$ pip install coreapi-cli
|
||||
|
||||
To start inspecting and interacting with an API the schema must first be loaded
|
||||
from the network.
|
||||
|
||||
$ coreapi get http://api.example.org/
|
||||
<Pastebin API "http://127.0.0.1:8000/">
|
||||
snippets: {
|
||||
create(code, [title], [linenos], [language], [style])
|
||||
destroy(pk)
|
||||
highlight(pk)
|
||||
list([page])
|
||||
partial_update(pk, [title], [code], [linenos], [language], [style])
|
||||
retrieve(pk)
|
||||
update(pk, code, [title], [linenos], [language], [style])
|
||||
}
|
||||
users: {
|
||||
list([page])
|
||||
retrieve(pk)
|
||||
}
|
||||
|
||||
This will then load the schema, displaying the resulting `Document`. This
|
||||
`Document` includes all the available interactions that may be made against the API.
|
||||
|
||||
To interact with the API, use the `action` command. This command requires a list
|
||||
of keys that are used to index into the link.
|
||||
|
||||
$ coreapi action users list
|
||||
[
|
||||
{
|
||||
"url": "http://127.0.0.1:8000/users/2/",
|
||||
"id": 2,
|
||||
"username": "aziz",
|
||||
"snippets": []
|
||||
},
|
||||
...
|
||||
]
|
||||
|
||||
To inspect the underlying HTTP request and response, use the `--debug` flag.
|
||||
|
||||
$ coreapi action users list --debug
|
||||
> GET /users/ HTTP/1.1
|
||||
> Accept: application/vnd.coreapi+json, */*
|
||||
> Authorization: Basic bWF4Om1heA==
|
||||
> Host: 127.0.0.1
|
||||
> User-Agent: coreapi
|
||||
< 200 OK
|
||||
< Allow: GET, HEAD, OPTIONS
|
||||
< Content-Type: application/json
|
||||
< Date: Thu, 30 Jun 2016 10:51:46 GMT
|
||||
< Server: WSGIServer/0.1 Python/2.7.10
|
||||
< Vary: Accept, Cookie
|
||||
<
|
||||
< [{"url":"http://127.0.0.1/users/2/","id":2,"username":"aziz","snippets":[]},{"url":"http://127.0.0.1/users/3/","id":3,"username":"amy","snippets":["http://127.0.0.1/snippets/3/"]},{"url":"http://127.0.0.1/users/4/","id":4,"username":"max","snippets":["http://127.0.0.1/snippets/4/","http://127.0.0.1/snippets/5/","http://127.0.0.1/snippets/6/","http://127.0.0.1/snippets/7/"]},{"url":"http://127.0.0.1/users/5/","id":5,"username":"jose","snippets":[]},{"url":"http://127.0.0.1/users/6/","id":6,"username":"admin","snippets":["http://127.0.0.1/snippets/1/","http://127.0.0.1/snippets/2/"]}]
|
||||
|
||||
[
|
||||
...
|
||||
]
|
||||
|
||||
Some actions may include optional or required parameters.
|
||||
|
||||
$ coreapi action users create --param username=example
|
||||
|
||||
When using `--param`, the type of the input will be determined automatically.
|
||||
|
||||
If you want to be more explicit about the parameter type then use `--data` for
|
||||
any null, numeric, boolean, list, or object inputs, and use `--string` for string inputs.
|
||||
|
||||
$ coreapi action users edit --string username=tomchristie --data is_admin=true
|
||||
|
||||
## Authentication & headers
|
||||
|
||||
The `credentials` command is used to manage the request `Authentication:` header.
|
||||
Any credentials added are always linked to a particular domain, so as to ensure
|
||||
that credentials are not leaked across differing APIs.
|
||||
|
||||
The format for adding a new credential is:
|
||||
|
||||
$ coreapi credentials add <domain> <credentials string>
|
||||
|
||||
For instance:
|
||||
|
||||
$ coreapi credentials add api.example.org "Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b"
|
||||
|
||||
The optional `--auth` flag also allows you to add specific types of authentication,
|
||||
handling the encoding for you. Currently only `"basic"` is supported as an option here.
|
||||
For example:
|
||||
|
||||
$ coreapi credentials add api.example.org tomchristie:foobar --auth basic
|
||||
|
||||
You can also add specific request headers, using the `headers` command:
|
||||
|
||||
$ coreapi headers add api.example.org x-api-version 2
|
||||
|
||||
For more information and a listing of the available subcommands use `coreapi
|
||||
credentials --help` or `coreapi headers --help`.
|
||||
|
||||
## Codecs
|
||||
|
||||
By default the command line client only includes support for reading Core JSON
|
||||
schemas, however it includes a plugin system for installing additional codecs.
|
||||
|
||||
$ pip install openapi-codec jsonhyperschema-codec hal-codec
|
||||
$ coreapi codecs show
|
||||
Codecs
|
||||
corejson application/vnd.coreapi+json encoding, decoding
|
||||
hal application/hal+json encoding, decoding
|
||||
openapi application/openapi+json encoding, decoding
|
||||
jsonhyperschema application/schema+json decoding
|
||||
json application/json data
|
||||
text text/* data
|
||||
|
||||
## Utilities
|
||||
|
||||
The command line client includes functionality for bookmarking API URLs
|
||||
under a memorable name. For example, you can add a bookmark for the
|
||||
existing API, like so...
|
||||
|
||||
$ coreapi bookmarks add accountmanagement
|
||||
|
||||
There is also functionality for navigating forward or backward through the
|
||||
history of which API URLs have been accessed.
|
||||
|
||||
$ coreapi history show
|
||||
$ coreapi history back
|
||||
|
||||
For more information and a listing of the available subcommands use
|
||||
`coreapi bookmarks --help` or `coreapi history --help`.
|
||||
|
||||
## Other commands
|
||||
|
||||
To display the current `Document`:
|
||||
|
||||
$ coreapi show
|
||||
|
||||
To reload the current `Document` from the network:
|
||||
|
||||
$ coreapi reload
|
||||
|
||||
To load a schema file from disk:
|
||||
|
||||
$ coreapi load my-api-schema.json --format corejson
|
||||
|
||||
To dump the current document to console in a given format:
|
||||
|
||||
$ coreapi dump --format openapi
|
||||
|
||||
To remove the current document, along with all currently saved history,
|
||||
credentials, headers and bookmarks:
|
||||
|
||||
$ coreapi clear
|
||||
|
||||
---
|
||||
|
||||
# Python client library
|
||||
|
||||
The `coreapi` Python package allows you to programmatically interact with any
|
||||
API that exposes a supported schema format.
|
||||
|
||||
## Getting started
|
||||
|
||||
You'll need to install the `coreapi` package using `pip` before you can get
|
||||
started.
|
||||
|
||||
$ pip install coreapi
|
||||
|
||||
In order to start working with an API, we first need a `Client` instance. The
|
||||
client holds any configuration around which codecs and transports are supported
|
||||
when interacting with an API, which allows you to provide for more advanced
|
||||
kinds of behaviour.
|
||||
|
||||
import coreapi
|
||||
client = coreapi.Client()
|
||||
|
||||
Once we have a `Client` instance, we can fetch an API schema from the network.
|
||||
|
||||
schema = client.get('https://api.example.org/')
|
||||
|
||||
The object returned from this call will be a `Document` instance, which is
|
||||
a representation of the API schema.
|
||||
|
||||
## Authentication
|
||||
|
||||
Typically you'll also want to provide some authentication credentials when
|
||||
instantiating the client.
|
||||
|
||||
#### Token authentication
|
||||
|
||||
The `TokenAuthentication` class can be used to support REST framework's built-in
|
||||
`TokenAuthentication`, as well as OAuth and JWT schemes.
|
||||
|
||||
auth = coreapi.auth.TokenAuthentication(
|
||||
scheme='JWT',
|
||||
token='<token>'
|
||||
)
|
||||
client = coreapi.Client(auth=auth)
|
||||
|
||||
When using TokenAuthentication you'll probably need to implement a login flow
|
||||
using the CoreAPI client.
|
||||
|
||||
A suggested pattern for this would be to initially make an unauthenticated client
|
||||
request to an "obtain token" endpoint
|
||||
|
||||
For example, using the "Django REST framework JWT" package
|
||||
|
||||
client = coreapi.Client()
|
||||
schema = client.get('https://api.example.org/')
|
||||
|
||||
action = ['api-token-auth', 'create']
|
||||
params = {"username": "example", "password": "secret"}
|
||||
result = client.action(schema, action, params)
|
||||
|
||||
auth = coreapi.auth.TokenAuthentication(
|
||||
scheme='JWT',
|
||||
token=result['token']
|
||||
)
|
||||
client = coreapi.Client(auth=auth)
|
||||
|
||||
#### Basic authentication
|
||||
|
||||
The `BasicAuthentication` class can be used to support HTTP Basic Authentication.
|
||||
|
||||
auth = coreapi.auth.BasicAuthentication(
|
||||
username='<username>',
|
||||
password='<password>'
|
||||
)
|
||||
client = coreapi.Client(auth=auth)
|
||||
|
||||
## Interacting with the API
|
||||
|
||||
Now that we have a client and have fetched our schema `Document`, we can now
|
||||
start to interact with the API:
|
||||
|
||||
users = client.action(schema, ['users', 'list'])
|
||||
|
||||
Some endpoints may include named parameters, which might be either optional or required:
|
||||
|
||||
new_user = client.action(schema, ['users', 'create'], params={"username": "max"})
|
||||
|
||||
## Codecs
|
||||
|
||||
Codecs are responsible for encoding or decoding Documents.
|
||||
|
||||
The decoding process is used by a client to take a bytestring of an API schema
|
||||
definition, and returning the Core API `Document` that represents that interface.
|
||||
|
||||
A codec should be associated with a particular media type, such as `'application/coreapi+json'`.
|
||||
|
||||
This media type is used by the server in the response `Content-Type` header,
|
||||
in order to indicate what kind of data is being returned in the response.
|
||||
|
||||
#### Configuring codecs
|
||||
|
||||
The codecs that are available can be configured when instantiating a client.
|
||||
The keyword argument used here is `decoders`, because in the context of a
|
||||
client the codecs are only for *decoding* responses.
|
||||
|
||||
In the following example we'll configure a client to only accept `Core JSON`
|
||||
and `JSON` responses. This will allow us to receive and decode a Core JSON schema,
|
||||
and subsequently to receive JSON responses made against the API.
|
||||
|
||||
from coreapi import codecs, Client
|
||||
|
||||
decoders = [codecs.CoreJSONCodec(), codecs.JSONCodec()]
|
||||
client = Client(decoders=decoders)
|
||||
|
||||
#### Loading and saving schemas
|
||||
|
||||
You can use a codec directly, in order to load an existing schema definition,
|
||||
and return the resulting `Document`.
|
||||
|
||||
input_file = open('my-api-schema.json', 'rb')
|
||||
schema_definition = input_file.read()
|
||||
codec = codecs.CoreJSONCodec()
|
||||
schema = codec.load(schema_definition)
|
||||
|
||||
You can also use a codec directly to generate a schema definition given a `Document` instance:
|
||||
|
||||
schema_definition = codec.dump(schema)
|
||||
output_file = open('my-api-schema.json', 'rb')
|
||||
output_file.write(schema_definition)
|
||||
|
||||
## Transports
|
||||
|
||||
Transports are responsible for making network requests. The set of transports
|
||||
that a client has installed determines which network protocols it is able to
|
||||
support.
|
||||
|
||||
Currently the `coreapi` library only includes an HTTP/HTTPS transport, but
|
||||
other protocols can also be supported.
|
||||
|
||||
#### Configuring transports
|
||||
|
||||
The behavior of the network layer can be customized by configuring the
|
||||
transports that the client is instantiated with.
|
||||
|
||||
import requests
|
||||
from coreapi import transports, Client
|
||||
|
||||
credentials = {'api.example.org': 'Token 3bd44a009d16ff'}
|
||||
transports = transports.HTTPTransport(credentials=credentials)
|
||||
client = Client(transports=transports)
|
||||
|
||||
More complex customizations can also be achieved, for example modifying the
|
||||
underlying `requests.Session` instance to [attach transport adaptors][transport-adaptors]
|
||||
that modify the outgoing requests.
|
||||
|
||||
---
|
||||
|
||||
# JavaScript Client Library
|
||||
|
||||
The JavaScript client library allows you to interact with your API either from a browser, or using node.
|
||||
|
||||
## Installing the JavaScript client
|
||||
|
||||
There are two separate JavaScript resources that you need to include in your HTML pages in order to use the JavaScript client library. These are a static `coreapi.js` file, which contains the code for the dynamic client library, and a templated `schema.js` resource, which exposes your API schema.
|
||||
|
||||
First, install the API documentation views. These will include the schema resource that'll allow you to load the schema directly from an HTML page, without having to make an asynchronous AJAX call.
|
||||
|
||||
from rest_framework.documentation import include_docs_urls
|
||||
|
||||
urlpatterns = [
|
||||
...
|
||||
path('docs/', include_docs_urls(title='My API service'), name='api-docs'),
|
||||
]
|
||||
|
||||
Once the API documentation URLs are installed, you'll be able to include both the required JavaScript resources. Note that the ordering of these two lines is important, as the schema loading requires CoreAPI to already be installed.
|
||||
|
||||
<!--
|
||||
Load the CoreAPI library and the API schema.
|
||||
|
||||
/static/rest_framework/js/coreapi-0.1.1.js
|
||||
/docs/schema.js
|
||||
-->
|
||||
{% load static %}
|
||||
<script src="{% static 'rest_framework/js/coreapi-0.1.1.js' %}"></script>
|
||||
<script src="{% url 'api-docs:schema-js' %}"></script>
|
||||
|
||||
The `coreapi` library, and the `schema` object will now both be available on the `window` instance.
|
||||
|
||||
const coreapi = window.coreapi;
|
||||
const schema = window.schema;
|
||||
|
||||
## Instantiating a client
|
||||
|
||||
In order to interact with the API you'll need a client instance.
|
||||
|
||||
var client = new coreapi.Client();
|
||||
|
||||
Typically you'll also want to provide some authentication credentials when
|
||||
instantiating the client.
|
||||
|
||||
#### Session authentication
|
||||
|
||||
The `SessionAuthentication` class allows session cookies to provide the user
|
||||
authentication. You'll want to provide a standard HTML login flow, to allow
|
||||
the user to login, and then instantiate a client using session authentication:
|
||||
|
||||
let auth = new coreapi.auth.SessionAuthentication({
|
||||
csrfCookieName: 'csrftoken',
|
||||
csrfHeaderName: 'X-CSRFToken',
|
||||
});
|
||||
let client = new coreapi.Client({auth: auth});
|
||||
|
||||
The authentication scheme will handle including a CSRF header in any outgoing
|
||||
requests for unsafe HTTP methods.
|
||||
|
||||
#### Token authentication
|
||||
|
||||
The `TokenAuthentication` class can be used to support REST framework's built-in
|
||||
`TokenAuthentication`, as well as OAuth and JWT schemes.
|
||||
|
||||
let auth = new coreapi.auth.TokenAuthentication({
|
||||
scheme: 'JWT',
|
||||
token: '<token>',
|
||||
});
|
||||
let client = new coreapi.Client({auth: auth});
|
||||
|
||||
When using TokenAuthentication you'll probably need to implement a login flow
|
||||
using the CoreAPI client.
|
||||
|
||||
A suggested pattern for this would be to initially make an unauthenticated client
|
||||
request to an "obtain token" endpoint
|
||||
|
||||
For example, using the "Django REST framework JWT" package
|
||||
|
||||
// Setup some globally accessible state
|
||||
window.client = new coreapi.Client();
|
||||
window.loggedIn = false;
|
||||
|
||||
function loginUser(username, password) {
|
||||
let action = ["api-token-auth", "obtain-token"];
|
||||
let params = {username: username, password: password};
|
||||
client.action(schema, action, params).then(function(result) {
|
||||
// On success, instantiate an authenticated client.
|
||||
let auth = window.coreapi.auth.TokenAuthentication({
|
||||
scheme: 'JWT',
|
||||
token: result['token'],
|
||||
})
|
||||
window.client = coreapi.Client({auth: auth});
|
||||
window.loggedIn = true;
|
||||
}).catch(function (error) {
|
||||
// Handle error case where eg. user provides incorrect credentials.
|
||||
})
|
||||
}
|
||||
|
||||
#### Basic authentication
|
||||
|
||||
The `BasicAuthentication` class can be used to support HTTP Basic Authentication.
|
||||
|
||||
let auth = new coreapi.auth.BasicAuthentication({
|
||||
username: '<username>',
|
||||
password: '<password>',
|
||||
})
|
||||
let client = new coreapi.Client({auth: auth});
|
||||
|
||||
## Using the client
|
||||
|
||||
Making requests:
|
||||
|
||||
let action = ["users", "list"];
|
||||
client.action(schema, action).then(function(result) {
|
||||
// Return value is in 'result'
|
||||
})
|
||||
|
||||
Including parameters:
|
||||
|
||||
let action = ["users", "create"];
|
||||
let params = {username: "example", email: "example@example.com"};
|
||||
client.action(schema, action, params).then(function(result) {
|
||||
// Return value is in 'result'
|
||||
})
|
||||
|
||||
Handling errors:
|
||||
|
||||
client.action(schema, action, params).then(function(result) {
|
||||
// Return value is in 'result'
|
||||
}).catch(function (error) {
|
||||
// Error value is in 'error'
|
||||
})
|
||||
|
||||
## Installation with node
|
||||
|
||||
The coreapi package is available on NPM.
|
||||
|
||||
$ npm install coreapi
|
||||
$ node
|
||||
const coreapi = require('coreapi')
|
||||
|
||||
You'll either want to include the API schema in your codebase directly, by copying it from the `schema.js` resource, or else load the schema asynchronously. For example:
|
||||
|
||||
let client = new coreapi.Client();
|
||||
let schema = null;
|
||||
client.get("https://api.example.org/").then(function(data) {
|
||||
// Load a CoreJSON API schema.
|
||||
schema = data;
|
||||
console.log('schema loaded');
|
||||
})
|
||||
|
||||
[heroku-api]: https://devcenter.heroku.com/categories/platform-api
|
||||
[heroku-example]: https://www.coreapi.org/tools-and-resources/example-services/#heroku-json-hyper-schema
|
||||
[core-api]: https://www.coreapi.org/
|
||||
[schema-generation]: ../api-guide/schemas.md
|
||||
[transport-adaptors]: http://docs.python-requests.org/en/master/user/advanced/#transport-adapters
|
|
@ -17,7 +17,7 @@ By default, the API will return the format specified by the headers, which in th
|
|||
|
||||
## Customizing
|
||||
|
||||
The browsable API is built with [Twitter's Bootstrap][bootstrap] (v 3.3.5), making it easy to customize the look-and-feel.
|
||||
The browsable API is built with [Twitter's Bootstrap][bootstrap] (v 3.4.1), making it easy to customize the look-and-feel.
|
||||
|
||||
To customize the default style, create a template called `rest_framework/api.html` that extends from `rest_framework/base.html`. For example:
|
||||
|
||||
|
@ -35,7 +35,7 @@ To replace the default theme, add a `bootstrap_theme` block to your `api.html` a
|
|||
<link rel="stylesheet" href="/path/to/my/bootstrap.css" type="text/css">
|
||||
{% endblock %}
|
||||
|
||||
Suitable pre-made replacement themes are 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.
|
||||
Suitable pre-made replacement themes are 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. Make sure that the Bootstrap version of the new theme matches that of the default theme.
|
||||
|
||||
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.
|
||||
|
||||
|
@ -44,7 +44,7 @@ Full example:
|
|||
{% extends "rest_framework/base.html" %}
|
||||
|
||||
{% block bootstrap_theme %}
|
||||
<link rel="stylesheet" href="https://bootswatch.com/flatly/bootstrap.min.css" type="text/css">
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootswatch@3.4.1/flatly/bootstrap.min.css" type="text/css">
|
||||
{% endblock %}
|
||||
|
||||
{% block bootstrap_navbar_variant %}{% endblock %}
|
||||
|
|
|
@ -4,12 +4,42 @@
|
|||
>
|
||||
> — Roy Fielding, [REST APIs must be hypertext driven][cite]
|
||||
|
||||
REST framework provides built-in support for generating OpenAPI schemas, which
|
||||
can be used with tools that allow you to build API documentation.
|
||||
REST framework provides a range of different choices for documenting your API. The following
|
||||
is a non-exhaustive list of the most popular ones.
|
||||
|
||||
There are also a number of great third-party documentation packages available.
|
||||
## Third party packages for OpenAPI support
|
||||
|
||||
## Generating documentation from OpenAPI schemas
|
||||
### drf-spectacular
|
||||
|
||||
[drf-spectacular][drf-spectacular] is an [OpenAPI 3][open-api] schema generation library with explicit
|
||||
focus on extensibility, customizability and client generation. It is the recommended way for
|
||||
generating and presenting OpenAPI schemas.
|
||||
|
||||
The library aims to extract as much schema information as possible, while providing decorators and extensions for easy
|
||||
customization. There is explicit support for [swagger-codegen][swagger], [SwaggerUI][swagger-ui] and [Redoc][redoc],
|
||||
i18n, versioning, authentication, polymorphism (dynamic requests and responses), query/path/header parameters,
|
||||
documentation and more. Several popular plugins for DRF are supported out-of-the-box as well.
|
||||
|
||||
### drf-yasg
|
||||
|
||||
[drf-yasg][drf-yasg] is a [Swagger / OpenAPI 2][swagger] generation tool implemented without using the schema generation provided
|
||||
by Django Rest Framework.
|
||||
|
||||
It aims to implement as much of the [OpenAPI 2][open-api] specification as possible - nested schemas, named models,
|
||||
response bodies, enum/pattern/min/max validators, form parameters, etc. - and to generate documents usable with code
|
||||
generation tools like `swagger-codegen`.
|
||||
|
||||
This also translates into a very useful interactive documentation viewer in the form of `swagger-ui`:
|
||||
|
||||
![Screenshot - drf-yasg][image-drf-yasg]
|
||||
|
||||
---
|
||||
|
||||
## Built-in OpenAPI schema generation (deprecated)
|
||||
|
||||
**Deprecation notice: REST framework's built-in support for generating OpenAPI schemas is
|
||||
deprecated in favor of 3rd party packages that can provide this functionality instead.
|
||||
As replacement, we recommend using the [drf-spectacular](#drf-spectacular) package.**
|
||||
|
||||
There are a number of packages available that allow you to generate HTML
|
||||
documentation pages from OpenAPI schemas.
|
||||
|
@ -124,35 +154,6 @@ urlpatterns = [
|
|||
|
||||
See the [ReDoc documentation][redoc] for advanced usage.
|
||||
|
||||
## Third party packages
|
||||
|
||||
There are a number of mature third-party packages for providing API documentation.
|
||||
|
||||
#### drf-yasg - Yet Another Swagger Generator
|
||||
|
||||
[drf-yasg][drf-yasg] is a [Swagger][swagger] generation tool implemented without using the schema generation provided
|
||||
by Django Rest Framework.
|
||||
|
||||
It aims to implement as much of the [OpenAPI][open-api] specification as possible - nested schemas, named models,
|
||||
response bodies, enum/pattern/min/max validators, form parameters, etc. - and to generate documents usable with code
|
||||
generation tools like `swagger-codegen`.
|
||||
|
||||
This also translates into a very useful interactive documentation viewer in the form of `swagger-ui`:
|
||||
|
||||
|
||||
![Screenshot - drf-yasg][image-drf-yasg]
|
||||
|
||||
#### drf-spectacular - Sane and flexible OpenAPI 3.0 schema generation for Django REST framework
|
||||
|
||||
[drf-spectacular][drf-spectacular] is a [OpenAPI 3][open-api] schema generation tool with explicit focus on extensibility,
|
||||
customizability and client generation. Usage patterns are very similar to [drf-yasg][drf-yasg].
|
||||
|
||||
It aims to extract as much schema information as possible, while providing decorators and extensions for easy
|
||||
customization. There is explicit support for [swagger-codegen][swagger], [SwaggerUI][swagger-ui] and [Redoc][redoc],
|
||||
i18n, versioning, authentication, polymorphism (dynamic requests and responses), query/path/header parameters,
|
||||
documentation and more. Several popular plugins for DRF are supported out-of-the-box as well.
|
||||
|
||||
---
|
||||
|
||||
## Self describing APIs
|
||||
|
||||
|
|
|
@ -207,14 +207,14 @@ Field templates can also use additional style properties, depending on their typ
|
|||
|
||||
The complete list of `base_template` options and their associated style options is listed below.
|
||||
|
||||
base_template | Valid field types | Additional style options
|
||||
----|----|----
|
||||
input.html | Any string, numeric or date/time field | input_type, placeholder, hide_label, autofocus
|
||||
textarea.html | `CharField` | rows, placeholder, hide_label
|
||||
select.html | `ChoiceField` or relational field types | hide_label
|
||||
radio.html | `ChoiceField` or relational field types | inline, hide_label
|
||||
select_multiple.html | `MultipleChoiceField` or relational fields with `many=True` | hide_label
|
||||
base_template | Valid field types | Additional style options
|
||||
-----------------------|-------------------------------------------------------------|-----------------------------------------------
|
||||
input.html | Any string, numeric or date/time field | input_type, placeholder, hide_label, autofocus
|
||||
textarea.html | `CharField` | rows, placeholder, hide_label
|
||||
select.html | `ChoiceField` or relational field types | hide_label
|
||||
radio.html | `ChoiceField` or relational field types | inline, hide_label
|
||||
select_multiple.html | `MultipleChoiceField` or relational fields with `many=True` | hide_label
|
||||
checkbox_multiple.html | `MultipleChoiceField` or relational fields with `many=True` | inline, hide_label
|
||||
checkbox.html | `BooleanField` | hide_label
|
||||
fieldset.html | Nested serializer | hide_label
|
||||
list_fieldset.html | `ListField` or nested serializer with `many=True` | hide_label
|
||||
checkbox.html | `BooleanField` | hide_label
|
||||
fieldset.html | Nested serializer | hide_label
|
||||
list_fieldset.html | `ListField` or nested serializer with `many=True` | hide_label
|
||||
|
|
|
@ -17,9 +17,9 @@ You can change the default language by using the standard Django `LANGUAGE_CODE`
|
|||
|
||||
LANGUAGE_CODE = "es-es"
|
||||
|
||||
You can turn on per-request language requests by adding `LocalMiddleware` to your `MIDDLEWARE_CLASSES` setting:
|
||||
You can turn on per-request language requests by adding `LocalMiddleware` to your `MIDDLEWARE` setting:
|
||||
|
||||
MIDDLEWARE_CLASSES = [
|
||||
MIDDLEWARE = [
|
||||
...
|
||||
'django.middleware.locale.LocaleMiddleware'
|
||||
]
|
||||
|
@ -90,7 +90,7 @@ If you're only translating custom error messages that exist inside your project
|
|||
|
||||
## How the language is determined
|
||||
|
||||
If you want to allow per-request language preferences you'll need to include `django.middleware.locale.LocaleMiddleware` in your `MIDDLEWARE_CLASSES` setting.
|
||||
If you want to allow per-request language preferences you'll need to include `django.middleware.locale.LocaleMiddleware` in your `MIDDLEWARE` setting.
|
||||
|
||||
You can find more information on how the language preference is determined in the [Django documentation][django-language-preference]. For reference, the method is:
|
||||
|
||||
|
|
|
@ -4,7 +4,7 @@
|
|||
>
|
||||
> — Mike Amundsen, [REST fest 2012 keynote][cite].
|
||||
|
||||
First off, the disclaimer. The name "Django REST framework" was decided back in early 2011 and was chosen simply to sure the project would be easily found by developers. Throughout the documentation we try to use the more simple and technically correct terminology of "Web APIs".
|
||||
First off, the disclaimer. The name "Django REST framework" was decided back in early 2011 and was chosen simply to ensure the project would be easily found by developers. Throughout the documentation we try to use the more simple and technically correct terminology of "Web APIs".
|
||||
|
||||
If you are serious about designing a Hypermedia API, you should look to resources outside of this documentation to help inform your design choices.
|
||||
|
||||
|
|
|
@ -45,7 +45,7 @@ We'll need to add our new `snippets` app and the `rest_framework` app to `INSTAL
|
|||
INSTALLED_APPS = [
|
||||
...
|
||||
'rest_framework',
|
||||
'snippets.apps.SnippetsConfig',
|
||||
'snippets',
|
||||
]
|
||||
|
||||
Okay, we're ready to roll.
|
||||
|
@ -77,7 +77,7 @@ For the purposes of this tutorial we're going to start by creating a simple `Sni
|
|||
We'll also need to create an initial migration for our snippet model, and sync the database for the first time.
|
||||
|
||||
python manage.py makemigrations snippets
|
||||
python manage.py migrate
|
||||
python manage.py migrate snippets
|
||||
|
||||
## Creating a Serializer class
|
||||
|
||||
|
@ -179,7 +179,7 @@ We can also serialize querysets instead of model instances. To do so we simply
|
|||
|
||||
## Using ModelSerializers
|
||||
|
||||
Our `SnippetSerializer` class is replicating a lot of information that's also contained in the `Snippet` model. It would be nice if we could keep our code a bit more concise.
|
||||
Our `SnippetSerializer` class is replicating a lot of information that's also contained in the `Snippet` model. It would be nice if we could keep our code a bit more concise.
|
||||
|
||||
In the same way that Django provides both `Form` classes and `ModelForm` classes, REST framework includes both `Serializer` classes, and `ModelSerializer` classes.
|
||||
|
||||
|
@ -307,8 +307,8 @@ Quit out of the shell...
|
|||
Validating models...
|
||||
|
||||
0 errors found
|
||||
Django version 1.11, using settings 'tutorial.settings'
|
||||
Development server is running at http://127.0.0.1:8000/
|
||||
Django version 4.0, using settings 'tutorial.settings'
|
||||
Starting Development server at http://127.0.0.1:8000/
|
||||
Quit the server with CONTROL-C.
|
||||
|
||||
In another terminal window, we can test the server.
|
||||
|
@ -374,5 +374,5 @@ We'll see how we can start to improve things in [part 2 of the tutorial][tut-2].
|
|||
[sandbox]: https://restframework.herokuapp.com/
|
||||
[venv]: https://docs.python.org/3/library/venv.html
|
||||
[tut-2]: 2-requests-and-responses.md
|
||||
[httpie]: https://github.com/jakubroztocil/httpie#installation
|
||||
[httpie]: https://github.com/httpie/httpie#installation
|
||||
[curl]: https://curl.haxx.se/
|
||||
|
|
|
@ -29,7 +29,7 @@ REST framework provides two wrappers you can use to write API views.
|
|||
|
||||
These wrappers provide a few bits of functionality such as making sure you receive `Request` instances in your view, and adding context to `Response` objects so that content negotiation can be performed.
|
||||
|
||||
The wrappers also provide behaviour such as returning `405 Method Not Allowed` responses when appropriate, and handling any `ParseError` exceptions that occur when accessing `request.data` with malformed input.
|
||||
The wrappers also provide behavior such as returning `405 Method Not Allowed` responses when appropriate, and handling any `ParseError` exceptions that occur when accessing `request.data` with malformed input.
|
||||
|
||||
## Pulling it all together
|
||||
|
||||
|
@ -112,7 +112,7 @@ Now update the `snippets/urls.py` file slightly, to append a set of `format_suff
|
|||
|
||||
urlpatterns = [
|
||||
path('snippets/', views.snippet_list),
|
||||
path('snippets/<int:pk>', views.snippet_detail),
|
||||
path('snippets/<int:pk>/', views.snippet_detail),
|
||||
]
|
||||
|
||||
urlpatterns = format_suffix_patterns(urlpatterns)
|
||||
|
|
|
@ -79,9 +79,9 @@ Okay, we're done. If you run the development server everything should be workin
|
|||
|
||||
## Using mixins
|
||||
|
||||
One of the big wins of using class-based views is that it allows us to easily compose reusable bits of behaviour.
|
||||
One of the big wins of using class-based views is that it allows us to easily compose reusable bits of behavior.
|
||||
|
||||
The create/retrieve/update/delete operations that we've been using so far are going to be pretty similar for any model-backed API views we create. Those bits of common behaviour are implemented in REST framework's mixin classes.
|
||||
The create/retrieve/update/delete operations that we've been using so far are going to be pretty similar for any model-backed API views we create. Those bits of common behavior are implemented in REST framework's mixin classes.
|
||||
|
||||
Let's take a look at how we can compose the views by using the mixin classes. Here's our `views.py` module again.
|
||||
|
||||
|
|
|
@ -38,7 +38,7 @@ And now we can add a `.save()` method to our model class:
|
|||
formatter = HtmlFormatter(style=self.style, linenos=linenos,
|
||||
full=True, **options)
|
||||
self.highlighted = highlight(self.code, lexer, formatter)
|
||||
super(Snippet, self).save(*args, **kwargs)
|
||||
super().save(*args, **kwargs)
|
||||
|
||||
When that's all done we'll need to update our database tables.
|
||||
Normally we'd create a database migration in order to do that, but for the purposes of this tutorial, let's just delete the database and start again.
|
||||
|
|
|
@ -31,7 +31,6 @@ The other thing we need to consider when creating the code highlight view is tha
|
|||
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.py` add:
|
||||
|
||||
from rest_framework import renderers
|
||||
from rest_framework.response import Response
|
||||
|
||||
class SnippetHighlight(generics.GenericAPIView):
|
||||
queryset = Snippet.objects.all()
|
||||
|
|
|
@ -10,10 +10,11 @@ A `ViewSet` class is only bound to a set of method handlers at the last moment,
|
|||
|
||||
Let's take our current set of views, and refactor them into view sets.
|
||||
|
||||
First of all let's refactor our `UserList` and `UserDetail` views into a single `UserViewSet`. We can remove the two views, and replace them with a single class:
|
||||
First of all let's refactor our `UserList` and `UserDetail` classes into a single `UserViewSet` class. We can remove the two view classes, and replace them with a single ViewSet class:
|
||||
|
||||
from rest_framework import viewsets
|
||||
|
||||
|
||||
class UserViewSet(viewsets.ReadOnlyModelViewSet):
|
||||
"""
|
||||
This viewset automatically provides `list` and `retrieve` actions.
|
||||
|
@ -25,13 +26,15 @@ Here we've used the `ReadOnlyModelViewSet` class to automatically provide the de
|
|||
|
||||
Next we're going to replace the `SnippetList`, `SnippetDetail` and `SnippetHighlight` view classes. We can remove the three views, and again replace them with a single class.
|
||||
|
||||
from rest_framework import permissions
|
||||
from rest_framework import renderers
|
||||
from rest_framework.decorators import action
|
||||
from rest_framework.response import Response
|
||||
from rest_framework import permissions
|
||||
|
||||
|
||||
class SnippetViewSet(viewsets.ModelViewSet):
|
||||
"""
|
||||
This viewset automatically provides `list`, `create`, `retrieve`,
|
||||
This ViewSet automatically provides `list`, `create`, `retrieve`,
|
||||
`update` and `destroy` actions.
|
||||
|
||||
Additionally we also provide an extra `highlight` action.
|
||||
|
@ -64,9 +67,10 @@ To see what's going on under the hood let's first explicitly create a set of vie
|
|||
|
||||
In the `snippets/urls.py` file we bind our `ViewSet` classes into a set of concrete views.
|
||||
|
||||
from snippets.views import SnippetViewSet, UserViewSet, api_root
|
||||
from rest_framework import renderers
|
||||
|
||||
from snippets.views import api_root, SnippetViewSet, UserViewSet
|
||||
|
||||
snippet_list = SnippetViewSet.as_view({
|
||||
'get': 'list',
|
||||
'post': 'create'
|
||||
|
@ -87,7 +91,7 @@ In the `snippets/urls.py` file we bind our `ViewSet` classes into a set of concr
|
|||
'get': 'retrieve'
|
||||
})
|
||||
|
||||
Notice how we're creating multiple views from each `ViewSet` class, by binding the http methods to the required action for each view.
|
||||
Notice how we're creating multiple views from each `ViewSet` class, by binding the HTTP methods to the required action for each view.
|
||||
|
||||
Now that we've bound our resources into concrete views, we can register the views with the URL conf as usual.
|
||||
|
||||
|
@ -108,24 +112,25 @@ Here's our re-wired `snippets/urls.py` file.
|
|||
|
||||
from django.urls import path, include
|
||||
from rest_framework.routers import DefaultRouter
|
||||
|
||||
from snippets import views
|
||||
|
||||
# Create a router and register our viewsets with it.
|
||||
# Create a router and register our ViewSets with it.
|
||||
router = DefaultRouter()
|
||||
router.register(r'snippets', views.SnippetViewSet)
|
||||
router.register(r'users', views.UserViewSet)
|
||||
router.register(r'snippets', views.SnippetViewSet, basename='snippet')
|
||||
router.register(r'users', views.UserViewSet, basename='user')
|
||||
|
||||
# The API URLs are now determined automatically by the router.
|
||||
urlpatterns = [
|
||||
path('', include(router.urls)),
|
||||
]
|
||||
|
||||
Registering the viewsets with the router is similar to providing a urlpattern. We include two arguments - the URL prefix for the views, and the viewset itself.
|
||||
Registering the ViewSets with the router is similar to providing a urlpattern. We include two arguments - the URL prefix for the views, and the view set itself.
|
||||
|
||||
The `DefaultRouter` class we're using also automatically creates the API root view for us, so we can now delete the `api_root` method from our `views` module.
|
||||
The `DefaultRouter` class we're using also automatically creates the API root view for us, so we can now delete the `api_root` function from our `views` module.
|
||||
|
||||
## Trade-offs between views vs viewsets
|
||||
## Trade-offs between views vs ViewSets
|
||||
|
||||
Using viewsets can be a really useful abstraction. It helps ensure that URL conventions will be consistent across your API, minimizes the amount of code you need to write, and allows you to concentrate on the interactions and representations your API provides rather than the specifics of the URL conf.
|
||||
Using ViewSets can be a really useful abstraction. It helps ensure that URL conventions will be consistent across your API, minimizes the amount of code you need to write, and allows you to concentrate on the interactions and representations your API provides rather than the specifics of the URL conf.
|
||||
|
||||
That doesn't mean it's always the right approach to take. There's a similar set of trade-offs to consider as when using class-based views instead of function based views. Using viewsets is less explicit than building your views individually.
|
||||
That doesn't mean it's always the right approach to take. There's a similar set of trade-offs to consider as when using class-based views instead of function-based views. Using ViewSets is less explicit than building your API views individually.
|
||||
|
|
|
@ -30,21 +30,24 @@ The project layout should look like:
|
|||
<some path>/tutorial
|
||||
$ find .
|
||||
.
|
||||
./manage.py
|
||||
./tutorial
|
||||
./tutorial/asgi.py
|
||||
./tutorial/__init__.py
|
||||
./tutorial/quickstart
|
||||
./tutorial/quickstart/__init__.py
|
||||
./tutorial/quickstart/admin.py
|
||||
./tutorial/quickstart/apps.py
|
||||
./tutorial/quickstart/migrations
|
||||
./tutorial/quickstart/migrations/__init__.py
|
||||
./tutorial/quickstart/models.py
|
||||
./tutorial/quickstart/__init__.py
|
||||
./tutorial/quickstart/apps.py
|
||||
./tutorial/quickstart/admin.py
|
||||
./tutorial/quickstart/tests.py
|
||||
./tutorial/quickstart/views.py
|
||||
./tutorial/settings.py
|
||||
./tutorial/urls.py
|
||||
./tutorial/wsgi.py
|
||||
./env
|
||||
./env/...
|
||||
./manage.py
|
||||
|
||||
It may look unusual that the application has been created within the project directory. Using the project's namespace avoids name clashes with external modules (a topic that goes outside the scope of the quickstart).
|
||||
|
||||
|
@ -52,9 +55,9 @@ Now sync your database for the first time:
|
|||
|
||||
python manage.py migrate
|
||||
|
||||
We'll also create an initial user named `admin` with a password of `password123`. We'll authenticate as that user later in our example.
|
||||
We'll also create an initial user named `admin` with a password. We'll authenticate as that user later in our example.
|
||||
|
||||
python manage.py createsuperuser --email admin@example.com --username admin
|
||||
python manage.py createsuperuser --username admin --email admin@example.com
|
||||
|
||||
Once you've set up a database and the initial user is created and ready to go, open up the app's directory and we'll get coding...
|
||||
|
||||
|
@ -62,7 +65,7 @@ Once you've set up a database and the initial user is created and ready to go, o
|
|||
|
||||
First up we're going to define some serializers. Let's create a new module named `tutorial/quickstart/serializers.py` that we'll use for our data representations.
|
||||
|
||||
from django.contrib.auth.models import User, Group
|
||||
from django.contrib.auth.models import Group, User
|
||||
from rest_framework import serializers
|
||||
|
||||
|
||||
|
@ -83,10 +86,10 @@ Notice that we're using hyperlinked relations in this case with `HyperlinkedMode
|
|||
|
||||
Right, we'd better write some views then. Open `tutorial/quickstart/views.py` and get typing.
|
||||
|
||||
from django.contrib.auth.models import User, Group
|
||||
from rest_framework import viewsets
|
||||
from rest_framework import permissions
|
||||
from tutorial.quickstart.serializers import UserSerializer, GroupSerializer
|
||||
from django.contrib.auth.models import Group, User
|
||||
from rest_framework import permissions, viewsets
|
||||
|
||||
from tutorial.quickstart.serializers import GroupSerializer, UserSerializer
|
||||
|
||||
|
||||
class UserViewSet(viewsets.ModelViewSet):
|
||||
|
@ -116,6 +119,7 @@ Okay, now let's wire up the API URLs. On to `tutorial/urls.py`...
|
|||
|
||||
from django.urls import include, path
|
||||
from rest_framework import routers
|
||||
|
||||
from tutorial.quickstart import views
|
||||
|
||||
router = routers.DefaultRouter()
|
||||
|
@ -128,6 +132,8 @@ Okay, now let's wire up the API URLs. On to `tutorial/urls.py`...
|
|||
path('', include(router.urls)),
|
||||
path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
|
||||
]
|
||||
|
||||
urlpatterns += router.urls
|
||||
|
||||
Because we're using viewsets instead of views, we can automatically generate the URL conf for our API, by simply registering the viewsets with a router class.
|
||||
|
||||
|
@ -164,9 +170,30 @@ We're now ready to test the API we've built. Let's fire up the server from the
|
|||
|
||||
We can now access our API, both from the command-line, using tools like `curl`...
|
||||
|
||||
bash: curl -H 'Accept: application/json; indent=4' -u admin:password123 http://127.0.0.1:8000/users/
|
||||
bash: curl -u admin -H 'Accept: application/json; indent=4' http://127.0.0.1:8000/users/
|
||||
Enter host password for user 'admin':
|
||||
{
|
||||
"count": 2,
|
||||
"count": 1,
|
||||
"next": null,
|
||||
"previous": null,
|
||||
"results": [
|
||||
{
|
||||
"url": "http://127.0.0.1:8000/users/1/",
|
||||
"username": "admin",
|
||||
"email": "admin@example.com",
|
||||
"groups": []
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
Or using the [httpie][httpie], command line tool...
|
||||
|
||||
bash: http -a admin http://127.0.0.1:8000/users/
|
||||
http: password for admin@127.0.0.1:8000::
|
||||
$HTTP/1.1 200 OK
|
||||
...
|
||||
{
|
||||
"count": 1,
|
||||
"next": null,
|
||||
"previous": null,
|
||||
"results": [
|
||||
|
@ -175,38 +202,6 @@ We can now access our API, both from the command-line, using tools like `curl`..
|
|||
"groups": [],
|
||||
"url": "http://127.0.0.1:8000/users/1/",
|
||||
"username": "admin"
|
||||
},
|
||||
{
|
||||
"email": "tom@example.com",
|
||||
"groups": [],
|
||||
"url": "http://127.0.0.1:8000/users/2/",
|
||||
"username": "tom"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
Or using the [httpie][httpie], command line tool...
|
||||
|
||||
bash: http -a admin:password123 http://127.0.0.1:8000/users/
|
||||
|
||||
HTTP/1.1 200 OK
|
||||
...
|
||||
{
|
||||
"count": 2,
|
||||
"next": null,
|
||||
"previous": null,
|
||||
"results": [
|
||||
{
|
||||
"email": "admin@example.com",
|
||||
"groups": [],
|
||||
"url": "http://localhost:8000/users/1/",
|
||||
"username": "paul"
|
||||
},
|
||||
{
|
||||
"email": "tom@example.com",
|
||||
"groups": [],
|
||||
"url": "http://127.0.0.1:8000/users/2/",
|
||||
"username": "tom"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
@ -225,4 +220,4 @@ If you want to get a more in depth understanding of how REST framework fits toge
|
|||
[image]: ../img/quickstart.png
|
||||
[tutorial]: 1-serialization.md
|
||||
[guide]: ../api-guide/requests.md
|
||||
[httpie]: https://github.com/jakubroztocil/httpie#installation
|
||||
[httpie]: https://httpie.io/docs#installation
|
||||
|
|
|
@ -53,7 +53,6 @@ nav:
|
|||
- 'Settings': 'api-guide/settings.md'
|
||||
- Topics:
|
||||
- 'Documenting your API': 'topics/documenting-your-api.md'
|
||||
- 'API Clients': 'topics/api-clients.md'
|
||||
- 'Internationalization': 'topics/internationalization.md'
|
||||
- 'AJAX, CSRF & CORS': 'topics/ajax-csrf-cors.md'
|
||||
- 'HTML & Forms': 'topics/html-and-forms.md'
|
||||
|
@ -66,6 +65,8 @@ nav:
|
|||
- 'Contributing to REST framework': 'community/contributing.md'
|
||||
- 'Project management': 'community/project-management.md'
|
||||
- 'Release Notes': 'community/release-notes.md'
|
||||
- '3.14 Announcement': 'community/3.14-announcement.md'
|
||||
- '3.13 Announcement': 'community/3.13-announcement.md'
|
||||
- '3.12 Announcement': 'community/3.12-announcement.md'
|
||||
- '3.11 Announcement': 'community/3.11-announcement.md'
|
||||
- '3.10 Announcement': 'community/3.10-announcement.md'
|
||||
|
|
|
@ -1,6 +1,7 @@
|
|||
# The base set of requirements for REST framework is actually
|
||||
# just Django, but for the purposes of development and testing
|
||||
# there are a number of packages that are useful to install.
|
||||
# just Django and pytz, but for the purposes of development
|
||||
# and testing there are a number of packages that are useful
|
||||
# to install.
|
||||
|
||||
# Laying these out as separate requirements files, allows us to
|
||||
# only included the relevant sets when running tox, and ensures
|
||||
|
|
|
@ -1,2 +1,3 @@
|
|||
# MkDocs to build our documentation.
|
||||
mkdocs>=1.1.2,<1.2
|
||||
jinja2>=2.10,<3.1.0 # contextfilter has been renamed
|
||||
|
|
|
@ -1,10 +1,10 @@
|
|||
# Optional packages which may be used with REST framework.
|
||||
coreapi==2.3.1
|
||||
coreschema==0.0.4
|
||||
django-filter>=2.4.0,<3.0
|
||||
django-guardian>=2.3.0,<2.4
|
||||
markdown==3.3;python_version>="3.6"
|
||||
markdown==3.2.2;python_version=="3.5"
|
||||
psycopg2-binary>=2.8.5,<2.9
|
||||
pygments>=2.7.1,<2.8
|
||||
django-filter
|
||||
django-guardian>=2.4.0,<2.5
|
||||
inflection==0.5.1
|
||||
markdown==3.3
|
||||
psycopg2-binary>=2.9.5,<2.10
|
||||
pygments==2.12
|
||||
pyyaml>=5.3.1,<5.4
|
||||
|
|
|
@ -5,4 +5,4 @@ wheel>=0.35.1,<0.36
|
|||
twine>=3.2.0,<3.3
|
||||
|
||||
# Transifex client for managing translation resources.
|
||||
transifex-client>=0.13.12,<0.14
|
||||
transifex-client
|
||||
|
|
|
@ -1,4 +1,7 @@
|
|||
# Pytest for running the tests.
|
||||
pytest>=6.1,<7.0
|
||||
pytest-cov>=2.10.1,<3.0
|
||||
pytest-django>=4.1.0,<5.0
|
||||
pytest>=6.2.0,<8.0
|
||||
pytest-cov>=4.0.0,<5.0
|
||||
pytest-django>=4.5.2,<5.0
|
||||
importlib-metadata<5.0
|
||||
# temporary pin of attrs
|
||||
attrs==22.1.0
|
||||
|
|
|
@ -10,7 +10,7 @@ ______ _____ _____ _____ __
|
|||
import django
|
||||
|
||||
__title__ = 'Django REST framework'
|
||||
__version__ = '3.12.4'
|
||||
__version__ = '3.14.0'
|
||||
__author__ = 'Tom Christie'
|
||||
__license__ = 'BSD 3-Clause'
|
||||
__copyright__ = 'Copyright 2011-2019 Encode OSS Ltd'
|
||||
|
@ -29,9 +29,5 @@ if django.VERSION < (3, 2):
|
|||
default_app_config = 'rest_framework.apps.RestFrameworkConfig'
|
||||
|
||||
|
||||
class RemovedInDRF313Warning(DeprecationWarning):
|
||||
pass
|
||||
|
||||
|
||||
class RemovedInDRF314Warning(PendingDeprecationWarning):
|
||||
class RemovedInDRF315Warning(DeprecationWarning):
|
||||
pass
|
||||
|
|
|
@ -78,12 +78,12 @@ class BasicAuthentication(BaseAuthentication):
|
|||
auth_decoded = base64.b64decode(auth[1]).decode('utf-8')
|
||||
except UnicodeDecodeError:
|
||||
auth_decoded = base64.b64decode(auth[1]).decode('latin-1')
|
||||
auth_parts = auth_decoded.partition(':')
|
||||
except (TypeError, UnicodeDecodeError, binascii.Error):
|
||||
|
||||
userid, password = auth_decoded.split(':', 1)
|
||||
except (TypeError, ValueError, UnicodeDecodeError, binascii.Error):
|
||||
msg = _('Invalid basic header. Credentials not correctly base64 encoded.')
|
||||
raise exceptions.AuthenticationFailed(msg)
|
||||
|
||||
userid, password = auth_parts[0], auth_parts[2]
|
||||
return self.authenticate_credentials(userid, password, request)
|
||||
|
||||
def authenticate_credentials(self, userid, password, request=None):
|
||||
|
@ -227,6 +227,6 @@ class RemoteUserAuthentication(BaseAuthentication):
|
|||
header = "REMOTE_USER"
|
||||
|
||||
def authenticate(self, request):
|
||||
user = authenticate(remote_user=request.META.get(self.header))
|
||||
user = authenticate(request=request, remote_user=request.META.get(self.header))
|
||||
if user and user.is_active:
|
||||
return (user, None)
|
||||
|
|
|
@ -25,6 +25,7 @@ class TokenAdmin(admin.ModelAdmin):
|
|||
fields = ('user',)
|
||||
ordering = ('-created',)
|
||||
actions = None # Actions not compatible with mapped IDs.
|
||||
autocomplete_fields = ("user",)
|
||||
|
||||
def get_changelist(self, request, **kwargs):
|
||||
return TokenChangeList
|
||||
|
|
|
@ -0,0 +1,17 @@
|
|||
# Generated by Django 4.1.3 on 2022-11-24 21:07
|
||||
|
||||
from django.db import migrations
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('authtoken', '0003_tokenproxy'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterModelOptions(
|
||||
name='tokenproxy',
|
||||
options={'verbose_name': 'Token', 'verbose_name_plural': 'Tokens'},
|
||||
),
|
||||
]
|
|
@ -51,4 +51,5 @@ class TokenProxy(Token):
|
|||
class Meta:
|
||||
proxy = 'rest_framework.authtoken' in settings.INSTALLED_APPS
|
||||
abstract = 'rest_framework.authtoken' not in settings.INSTALLED_APPS
|
||||
verbose_name = "token"
|
||||
verbose_name = _("Token")
|
||||
verbose_name_plural = _("Tokens")
|
||||
|
|
|
@ -2,6 +2,7 @@
|
|||
The `compat` module provides support for backwards compatibility with older
|
||||
versions of Django/Python, and compatibility wrappers around optional packages.
|
||||
"""
|
||||
import django
|
||||
from django.conf import settings
|
||||
from django.views.generic import View
|
||||
|
||||
|
@ -152,6 +153,30 @@ else:
|
|||
return False
|
||||
|
||||
|
||||
if django.VERSION >= (4, 2):
|
||||
# Django 4.2+: use the stock parse_header_parameters function
|
||||
# Note: Django 4.1 also has an implementation of parse_header_parameters
|
||||
# which is slightly different from the one in 4.2, it needs
|
||||
# the compatibility shim as well.
|
||||
from django.utils.http import parse_header_parameters
|
||||
else:
|
||||
# Django <= 4.1: create a compatibility shim for parse_header_parameters
|
||||
from django.http.multipartparser import parse_header
|
||||
|
||||
def parse_header_parameters(line):
|
||||
# parse_header works with bytes, but parse_header_parameters
|
||||
# works with strings. Call encode to convert the line to bytes.
|
||||
main_value_pair, params = parse_header(line.encode())
|
||||
return main_value_pair, {
|
||||
# parse_header will convert *some* values to string.
|
||||
# parse_header_parameters converts *all* values to string.
|
||||
# Make sure all values are converted by calling decode on
|
||||
# any remaining non-string values.
|
||||
k: v if isinstance(v, str) else v.decode()
|
||||
for k, v in params.items()
|
||||
}
|
||||
|
||||
|
||||
# `separators` argument to `json.dumps()` differs between 2.x and 3.x
|
||||
# See: https://bugs.python.org/issue22767
|
||||
SHORT_SEPARATORS = (',', ':')
|
||||
|
|
|
@ -142,7 +142,7 @@ def action(methods=None, detail=None, url_path=None, url_name=None, **kwargs):
|
|||
how the `@renderer_classes` etc. decorators work for function-
|
||||
based API views.
|
||||
"""
|
||||
methods = ['get'] if (methods is None) else methods
|
||||
methods = ['get'] if methods is None else methods
|
||||
methods = [method.lower() for method in methods]
|
||||
|
||||
assert detail is not None, (
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
"""
|
||||
Handled exceptions raised by REST framework.
|
||||
|
||||
In addition Django's built in 403 and 404 exceptions are handled.
|
||||
In addition, Django's built in 403 and 404 exceptions are handled.
|
||||
(`django.http.Http404` and `django.core.exceptions.PermissionDenied`)
|
||||
"""
|
||||
import math
|
||||
|
@ -72,16 +72,19 @@ class ErrorDetail(str):
|
|||
return self
|
||||
|
||||
def __eq__(self, other):
|
||||
r = super().__eq__(other)
|
||||
if r is NotImplemented:
|
||||
result = super().__eq__(other)
|
||||
if result is NotImplemented:
|
||||
return NotImplemented
|
||||
try:
|
||||
return r and self.code == other.code
|
||||
return result and self.code == other.code
|
||||
except AttributeError:
|
||||
return r
|
||||
return result
|
||||
|
||||
def __ne__(self, other):
|
||||
return not self.__eq__(other)
|
||||
result = self.__eq__(other)
|
||||
if result is NotImplemented:
|
||||
return NotImplemented
|
||||
return not result
|
||||
|
||||
def __repr__(self):
|
||||
return 'ErrorDetail(string=%r, code=%r)' % (
|
||||
|
@ -141,17 +144,30 @@ class ValidationError(APIException):
|
|||
status_code = status.HTTP_400_BAD_REQUEST
|
||||
default_detail = _('Invalid input.')
|
||||
default_code = 'invalid'
|
||||
default_params = {}
|
||||
|
||||
def __init__(self, detail=None, code=None):
|
||||
def __init__(self, detail=None, code=None, params=None):
|
||||
if detail is None:
|
||||
detail = self.default_detail
|
||||
if code is None:
|
||||
code = self.default_code
|
||||
if params is None:
|
||||
params = self.default_params
|
||||
|
||||
# For validation failures, we may collect many errors together,
|
||||
# so the details should always be coerced to a list if not already.
|
||||
if isinstance(detail, tuple):
|
||||
detail = list(detail)
|
||||
if isinstance(detail, str):
|
||||
detail = [detail % params]
|
||||
elif isinstance(detail, ValidationError):
|
||||
detail = detail.detail
|
||||
elif isinstance(detail, (list, tuple)):
|
||||
final_detail = []
|
||||
for detail_item in detail:
|
||||
if isinstance(detail_item, ValidationError):
|
||||
final_detail += detail_item.detail
|
||||
else:
|
||||
final_detail += [detail_item % params if isinstance(detail_item, str) else detail_item]
|
||||
detail = final_detail
|
||||
elif not isinstance(detail, dict) and not isinstance(detail, list):
|
||||
detail = [detail]
|
||||
|
||||
|
|
|
@ -1,3 +1,4 @@
|
|||
import contextlib
|
||||
import copy
|
||||
import datetime
|
||||
import decimal
|
||||
|
@ -5,7 +6,6 @@ import functools
|
|||
import inspect
|
||||
import re
|
||||
import uuid
|
||||
import warnings
|
||||
from collections import OrderedDict
|
||||
from collections.abc import Mapping
|
||||
|
||||
|
@ -27,13 +27,10 @@ from django.utils.duration import duration_string
|
|||
from django.utils.encoding import is_protected_type, smart_str
|
||||
from django.utils.formats import localize_input, sanitize_separators
|
||||
from django.utils.ipv6 import clean_ipv6_address
|
||||
from django.utils.timezone import utc
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
from pytz.exceptions import InvalidTimeError
|
||||
|
||||
from rest_framework import (
|
||||
ISO_8601, RemovedInDRF313Warning, RemovedInDRF314Warning
|
||||
)
|
||||
from rest_framework import ISO_8601
|
||||
from rest_framework.exceptions import ErrorDetail, ValidationError
|
||||
from rest_framework.settings import api_settings
|
||||
from rest_framework.utils import html, humanize_datetime, json, representation
|
||||
|
@ -63,6 +60,9 @@ def is_simple_callable(obj):
|
|||
"""
|
||||
True if the object is a callable that takes no arguments.
|
||||
"""
|
||||
if not callable(obj):
|
||||
return False
|
||||
|
||||
# Bail early since we cannot inspect built-in function signatures.
|
||||
if inspect.isbuiltin(obj):
|
||||
raise BuiltinSignatureError(
|
||||
|
@ -242,16 +242,6 @@ class CreateOnlyDefault:
|
|||
if is_update:
|
||||
raise SkipField()
|
||||
if callable(self.default):
|
||||
if hasattr(self.default, 'set_context'):
|
||||
warnings.warn(
|
||||
"Method `set_context` on defaults is deprecated and will "
|
||||
"no longer be called starting with 3.13. Instead set "
|
||||
"`requires_context = True` on the class, and accept the "
|
||||
"context as an additional argument.",
|
||||
RemovedInDRF313Warning, stacklevel=2
|
||||
)
|
||||
self.default.set_context(self)
|
||||
|
||||
if getattr(self.default, 'requires_context', False):
|
||||
return self.default(serializer_field)
|
||||
else:
|
||||
|
@ -299,7 +289,7 @@ class Field:
|
|||
default_empty_html = empty
|
||||
initial = None
|
||||
|
||||
def __init__(self, read_only=False, write_only=False,
|
||||
def __init__(self, *, read_only=False, write_only=False,
|
||||
required=None, default=empty, initial=empty, source=None,
|
||||
label=None, help_text=None, style=None,
|
||||
error_messages=None, validators=None, allow_null=False):
|
||||
|
@ -345,6 +335,10 @@ class Field:
|
|||
messages.update(error_messages or {})
|
||||
self.error_messages = messages
|
||||
|
||||
# Allow generic typing checking for fields.
|
||||
def __class_getitem__(cls, *args, **kwargs):
|
||||
return cls
|
||||
|
||||
def bind(self, field_name, parent):
|
||||
"""
|
||||
Initializes the field name and parent for the field instance.
|
||||
|
@ -481,16 +475,6 @@ class Field:
|
|||
# No default, or this is a partial update.
|
||||
raise SkipField()
|
||||
if callable(self.default):
|
||||
if hasattr(self.default, 'set_context'):
|
||||
warnings.warn(
|
||||
"Method `set_context` on defaults is deprecated and will "
|
||||
"no longer be called starting with 3.13. Instead set "
|
||||
"`requires_context = True` on the class, and accept the "
|
||||
"context as an additional argument.",
|
||||
RemovedInDRF313Warning, stacklevel=2
|
||||
)
|
||||
self.default.set_context(self)
|
||||
|
||||
if getattr(self.default, 'requires_context', False):
|
||||
return self.default(self)
|
||||
else:
|
||||
|
@ -555,16 +539,6 @@ class Field:
|
|||
"""
|
||||
errors = []
|
||||
for validator in self.validators:
|
||||
if hasattr(validator, 'set_context'):
|
||||
warnings.warn(
|
||||
"Method `set_context` on validators is deprecated and will "
|
||||
"no longer be called starting with 3.13. Instead set "
|
||||
"`requires_context = True` on the class, and accept the "
|
||||
"context as an additional argument.",
|
||||
RemovedInDRF313Warning, stacklevel=2
|
||||
)
|
||||
validator.set_context(self)
|
||||
|
||||
try:
|
||||
if getattr(validator, 'requires_context', False):
|
||||
validator(value, self)
|
||||
|
@ -699,16 +673,20 @@ class BooleanField(Field):
|
|||
}
|
||||
NULL_VALUES = {'null', 'Null', 'NULL', '', None}
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
if kwargs.get('allow_null', False):
|
||||
self.default_empty_html = None
|
||||
self.initial = None
|
||||
super().__init__(**kwargs)
|
||||
|
||||
def to_internal_value(self, data):
|
||||
try:
|
||||
with contextlib.suppress(TypeError):
|
||||
if data in self.TRUE_VALUES:
|
||||
return True
|
||||
elif data in self.FALSE_VALUES:
|
||||
return False
|
||||
elif data in self.NULL_VALUES and self.allow_null:
|
||||
return None
|
||||
except TypeError: # Input is an unhashable type
|
||||
pass
|
||||
self.fail('invalid', input=data)
|
||||
|
||||
def to_representation(self, value):
|
||||
|
@ -721,23 +699,6 @@ class BooleanField(Field):
|
|||
return bool(value)
|
||||
|
||||
|
||||
class NullBooleanField(BooleanField):
|
||||
initial = None
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
warnings.warn(
|
||||
"The `NullBooleanField` is deprecated and will be removed starting "
|
||||
"with 3.14. Instead use the `BooleanField` field and set "
|
||||
"`allow_null=True` which does the same thing.",
|
||||
RemovedInDRF314Warning, stacklevel=2
|
||||
)
|
||||
|
||||
assert 'allow_null' not in kwargs, '`allow_null` is not a valid option.'
|
||||
kwargs['allow_null'] = True
|
||||
|
||||
super().__init__(**kwargs)
|
||||
|
||||
|
||||
# String types...
|
||||
|
||||
class CharField(Field):
|
||||
|
@ -947,7 +908,8 @@ class FloatField(Field):
|
|||
'invalid': _('A valid number is required.'),
|
||||
'max_value': _('Ensure this value is less than or equal to {max_value}.'),
|
||||
'min_value': _('Ensure this value is greater than or equal to {min_value}.'),
|
||||
'max_string_length': _('String value too large.')
|
||||
'max_string_length': _('String value too large.'),
|
||||
'overflow': _('Integer value too large to convert to float')
|
||||
}
|
||||
MAX_STRING_LENGTH = 1000 # Guard against malicious string inputs.
|
||||
|
||||
|
@ -973,6 +935,8 @@ class FloatField(Field):
|
|||
return float(data)
|
||||
except (TypeError, ValueError):
|
||||
self.fail('invalid')
|
||||
except OverflowError:
|
||||
self.fail('overflow')
|
||||
|
||||
def to_representation(self, value):
|
||||
return float(value)
|
||||
|
@ -991,10 +955,11 @@ class DecimalField(Field):
|
|||
MAX_STRING_LENGTH = 1000 # Guard against malicious string inputs.
|
||||
|
||||
def __init__(self, max_digits, decimal_places, coerce_to_string=None, max_value=None, min_value=None,
|
||||
localize=False, rounding=None, **kwargs):
|
||||
localize=False, rounding=None, normalize_output=False, **kwargs):
|
||||
self.max_digits = max_digits
|
||||
self.decimal_places = decimal_places
|
||||
self.localize = localize
|
||||
self.normalize_output = normalize_output
|
||||
if coerce_to_string is not None:
|
||||
self.coerce_to_string = coerce_to_string
|
||||
if self.localize:
|
||||
|
@ -1025,6 +990,11 @@ class DecimalField(Field):
|
|||
'Invalid rounding option %s. Valid values for rounding are: %s' % (rounding, valid_roundings))
|
||||
self.rounding = rounding
|
||||
|
||||
def validate_empty_values(self, data):
|
||||
if smart_str(data).strip() == '' and self.allow_null:
|
||||
return (True, None)
|
||||
return super().validate_empty_values(data)
|
||||
|
||||
def to_internal_value(self, data):
|
||||
"""
|
||||
Validate that the input is a decimal number and return a Decimal
|
||||
|
@ -1042,9 +1012,6 @@ class DecimalField(Field):
|
|||
try:
|
||||
value = decimal.Decimal(data)
|
||||
except decimal.DecimalException:
|
||||
if data == '' and self.allow_null:
|
||||
return None
|
||||
|
||||
self.fail('invalid')
|
||||
|
||||
if value.is_nan():
|
||||
|
@ -1105,6 +1072,9 @@ class DecimalField(Field):
|
|||
|
||||
quantized = self.quantize(value)
|
||||
|
||||
if self.normalize_output:
|
||||
quantized = quantized.normalize()
|
||||
|
||||
if not coerce_to_string:
|
||||
return quantized
|
||||
if self.localize:
|
||||
|
@ -1140,21 +1110,21 @@ class DateTimeField(Field):
|
|||
}
|
||||
datetime_parser = datetime.datetime.strptime
|
||||
|
||||
def __init__(self, format=empty, input_formats=None, default_timezone=None, *args, **kwargs):
|
||||
def __init__(self, format=empty, input_formats=None, default_timezone=None, **kwargs):
|
||||
if format is not empty:
|
||||
self.format = format
|
||||
if input_formats is not None:
|
||||
self.input_formats = input_formats
|
||||
if default_timezone is not None:
|
||||
self.timezone = default_timezone
|
||||
super().__init__(*args, **kwargs)
|
||||
super().__init__(**kwargs)
|
||||
|
||||
def enforce_timezone(self, value):
|
||||
"""
|
||||
When `self.default_timezone` is `None`, always return naive datetimes.
|
||||
When `self.default_timezone` is not `None`, always return aware datetimes.
|
||||
"""
|
||||
field_timezone = getattr(self, 'timezone', self.default_timezone())
|
||||
field_timezone = self.timezone if hasattr(self, 'timezone') else self.default_timezone()
|
||||
|
||||
if field_timezone is not None:
|
||||
if timezone.is_aware(value):
|
||||
|
@ -1167,7 +1137,7 @@ class DateTimeField(Field):
|
|||
except InvalidTimeError:
|
||||
self.fail('make_aware', timezone=field_timezone)
|
||||
elif (field_timezone is None) and timezone.is_aware(value):
|
||||
return timezone.make_naive(value, utc)
|
||||
return timezone.make_naive(value, datetime.timezone.utc)
|
||||
return value
|
||||
|
||||
def default_timezone(self):
|
||||
|
@ -1183,19 +1153,14 @@ class DateTimeField(Field):
|
|||
return self.enforce_timezone(value)
|
||||
|
||||
for input_format in input_formats:
|
||||
if input_format.lower() == ISO_8601:
|
||||
try:
|
||||
with contextlib.suppress(ValueError, TypeError):
|
||||
if input_format.lower() == ISO_8601:
|
||||
parsed = parse_datetime(value)
|
||||
if parsed is not None:
|
||||
return self.enforce_timezone(parsed)
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
else:
|
||||
try:
|
||||
parsed = self.datetime_parser(value, input_format)
|
||||
return self.enforce_timezone(parsed)
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
|
||||
parsed = self.datetime_parser(value, input_format)
|
||||
return self.enforce_timezone(parsed)
|
||||
|
||||
humanized_format = humanize_datetime.datetime_formats(input_formats)
|
||||
self.fail('invalid', format=humanized_format)
|
||||
|
@ -1226,12 +1191,12 @@ class DateField(Field):
|
|||
}
|
||||
datetime_parser = datetime.datetime.strptime
|
||||
|
||||
def __init__(self, format=empty, input_formats=None, *args, **kwargs):
|
||||
def __init__(self, format=empty, input_formats=None, **kwargs):
|
||||
if format is not empty:
|
||||
self.format = format
|
||||
if input_formats is not None:
|
||||
self.input_formats = input_formats
|
||||
super().__init__(*args, **kwargs)
|
||||
super().__init__(**kwargs)
|
||||
|
||||
def to_internal_value(self, value):
|
||||
input_formats = getattr(self, 'input_formats', api_settings.DATE_INPUT_FORMATS)
|
||||
|
@ -1292,12 +1257,12 @@ class TimeField(Field):
|
|||
}
|
||||
datetime_parser = datetime.datetime.strptime
|
||||
|
||||
def __init__(self, format=empty, input_formats=None, *args, **kwargs):
|
||||
def __init__(self, format=empty, input_formats=None, **kwargs):
|
||||
if format is not empty:
|
||||
self.format = format
|
||||
if input_formats is not None:
|
||||
self.input_formats = input_formats
|
||||
super().__init__(*args, **kwargs)
|
||||
super().__init__(**kwargs)
|
||||
|
||||
def to_internal_value(self, value):
|
||||
input_formats = getattr(self, 'input_formats', api_settings.TIME_INPUT_FORMATS)
|
||||
|
@ -1353,6 +1318,7 @@ class DurationField(Field):
|
|||
'invalid': _('Duration has wrong format. Use one of these formats instead: {format}.'),
|
||||
'max_value': _('Ensure this value is less than or equal to {max_value}.'),
|
||||
'min_value': _('Ensure this value is greater than or equal to {min_value}.'),
|
||||
'overflow': _('The number of days must be between {min_days} and {max_days}.'),
|
||||
}
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
|
@ -1371,7 +1337,10 @@ class DurationField(Field):
|
|||
def to_internal_value(self, value):
|
||||
if isinstance(value, datetime.timedelta):
|
||||
return value
|
||||
parsed = parse_duration(str(value))
|
||||
try:
|
||||
parsed = parse_duration(str(value))
|
||||
except OverflowError:
|
||||
self.fail('overflow', min_days=datetime.timedelta.min.days, max_days=datetime.timedelta.max.days)
|
||||
if parsed is not None:
|
||||
return parsed
|
||||
self.fail('invalid', format='[DD] [HH:[MM:]]ss[.uuuuuu]')
|
||||
|
@ -1447,9 +1416,9 @@ class MultipleChoiceField(ChoiceField):
|
|||
}
|
||||
default_empty_html = []
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
def __init__(self, **kwargs):
|
||||
self.allow_empty = kwargs.pop('allow_empty', True)
|
||||
super().__init__(*args, **kwargs)
|
||||
super().__init__(**kwargs)
|
||||
|
||||
def get_value(self, dictionary):
|
||||
if self.field_name not in dictionary:
|
||||
|
@ -1468,6 +1437,8 @@ class MultipleChoiceField(ChoiceField):
|
|||
self.fail('empty')
|
||||
|
||||
return {
|
||||
# Arguments for super() are needed because of scoping inside
|
||||
# comprehensions.
|
||||
super(MultipleChoiceField, self).to_internal_value(item)
|
||||
for item in data
|
||||
}
|
||||
|
@ -1492,6 +1463,7 @@ class FilePathField(ChoiceField):
|
|||
allow_folders=allow_folders, required=required
|
||||
)
|
||||
kwargs['choices'] = field.choices
|
||||
kwargs['required'] = required
|
||||
super().__init__(**kwargs)
|
||||
|
||||
|
||||
|
@ -1506,12 +1478,12 @@ class FileField(Field):
|
|||
'max_length': _('Ensure this filename has at most {max_length} characters (it has {length}).'),
|
||||
}
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
def __init__(self, **kwargs):
|
||||
self.max_length = kwargs.pop('max_length', None)
|
||||
self.allow_empty_file = kwargs.pop('allow_empty_file', False)
|
||||
if 'use_url' in kwargs:
|
||||
self.use_url = kwargs.pop('use_url')
|
||||
super().__init__(*args, **kwargs)
|
||||
super().__init__(**kwargs)
|
||||
|
||||
def to_internal_value(self, data):
|
||||
try:
|
||||
|
@ -1555,9 +1527,9 @@ class ImageField(FileField):
|
|||
),
|
||||
}
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
def __init__(self, **kwargs):
|
||||
self._DjangoImageField = kwargs.pop('_DjangoImageField', DjangoImageField)
|
||||
super().__init__(*args, **kwargs)
|
||||
super().__init__(**kwargs)
|
||||
|
||||
def to_internal_value(self, data):
|
||||
# Image validation is a bit grungy, so we'll just outright
|
||||
|
@ -1572,8 +1544,8 @@ class ImageField(FileField):
|
|||
# Composite field types...
|
||||
|
||||
class _UnvalidatedField(Field):
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
def __init__(self, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
self.allow_blank = True
|
||||
self.allow_null = True
|
||||
|
||||
|
@ -1594,7 +1566,7 @@ class ListField(Field):
|
|||
'max_length': _('Ensure this field has no more than {max_length} elements.')
|
||||
}
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
def __init__(self, **kwargs):
|
||||
self.child = kwargs.pop('child', copy.deepcopy(self.child))
|
||||
self.allow_empty = kwargs.pop('allow_empty', True)
|
||||
self.max_length = kwargs.pop('max_length', None)
|
||||
|
@ -1606,7 +1578,7 @@ class ListField(Field):
|
|||
"Remove `source=` from the field declaration."
|
||||
)
|
||||
|
||||
super().__init__(*args, **kwargs)
|
||||
super().__init__(**kwargs)
|
||||
self.child.bind(field_name='', parent=self)
|
||||
if self.max_length is not None:
|
||||
message = lazy_format(self.error_messages['max_length'], max_length=self.max_length)
|
||||
|
@ -1657,6 +1629,8 @@ class ListField(Field):
|
|||
result.append(self.child.run_validation(item))
|
||||
except ValidationError as e:
|
||||
errors[idx] = e.detail
|
||||
except DjangoValidationError as e:
|
||||
errors[idx] = get_error_detail(e)
|
||||
|
||||
if not errors:
|
||||
return result
|
||||
|
@ -1671,7 +1645,7 @@ class DictField(Field):
|
|||
'empty': _('This dictionary may not be empty.'),
|
||||
}
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
def __init__(self, **kwargs):
|
||||
self.child = kwargs.pop('child', copy.deepcopy(self.child))
|
||||
self.allow_empty = kwargs.pop('allow_empty', True)
|
||||
|
||||
|
@ -1681,7 +1655,7 @@ class DictField(Field):
|
|||
"Remove `source=` from the field declaration."
|
||||
)
|
||||
|
||||
super().__init__(*args, **kwargs)
|
||||
super().__init__(**kwargs)
|
||||
self.child.bind(field_name='', parent=self)
|
||||
|
||||
def get_value(self, dictionary):
|
||||
|
@ -1730,8 +1704,8 @@ class DictField(Field):
|
|||
class HStoreField(DictField):
|
||||
child = CharField(allow_blank=True, allow_null=True)
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
def __init__(self, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
assert isinstance(self.child, CharField), (
|
||||
"The `child` argument must be an instance of `CharField`, "
|
||||
"as the hstore extension stores values as strings."
|
||||
|
@ -1746,11 +1720,11 @@ class JSONField(Field):
|
|||
# Workaround for isinstance calls when importing the field isn't possible
|
||||
_is_jsonfield = True
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
def __init__(self, **kwargs):
|
||||
self.binary = kwargs.pop('binary', False)
|
||||
self.encoder = kwargs.pop('encoder', None)
|
||||
self.decoder = kwargs.pop('decoder', None)
|
||||
super().__init__(*args, **kwargs)
|
||||
super().__init__(**kwargs)
|
||||
|
||||
def get_value(self, dictionary):
|
||||
if html.is_html_input(dictionary) and self.field_name in dictionary:
|
||||
|
@ -1837,7 +1811,7 @@ class SerializerMethodField(Field):
|
|||
|
||||
For example:
|
||||
|
||||
class ExampleSerializer(self):
|
||||
class ExampleSerializer(Serializer):
|
||||
extra_info = SerializerMethodField()
|
||||
|
||||
def get_extra_info(self, obj):
|
||||
|
|
|
@ -45,6 +45,10 @@ class GenericAPIView(views.APIView):
|
|||
# The style to use for queryset pagination.
|
||||
pagination_class = api_settings.DEFAULT_PAGINATION_CLASS
|
||||
|
||||
# Allow generic typing checking for generic views.
|
||||
def __class_getitem__(cls, *args, **kwargs):
|
||||
return cls
|
||||
|
||||
def get_queryset(self):
|
||||
"""
|
||||
Get the list of items for this view.
|
||||
|
|
|
@ -26,6 +26,7 @@ class Command(BaseCommand):
|
|||
parser.add_argument('--urlconf', dest="urlconf", default=None, type=str)
|
||||
parser.add_argument('--generator_class', dest="generator_class", default=None, type=str)
|
||||
parser.add_argument('--file', dest="file", default=None, type=str)
|
||||
parser.add_argument('--api_version', dest="api_version", default='', type=str)
|
||||
|
||||
def handle(self, *args, **options):
|
||||
if options['generator_class']:
|
||||
|
@ -37,6 +38,7 @@ class Command(BaseCommand):
|
|||
title=options['title'],
|
||||
description=options['description'],
|
||||
urlconf=options['urlconf'],
|
||||
version=options['api_version'],
|
||||
)
|
||||
schema = generator.get_schema(request=None, public=True)
|
||||
renderer = self.get_renderer(options['format'])
|
||||
|
|
|
@ -36,7 +36,6 @@ class SimpleMetadata(BaseMetadata):
|
|||
label_lookup = ClassLookupDict({
|
||||
serializers.Field: 'field',
|
||||
serializers.BooleanField: 'boolean',
|
||||
serializers.NullBooleanField: 'boolean',
|
||||
serializers.CharField: 'string',
|
||||
serializers.UUIDField: 'string',
|
||||
serializers.URLField: 'url',
|
||||
|
@ -49,6 +48,7 @@ class SimpleMetadata(BaseMetadata):
|
|||
serializers.DateField: 'date',
|
||||
serializers.DateTimeField: 'datetime',
|
||||
serializers.TimeField: 'time',
|
||||
serializers.DurationField: 'duration',
|
||||
serializers.ChoiceField: 'choice',
|
||||
serializers.MultipleChoiceField: 'multiple choice',
|
||||
serializers.FileField: 'file upload',
|
||||
|
|
|
@ -4,6 +4,8 @@ Basic building blocks for generic class based views.
|
|||
We don't bind behaviour to http method handlers yet,
|
||||
which allows mixin classes to be composed in interesting ways.
|
||||
"""
|
||||
from django.db.models.query import prefetch_related_objects
|
||||
|
||||
from rest_framework import status
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.settings import api_settings
|
||||
|
@ -67,10 +69,13 @@ class UpdateModelMixin:
|
|||
serializer.is_valid(raise_exception=True)
|
||||
self.perform_update(serializer)
|
||||
|
||||
if getattr(instance, '_prefetched_objects_cache', None):
|
||||
queryset = self.filter_queryset(self.get_queryset())
|
||||
if queryset._prefetch_related_lookups:
|
||||
# If 'prefetch_related' has been applied to a queryset, we need to
|
||||
# forcibly invalidate the prefetch cache on the instance.
|
||||
# forcibly invalidate the prefetch cache on the instance,
|
||||
# and then re-prefetch related objects
|
||||
instance._prefetched_objects_cache = {}
|
||||
prefetch_related_objects([instance], *queryset._prefetch_related_lookups)
|
||||
|
||||
return Response(serializer.data)
|
||||
|
||||
|
|
|
@ -4,7 +4,7 @@ incoming request. Typically this will be based on the request's Accept header.
|
|||
"""
|
||||
from django.http import Http404
|
||||
|
||||
from rest_framework import HTTP_HEADER_ENCODING, exceptions
|
||||
from rest_framework import exceptions
|
||||
from rest_framework.settings import api_settings
|
||||
from rest_framework.utils.mediatypes import (
|
||||
_MediaType, media_type_matches, order_by_precedence
|
||||
|
@ -64,9 +64,11 @@ class DefaultContentNegotiation(BaseContentNegotiation):
|
|||
# Accepted media type is 'application/json'
|
||||
full_media_type = ';'.join(
|
||||
(renderer.media_type,) +
|
||||
tuple('{}={}'.format(
|
||||
key, value.decode(HTTP_HEADER_ENCODING))
|
||||
for key, value in media_type_wrapper.params.items()))
|
||||
tuple(
|
||||
'{}={}'.format(key, value)
|
||||
for key, value in media_type_wrapper.params.items()
|
||||
)
|
||||
)
|
||||
return renderer, full_media_type
|
||||
else:
|
||||
# Eg client requests 'application/json; indent=8'
|
||||
|
|
|
@ -2,6 +2,8 @@
|
|||
Pagination serializers determine the structure of the output that should
|
||||
be used for paginated responses.
|
||||
"""
|
||||
|
||||
import contextlib
|
||||
from base64 import b64decode, b64encode
|
||||
from collections import OrderedDict, namedtuple
|
||||
from urllib import parse
|
||||
|
@ -193,6 +195,7 @@ class PageNumberPagination(BasePagination):
|
|||
Paginate a queryset if required, either returning a
|
||||
page object, or `None` if pagination is not configured for this view.
|
||||
"""
|
||||
self.request = request
|
||||
page_size = self.get_page_size(request)
|
||||
if not page_size:
|
||||
return None
|
||||
|
@ -212,11 +215,10 @@ class PageNumberPagination(BasePagination):
|
|||
# The browsable API should display pagination controls.
|
||||
self.display_page_controls = True
|
||||
|
||||
self.request = request
|
||||
return list(self.page)
|
||||
|
||||
def get_page_number(self, request, paginator):
|
||||
page_number = request.query_params.get(self.page_query_param, 1)
|
||||
page_number = request.query_params.get(self.page_query_param) or 1
|
||||
if page_number in self.last_page_strings:
|
||||
page_number = paginator.num_pages
|
||||
return page_number
|
||||
|
@ -257,15 +259,12 @@ class PageNumberPagination(BasePagination):
|
|||
|
||||
def get_page_size(self, request):
|
||||
if self.page_size_query_param:
|
||||
try:
|
||||
with contextlib.suppress(KeyError, ValueError):
|
||||
return _positive_int(
|
||||
request.query_params[self.page_size_query_param],
|
||||
strict=True,
|
||||
cutoff=self.max_page_size
|
||||
)
|
||||
except (KeyError, ValueError):
|
||||
pass
|
||||
|
||||
return self.page_size
|
||||
|
||||
def get_next_link(self):
|
||||
|
@ -380,13 +379,13 @@ class LimitOffsetPagination(BasePagination):
|
|||
template = 'rest_framework/pagination/numbers.html'
|
||||
|
||||
def paginate_queryset(self, queryset, request, view=None):
|
||||
self.request = request
|
||||
self.limit = self.get_limit(request)
|
||||
if self.limit is None:
|
||||
return None
|
||||
|
||||
self.count = self.get_count(queryset)
|
||||
self.offset = self.get_offset(request)
|
||||
self.request = request
|
||||
if self.count > self.limit and self.template is not None:
|
||||
self.display_page_controls = True
|
||||
|
||||
|
@ -430,15 +429,12 @@ class LimitOffsetPagination(BasePagination):
|
|||
|
||||
def get_limit(self, request):
|
||||
if self.limit_query_param:
|
||||
try:
|
||||
with contextlib.suppress(KeyError, ValueError):
|
||||
return _positive_int(
|
||||
request.query_params[self.limit_query_param],
|
||||
strict=True,
|
||||
cutoff=self.max_limit
|
||||
)
|
||||
except (KeyError, ValueError):
|
||||
pass
|
||||
|
||||
return self.default_limit
|
||||
|
||||
def get_offset(self, request):
|
||||
|
@ -603,6 +599,7 @@ class CursorPagination(BasePagination):
|
|||
offset_cutoff = 1000
|
||||
|
||||
def paginate_queryset(self, queryset, request, view=None):
|
||||
self.request = request
|
||||
self.page_size = self.get_page_size(request)
|
||||
if not self.page_size:
|
||||
return None
|
||||
|
@ -680,15 +677,12 @@ class CursorPagination(BasePagination):
|
|||
|
||||
def get_page_size(self, request):
|
||||
if self.page_size_query_param:
|
||||
try:
|
||||
with contextlib.suppress(KeyError, ValueError):
|
||||
return _positive_int(
|
||||
request.query_params[self.page_size_query_param],
|
||||
strict=True,
|
||||
cutoff=self.max_page_size
|
||||
)
|
||||
except (KeyError, ValueError):
|
||||
pass
|
||||
|
||||
return self.page_size
|
||||
|
||||
def get_next_link(self):
|
||||
|
@ -905,10 +899,16 @@ class CursorPagination(BasePagination):
|
|||
'next': {
|
||||
'type': 'string',
|
||||
'nullable': True,
|
||||
'format': 'uri',
|
||||
'example': 'http://api.example.org/accounts/?{cursor_query_param}=cD00ODY%3D"'.format(
|
||||
cursor_query_param=self.cursor_query_param)
|
||||
},
|
||||
'previous': {
|
||||
'type': 'string',
|
||||
'nullable': True,
|
||||
'format': 'uri',
|
||||
'example': 'http://api.example.org/accounts/?{cursor_query_param}=cj0xJnA9NDg3'.format(
|
||||
cursor_query_param=self.cursor_query_param)
|
||||
},
|
||||
'results': schema,
|
||||
},
|
||||
|
@ -961,7 +961,7 @@ class CursorPagination(BasePagination):
|
|||
'in': 'query',
|
||||
'description': force_str(self.cursor_query_description),
|
||||
'schema': {
|
||||
'type': 'integer',
|
||||
'type': 'string',
|
||||
},
|
||||
}
|
||||
]
|
||||
|
|
|
@ -4,8 +4,9 @@ Parsers are used to parse the content of incoming HTTP requests.
|
|||
They give us a generic way of being able to handle various media types
|
||||
on the request, such as form content or json encoded data.
|
||||
"""
|
||||
|
||||
import codecs
|
||||
from urllib import parse
|
||||
import contextlib
|
||||
|
||||
from django.conf import settings
|
||||
from django.core.files.uploadhandler import StopFutureHandlers
|
||||
|
@ -13,10 +14,10 @@ from django.http import QueryDict
|
|||
from django.http.multipartparser import ChunkIter
|
||||
from django.http.multipartparser import \
|
||||
MultiPartParser as DjangoMultiPartParser
|
||||
from django.http.multipartparser import MultiPartParserError, parse_header
|
||||
from django.utils.encoding import force_str
|
||||
from django.http.multipartparser import MultiPartParserError
|
||||
|
||||
from rest_framework import renderers
|
||||
from rest_framework.compat import parse_header_parameters
|
||||
from rest_framework.exceptions import ParseError
|
||||
from rest_framework.settings import api_settings
|
||||
from rest_framework.utils import json
|
||||
|
@ -194,30 +195,12 @@ class FileUploadParser(BaseParser):
|
|||
Detects the uploaded file name. First searches a 'filename' url kwarg.
|
||||
Then tries to parse Content-Disposition header.
|
||||
"""
|
||||
try:
|
||||
with contextlib.suppress(KeyError):
|
||||
return parser_context['kwargs']['filename']
|
||||
except KeyError:
|
||||
pass
|
||||
|
||||
try:
|
||||
with contextlib.suppress(AttributeError, KeyError, ValueError):
|
||||
meta = parser_context['request'].META
|
||||
disposition = parse_header(meta['HTTP_CONTENT_DISPOSITION'].encode())
|
||||
filename_parm = disposition[1]
|
||||
if 'filename*' in filename_parm:
|
||||
return self.get_encoded_filename(filename_parm)
|
||||
return force_str(filename_parm['filename'])
|
||||
except (AttributeError, KeyError, ValueError):
|
||||
pass
|
||||
|
||||
def get_encoded_filename(self, filename_parm):
|
||||
"""
|
||||
Handle encoded filenames per RFC6266. See also:
|
||||
https://tools.ietf.org/html/rfc2231#section-4
|
||||
"""
|
||||
encoded_filename = force_str(filename_parm['filename*'])
|
||||
try:
|
||||
charset, lang, filename = encoded_filename.split('\'', 2)
|
||||
filename = parse.unquote(filename)
|
||||
except (ValueError, LookupError):
|
||||
filename = force_str(filename_parm['filename'])
|
||||
return filename
|
||||
disposition, params = parse_header_parameters(meta['HTTP_CONTENT_DISPOSITION'])
|
||||
if 'filename*' in params:
|
||||
return params['filename*']
|
||||
return params['filename']
|
||||
|
|
|
@ -46,6 +46,14 @@ class OperandHolder(OperationHolderMixin):
|
|||
op2 = self.op2_class(*args, **kwargs)
|
||||
return self.operator_class(op1, op2)
|
||||
|
||||
def __eq__(self, other):
|
||||
return (
|
||||
isinstance(other, OperandHolder) and
|
||||
self.operator_class == other.operator_class and
|
||||
self.op1_class == other.op1_class and
|
||||
self.op2_class == other.op2_class
|
||||
)
|
||||
|
||||
|
||||
class AND:
|
||||
def __init__(self, op1, op2):
|
||||
|
@ -78,8 +86,11 @@ class OR:
|
|||
|
||||
def has_object_permission(self, request, view, obj):
|
||||
return (
|
||||
self.op1.has_object_permission(request, view, obj) or
|
||||
self.op2.has_object_permission(request, view, obj)
|
||||
self.op1.has_permission(request, view)
|
||||
and self.op1.has_object_permission(request, view, obj)
|
||||
) or (
|
||||
self.op2.has_permission(request, view)
|
||||
and self.op2.has_object_permission(request, view, obj)
|
||||
)
|
||||
|
||||
|
||||
|
@ -175,9 +186,9 @@ class DjangoModelPermissions(BasePermission):
|
|||
# Override this if you need to also provide 'view' permissions,
|
||||
# or if you want to provide custom permission codes.
|
||||
perms_map = {
|
||||
'GET': [],
|
||||
'GET': ['%(app_label)s.view_%(model_name)s'],
|
||||
'OPTIONS': [],
|
||||
'HEAD': [],
|
||||
'HEAD': ['%(app_label)s.view_%(model_name)s'],
|
||||
'POST': ['%(app_label)s.add_%(model_name)s'],
|
||||
'PUT': ['%(app_label)s.change_%(model_name)s'],
|
||||
'PATCH': ['%(app_label)s.change_%(model_name)s'],
|
||||
|
@ -217,19 +228,24 @@ class DjangoModelPermissions(BasePermission):
|
|||
return view.queryset
|
||||
|
||||
def has_permission(self, request, view):
|
||||
if not request.user or (
|
||||
not request.user.is_authenticated and self.authenticated_users_only):
|
||||
return False
|
||||
|
||||
# Workaround to ensure DjangoModelPermissions are not applied
|
||||
# to the root view when using DefaultRouter.
|
||||
if getattr(view, '_ignore_model_permissions', False):
|
||||
return True
|
||||
|
||||
if not request.user or (
|
||||
not request.user.is_authenticated and self.authenticated_users_only):
|
||||
return False
|
||||
|
||||
queryset = self._queryset(view)
|
||||
perms = self.get_required_permissions(request.method, queryset.model)
|
||||
change_perm = self.get_required_permissions('PUT', queryset.model)
|
||||
|
||||
return request.user.has_perms(perms)
|
||||
user = request.user
|
||||
if request.method == 'GET':
|
||||
return user.has_perms(perms) or user.has_perms(change_perm)
|
||||
|
||||
return user.has_perms(perms)
|
||||
|
||||
|
||||
class DjangoModelPermissionsOrAnonReadOnly(DjangoModelPermissions):
|
||||
|
|
|
@ -1,3 +1,4 @@
|
|||
import contextlib
|
||||
import sys
|
||||
from collections import OrderedDict
|
||||
from urllib import parse
|
||||
|
@ -10,7 +11,7 @@ from django.utils.encoding import smart_str, uri_to_iri
|
|||
from django.utils.translation import gettext_lazy as _
|
||||
|
||||
from rest_framework.fields import (
|
||||
Field, empty, get_attribute, is_simple_callable, iter_options
|
||||
Field, SkipField, empty, get_attribute, is_simple_callable, iter_options
|
||||
)
|
||||
from rest_framework.reverse import reverse
|
||||
from rest_framework.settings import api_settings
|
||||
|
@ -170,7 +171,7 @@ class RelatedField(Field):
|
|||
def get_attribute(self, instance):
|
||||
if self.use_pk_only_optimization() and self.source_attrs:
|
||||
# Optimized case, return a mock object only containing the pk attribute.
|
||||
try:
|
||||
with contextlib.suppress(AttributeError):
|
||||
attribute_instance = get_attribute(instance, self.source_attrs[:-1])
|
||||
value = attribute_instance.serializable_value(self.source_attrs[-1])
|
||||
if is_simple_callable(value):
|
||||
|
@ -183,9 +184,6 @@ class RelatedField(Field):
|
|||
value = getattr(value, 'pk', value)
|
||||
|
||||
return PKOnlyObject(pk=value)
|
||||
except AttributeError:
|
||||
pass
|
||||
|
||||
# Standard case, return the object instance.
|
||||
return super().get_attribute(instance)
|
||||
|
||||
|
@ -535,7 +533,30 @@ class ManyRelatedField(Field):
|
|||
if hasattr(instance, 'pk') and instance.pk is None:
|
||||
return []
|
||||
|
||||
relationship = get_attribute(instance, self.source_attrs)
|
||||
try:
|
||||
relationship = get_attribute(instance, self.source_attrs)
|
||||
except (KeyError, AttributeError) as exc:
|
||||
if self.default is not empty:
|
||||
return self.get_default()
|
||||
if self.allow_null:
|
||||
return None
|
||||
if not self.required:
|
||||
raise SkipField()
|
||||
msg = (
|
||||
'Got {exc_type} when attempting to get a value for field '
|
||||
'`{field}` on serializer `{serializer}`.\nThe serializer '
|
||||
'field might be named incorrectly and not match '
|
||||
'any attribute or key on the `{instance}` instance.\n'
|
||||
'Original exception text was: {exc}.'.format(
|
||||
exc_type=type(exc).__name__,
|
||||
field=self.field_name,
|
||||
serializer=self.parent.__class__.__name__,
|
||||
instance=instance.__class__.__name__,
|
||||
exc=exc
|
||||
)
|
||||
)
|
||||
raise type(exc)(msg)
|
||||
|
||||
return relationship.all() if hasattr(relationship, 'all') else relationship
|
||||
|
||||
def to_representation(self, iterable):
|
||||
|
|
|
@ -6,7 +6,9 @@ on the response, such as JSON encoded data or HTML output.
|
|||
|
||||
REST framework also provides an HTML renderer that renders the browsable API.
|
||||
"""
|
||||
|
||||
import base64
|
||||
import contextlib
|
||||
from collections import OrderedDict
|
||||
from urllib import parse
|
||||
|
||||
|
@ -14,15 +16,15 @@ from django import forms
|
|||
from django.conf import settings
|
||||
from django.core.exceptions import ImproperlyConfigured
|
||||
from django.core.paginator import Page
|
||||
from django.http.multipartparser import parse_header
|
||||
from django.template import engines, loader
|
||||
from django.urls import NoReverseMatch
|
||||
from django.utils.html import mark_safe
|
||||
from django.utils.safestring import SafeString
|
||||
|
||||
from rest_framework import VERSION, exceptions, serializers, status
|
||||
from rest_framework.compat import (
|
||||
INDENT_SEPARATORS, LONG_SEPARATORS, SHORT_SEPARATORS, coreapi, coreschema,
|
||||
pygments_css, yaml
|
||||
parse_header_parameters, pygments_css, yaml
|
||||
)
|
||||
from rest_framework.exceptions import ParseError
|
||||
from rest_framework.request import is_form_media_type, override_method
|
||||
|
@ -72,12 +74,9 @@ class JSONRenderer(BaseRenderer):
|
|||
# If the media type looks like 'application/json; indent=4',
|
||||
# then pretty print the result.
|
||||
# Note that we coerce `indent=0` into `indent=None`.
|
||||
base_media_type, params = parse_header(accepted_media_type.encode('ascii'))
|
||||
try:
|
||||
base_media_type, params = parse_header_parameters(accepted_media_type)
|
||||
with contextlib.suppress(KeyError, ValueError, TypeError):
|
||||
return zero_as_none(max(min(int(params['indent']), 8), 0))
|
||||
except (KeyError, ValueError, TypeError):
|
||||
pass
|
||||
|
||||
# If 'indent' is provided in the context, then pretty print the result.
|
||||
# E.g. If we're being called by the BrowsableAPIRenderer.
|
||||
return renderer_context.get('indent', None)
|
||||
|
@ -105,7 +104,7 @@ class JSONRenderer(BaseRenderer):
|
|||
|
||||
# We always fully escape \u2028 and \u2029 to ensure we output JSON
|
||||
# that is a strict javascript subset.
|
||||
# See: http://timelessrepo.com/json-isnt-a-javascript-subset
|
||||
# See: https://gist.github.com/damncabbage/623b879af56f850a6ddc
|
||||
ret = ret.replace('\u2028', '\\u2028').replace('\u2029', '\\u2029')
|
||||
return ret.encode()
|
||||
|
||||
|
@ -489,11 +488,8 @@ class BrowsableAPIRenderer(BaseRenderer):
|
|||
return
|
||||
|
||||
if existing_serializer is not None:
|
||||
try:
|
||||
with contextlib.suppress(TypeError):
|
||||
return self.render_form_for_serializer(existing_serializer)
|
||||
except TypeError:
|
||||
pass
|
||||
|
||||
if has_serializer:
|
||||
if method in ('PUT', 'PATCH'):
|
||||
serializer = view.get_serializer(instance=instance, **kwargs)
|
||||
|
@ -1035,13 +1031,16 @@ class CoreAPIJSONOpenAPIRenderer(_BaseOpenAPIRenderer):
|
|||
media_type = 'application/vnd.oai.openapi+json'
|
||||
charset = None
|
||||
format = 'openapi-json'
|
||||
ensure_ascii = not api_settings.UNICODE_JSON
|
||||
|
||||
def __init__(self):
|
||||
assert coreapi, 'Using CoreAPIJSONOpenAPIRenderer, but `coreapi` is not installed.'
|
||||
|
||||
def render(self, data, media_type=None, renderer_context=None):
|
||||
structure = self.get_structure(data)
|
||||
return json.dumps(structure, indent=4).encode('utf-8')
|
||||
return json.dumps(
|
||||
structure, indent=4,
|
||||
ensure_ascii=self.ensure_ascii).encode('utf-8')
|
||||
|
||||
|
||||
class OpenAPIRenderer(BaseRenderer):
|
||||
|
@ -1057,6 +1056,7 @@ class OpenAPIRenderer(BaseRenderer):
|
|||
class Dumper(yaml.Dumper):
|
||||
def ignore_aliases(self, data):
|
||||
return True
|
||||
Dumper.add_representer(SafeString, Dumper.represent_str)
|
||||
return yaml.dump(data, default_flow_style=False, sort_keys=False, Dumper=Dumper).encode('utf-8')
|
||||
|
||||
|
||||
|
@ -1065,6 +1065,9 @@ class JSONOpenAPIRenderer(BaseRenderer):
|
|||
charset = None
|
||||
encoder_class = encoders.JSONEncoder
|
||||
format = 'openapi-json'
|
||||
ensure_ascii = not api_settings.UNICODE_JSON
|
||||
|
||||
def render(self, data, media_type=None, renderer_context=None):
|
||||
return json.dumps(data, cls=self.encoder_class, indent=2).encode('utf-8')
|
||||
return json.dumps(
|
||||
data, cls=self.encoder_class, indent=2,
|
||||
ensure_ascii=self.ensure_ascii).encode('utf-8')
|
||||
|
|