mirror of
https://github.com/encode/django-rest-framework.git
synced 2025-01-24 00:04:16 +03:00
Merge branch 'restframework2' into rest-framework-2-merge
Conflicts: .gitignore .travis.yml AUTHORS README.rst djangorestframework/mixins.py djangorestframework/renderers.py djangorestframework/resources.py djangorestframework/serializer.py djangorestframework/templates/djangorestframework/base.html djangorestframework/templates/djangorestframework/login.html djangorestframework/templatetags/add_query_param.py djangorestframework/tests/accept.py djangorestframework/tests/authentication.py djangorestframework/tests/content.py djangorestframework/tests/reverse.py djangorestframework/tests/serializer.py djangorestframework/views.py docs/examples.rst docs/examples/blogpost.rst docs/examples/modelviews.rst docs/examples/objectstore.rst docs/examples/permissions.rst docs/examples/pygments.rst docs/examples/views.rst docs/howto/alternativeframeworks.rst docs/howto/mixin.rst docs/howto/reverse.rst docs/howto/usingurllib2.rst docs/index.rst docs/topics/release-notes.md examples/sandbox/views.py rest_framework/__init__.py rest_framework/compat.py rest_framework/utils/breadcrumbs.py setup.py
This commit is contained in:
commit
9b30dab4f7
16
.gitignore
vendored
16
.gitignore
vendored
|
@ -3,17 +3,11 @@
|
|||
*~
|
||||
.*
|
||||
|
||||
coverage.xml
|
||||
env
|
||||
docs/build
|
||||
html
|
||||
htmlcov
|
||||
examples/media/pygments/[A-Za-z0-9]*
|
||||
examples/media/objectstore/[A-Za-z0-9]*
|
||||
build/*
|
||||
dist/*
|
||||
xmlrunner/*
|
||||
djangorestframework.egg-info/*
|
||||
html/
|
||||
coverage/
|
||||
build/
|
||||
dist/
|
||||
rest_framework.egg-info/
|
||||
MANIFEST
|
||||
|
||||
!.gitignore
|
||||
|
|
21
.travis.yml
21
.travis.yml
|
@ -5,22 +5,13 @@ python:
|
|||
- "2.7"
|
||||
|
||||
env:
|
||||
- DJANGO=https://github.com/django/django/zipball/master TESTS='python setup.py test'
|
||||
- DJANGO=django==1.4.1 --use-mirrors TESTS='python setup.py test'
|
||||
- DJANGO=django==1.3.3 --use-mirrors TESTS='python setup.py test'
|
||||
- DJANGO=https://github.com/django/django/zipball/master
|
||||
- DJANGO=django==1.4.1 --use-mirrors
|
||||
- DJANGO=django==1.3.3 --use-mirrors
|
||||
|
||||
# command to install dependencies, e.g. pip install -r requirements.txt --use-mirrors
|
||||
install:
|
||||
- pip install $DJANGO
|
||||
- pip install -e . --use-mirrors
|
||||
- pip install -r requirements.txt
|
||||
- pip install $DJANGO
|
||||
- export PYTHONPATH=.
|
||||
|
||||
# command to run tests, e.g. python setup.py test
|
||||
script:
|
||||
- $TESTS
|
||||
|
||||
# Examples tests, currently dropped to keep the number of configurations sane
|
||||
# - DJANGO=https://github.com/django/django/zipball/master TESTS='python examples/runtests.py'
|
||||
# - DJANGO=django==1.4.1 --use-mirrors TESTS='python examples/runtests.py'
|
||||
# - DJANGO=django==1.3.3 --use-mirrors TESTS='python examples/runtests.py'
|
||||
# - pip install -r examples/requirements.txt
|
||||
- python rest_framework/runtests/runtests.py
|
||||
|
|
48
AUTHORS
48
AUTHORS
|
@ -1,48 +0,0 @@
|
|||
Tom Christie <tomchristie> - tom@tomchristie.com, @_tomchristie
|
||||
Marko Tibold <markotibold> (Additional thanks for providing & managing the Jenkins CI Server)
|
||||
Paul Bagwell <pbgwl>
|
||||
Sébastien Piquemal <sebpiq>
|
||||
Carmen Wick <cwick>
|
||||
Alex Ehlke <aehlke>
|
||||
Alen Mujezinovic <flashingpumpkin>
|
||||
Carles Barrobés <txels>
|
||||
Michael Fötsch <mfoetsch>
|
||||
David Larlet <david>
|
||||
Andrew Straw <astraw>
|
||||
Zeth <zeth>
|
||||
Fernando Zunino <fzunino>
|
||||
Jens Alm <ulmus>
|
||||
Craig Blaszczyk <jakul>
|
||||
Garcia Solero <garciasolero>
|
||||
Tom Drummond <devioustree>
|
||||
Danilo Bargen <gwrtheyrn>
|
||||
Andrew McCloud <amccloud>
|
||||
Thomas Steinacher <thomasst>
|
||||
Meurig Freeman <meurig>
|
||||
Anthony Nemitz <anemitz>
|
||||
Ewoud Kohl van Wijngaarden <ekohl>
|
||||
Michael Ding <yandy>
|
||||
Mjumbe Poe <mjumbewu>
|
||||
Natim <natim>
|
||||
Sebastian Żurek <sebzur>
|
||||
Benoit C <dzen>
|
||||
Chris Pickett <bunchesofdonald>
|
||||
Ben Timby <btimby>
|
||||
Michele Lazzeri <michelelazzeri-nextage>
|
||||
Camille Harang <mammique>
|
||||
Paul Oswald <poswald>
|
||||
Sean C. Farley <scfarley>
|
||||
Daniel Izquierdo <izquierdo>
|
||||
Can Yavuz <tschan>
|
||||
Shawn Lewis <shawnlewis>
|
||||
Adam Ness <greylurk>
|
||||
<yetist>
|
||||
Max Arnold <max-arnold>
|
||||
Ralph Broenink <ralphje>
|
||||
Simon Pantzare <pilt>
|
||||
Michael Barrett <phobologic>
|
||||
|
||||
THANKS TO:
|
||||
|
||||
Jesper Noehr <jespern> & the django-piston contributors for providing the starting point for this project.
|
||||
And of course, to the Django core team and the Django community at large. You guys rock.
|
22
LICENSE
22
LICENSE
|
@ -1,22 +0,0 @@
|
|||
Copyright (c) 2011, Tom Christie
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
Redistributions in binary form must reproduce the above copyright notice, this
|
||||
list of conditions and the following disclaimer in the documentation and/or
|
||||
other materials provided with the distribution.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
@ -1,5 +1,2 @@
|
|||
recursive-include djangorestframework/static *.ico *.txt *.css
|
||||
recursive-include djangorestframework/templates *.txt *.html
|
||||
recursive-include examples .keep *.py *.txt
|
||||
recursive-include docs *.py *.rst *.html *.txt
|
||||
include AUTHORS LICENSE CHANGELOG.rst requirements.txt tox.ini
|
||||
recursive-include rest_framework/static *.js *.css *.png
|
||||
recursive-include rest_framework/templates *.txt *.html
|
||||
|
|
101
README.md
Normal file
101
README.md
Normal file
|
@ -0,0 +1,101 @@
|
|||
# Django REST framework
|
||||
|
||||
**A toolkit for building well-connected, self-describing web APIs.**
|
||||
|
||||
**Author:** Tom Christie. [Follow me on Twitter][twitter]
|
||||
|
||||
[![build-status-image]][travis]
|
||||
|
||||
---
|
||||
|
||||
**Full documentation for REST framework is available on [http://django-rest-framework.org][docs].**
|
||||
|
||||
Note that this is the 2.0 version of REST framework. If you are looking for earlier versions please see the [0.4.x branch][0.4] on GitHub.
|
||||
|
||||
---
|
||||
|
||||
# Overview
|
||||
|
||||
Django REST framework is a lightweight library that makes it easy to build Web APIs. It is designed as a modular and easy to customize architecture, based on Django's class based views.
|
||||
|
||||
Web APIs built using REST framework are fully self-describing and web browseable - a huge useability win for your developers. It also supports a wide range of media types, authentication and permission policies out of the box.
|
||||
|
||||
If you are considering using REST framework for your API, we recommend reading the [REST framework 2 announcment][rest-framework-2-announcement] which gives a good overview of the framework and it's capabilities.
|
||||
|
||||
There is also a sandbox API you can use for testing purposes, [available here][sandbox].
|
||||
|
||||
# Requirements
|
||||
|
||||
* Python (2.6, 2.7)
|
||||
* Django (1.3, 1.4, 1.5)
|
||||
|
||||
**Optional:**
|
||||
|
||||
* [Markdown] - Markdown support for the self describing API.
|
||||
* [PyYAML] - YAML content type support.
|
||||
|
||||
# Installation
|
||||
|
||||
Install using `pip`...
|
||||
|
||||
pip install djangorestframework
|
||||
|
||||
...or clone the project from github.
|
||||
|
||||
git clone git@github.com:tomchristie/django-rest-framework.git
|
||||
pip install -r requirements.txt
|
||||
|
||||
# Development
|
||||
|
||||
To build the docs.
|
||||
|
||||
./mkdocs.py
|
||||
|
||||
To run the tests.
|
||||
|
||||
./rest_framework/runtests/runtests.py
|
||||
|
||||
# Changelog
|
||||
|
||||
## 2.0.0
|
||||
|
||||
* Redesign of core components.
|
||||
* Fix **all of the things**.
|
||||
|
||||
# License
|
||||
|
||||
Copyright (c) 2011, Tom Christie
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
Redistributions in binary form must reproduce the above copyright notice, this
|
||||
list of conditions and the following disclaimer in the documentation and/or
|
||||
other materials provided with the distribution.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
[build-status-image]: https://secure.travis-ci.org/tomchristie/django-rest-framework.png?branch=restframework2
|
||||
[travis]: http://travis-ci.org/tomchristie/django-rest-framework?branch=restframework2
|
||||
[twitter]: https://twitter.com/_tomchristie
|
||||
[0.4]: https://github.com/tomchristie/django-rest-framework/tree/0.4.X
|
||||
[sandbox]: http://restframework.herokuapp.com/
|
||||
[rest-framework-2-announcement]: topics/rest-framework-2-announcement.md
|
||||
|
||||
[docs]: http://tomchristie.github.com/django-rest-framework/
|
||||
[urlobject]: https://github.com/zacharyvoase/urlobject
|
||||
[markdown]: http://pypi.python.org/pypi/Markdown/
|
||||
[pyyaml]: http://pypi.python.org/pypi/PyYAML
|
||||
|
90
README.rst
90
README.rst
|
@ -1,90 +0,0 @@
|
|||
Django REST framework
|
||||
=====================
|
||||
|
||||
**Django REST framework makes it easy to build well-connected, self-describing RESTful Web APIs.**
|
||||
|
||||
**Author:** Tom Christie. `Follow me on Twitter <https://twitter.com/_tomchristie>`_.
|
||||
|
||||
:build status: |build-image|
|
||||
|
||||
.. |build-image| image:: https://secure.travis-ci.org/tomchristie/django-rest-framework.png?branch=master
|
||||
:target: https://secure.travis-ci.org/tomchristie/django-rest-framework
|
||||
|
||||
**Important!** REST framework 2.0 is due to be released to PyPI by the end of October.
|
||||
If you are considering building a new API using REST framework you should start working
|
||||
with the `restframework2` branch, and refering to the upcoming `REST framework 2 docs <http://tomchristie.github.com/django-rest-framework>`_.
|
||||
|
||||
Overview
|
||||
========
|
||||
|
||||
Features:
|
||||
|
||||
* Creates awesome self-describing *web browse-able* APIs.
|
||||
* Clean, modular design, using Django's class based views.
|
||||
* Easily extended for custom content types, serialization formats and authentication policies.
|
||||
* Stable, well tested code-base.
|
||||
* Active developer community.
|
||||
|
||||
Full documentation for the project is available at http://django-rest-framework.org
|
||||
|
||||
Issue tracking is on `GitHub <https://github.com/tomchristie/django-rest-framework/issues>`_.
|
||||
General questions should be taken to the `discussion group <http://groups.google.com/group/django-rest-framework>`_.
|
||||
|
||||
Requirements:
|
||||
|
||||
* Python 2.6+
|
||||
* Django 1.3+
|
||||
|
||||
|
||||
Installation Notes
|
||||
==================
|
||||
|
||||
To clone the project from GitHub using git::
|
||||
|
||||
git clone git@github.com:tomchristie/django-rest-framework.git
|
||||
|
||||
|
||||
To install django-rest-framework in a virtualenv environment::
|
||||
|
||||
cd django-rest-framework
|
||||
virtualenv --no-site-packages --distribute env
|
||||
source env/bin/activate
|
||||
pip install -r requirements.txt # django, coverage
|
||||
|
||||
|
||||
To run the tests::
|
||||
|
||||
export PYTHONPATH=. # Ensure djangorestframework is on the PYTHONPATH
|
||||
python djangorestframework/runtests/runtests.py
|
||||
|
||||
|
||||
To run the test coverage report::
|
||||
|
||||
export PYTHONPATH=. # Ensure djangorestframework is on the PYTHONPATH
|
||||
python djangorestframework/runtests/runcoverage.py
|
||||
|
||||
|
||||
To run the examples::
|
||||
|
||||
pip install -r examples/requirements.txt # pygments, httplib2, markdown
|
||||
cd examples
|
||||
export PYTHONPATH=..
|
||||
python manage.py syncdb
|
||||
python manage.py runserver
|
||||
|
||||
|
||||
To build the documentation::
|
||||
|
||||
pip install -r docs/requirements.txt # sphinx
|
||||
sphinx-build -c docs -b html -d docs/build docs html
|
||||
|
||||
|
||||
To run the tests against the full set of supported configurations::
|
||||
|
||||
deactivate # Ensure we are not currently running in a virtualenv
|
||||
tox
|
||||
|
||||
|
||||
To create the sdist packages::
|
||||
|
||||
python setup.py sdist --formats=gztar,zip
|
|
@ -1,101 +0,0 @@
|
|||
"""
|
||||
The :mod:`authentication` module provides a set of pluggable authentication classes.
|
||||
|
||||
Authentication behavior is provided by mixing the :class:`mixins.AuthMixin` class into a :class:`View` class.
|
||||
|
||||
The set of authentication methods which are used is then specified by setting the
|
||||
:attr:`authentication` attribute on the :class:`View` class, and listing a set of :class:`authentication` classes.
|
||||
"""
|
||||
|
||||
from django.contrib.auth import authenticate
|
||||
from djangorestframework.compat import CsrfViewMiddleware
|
||||
import base64
|
||||
|
||||
__all__ = (
|
||||
'BaseAuthentication',
|
||||
'BasicAuthentication',
|
||||
'UserLoggedInAuthentication'
|
||||
)
|
||||
|
||||
|
||||
class BaseAuthentication(object):
|
||||
"""
|
||||
All authentication classes should extend BaseAuthentication.
|
||||
"""
|
||||
|
||||
def __init__(self, view):
|
||||
"""
|
||||
:class:`Authentication` classes are always passed the current view on creation.
|
||||
"""
|
||||
self.view = view
|
||||
|
||||
def authenticate(self, request):
|
||||
"""
|
||||
Authenticate the :obj:`request` and return a :obj:`User` or :const:`None`. [*]_
|
||||
|
||||
.. [*] The authentication context *will* typically be a :obj:`User`,
|
||||
but it need not be. It can be any user-like object so long as the
|
||||
permissions classes (see the :mod:`permissions` module) on the view can
|
||||
handle the object and use it to determine if the request has the required
|
||||
permissions or not.
|
||||
|
||||
This can be an important distinction if you're implementing some token
|
||||
based authentication mechanism, where the authentication context
|
||||
may be more involved than simply mapping to a :obj:`User`.
|
||||
"""
|
||||
return None
|
||||
|
||||
|
||||
class BasicAuthentication(BaseAuthentication):
|
||||
"""
|
||||
Use HTTP Basic authentication.
|
||||
"""
|
||||
|
||||
def authenticate(self, request):
|
||||
"""
|
||||
Returns a :obj:`User` if a correct username and password have been supplied
|
||||
using HTTP Basic authentication. Otherwise returns :const:`None`.
|
||||
"""
|
||||
from django.utils.encoding import smart_unicode, DjangoUnicodeDecodeError
|
||||
|
||||
if 'HTTP_AUTHORIZATION' in request.META:
|
||||
auth = request.META['HTTP_AUTHORIZATION'].split()
|
||||
if len(auth) == 2 and auth[0].lower() == "basic":
|
||||
try:
|
||||
auth_parts = base64.b64decode(auth[1]).partition(':')
|
||||
except TypeError:
|
||||
return None
|
||||
|
||||
try:
|
||||
uname, passwd = smart_unicode(auth_parts[0]), smart_unicode(auth_parts[2])
|
||||
except DjangoUnicodeDecodeError:
|
||||
return None
|
||||
|
||||
user = authenticate(username=uname, password=passwd)
|
||||
if user is not None and user.is_active:
|
||||
return user
|
||||
return None
|
||||
|
||||
|
||||
class UserLoggedInAuthentication(BaseAuthentication):
|
||||
"""
|
||||
Use Django's session framework for authentication.
|
||||
"""
|
||||
|
||||
def authenticate(self, request):
|
||||
"""
|
||||
Returns a :obj:`User` if the request session currently has a logged in user.
|
||||
Otherwise returns :const:`None`.
|
||||
"""
|
||||
self.view.DATA # Make sure our generic parsing runs first
|
||||
|
||||
if getattr(request, 'user', None) and request.user.is_active:
|
||||
# Enforce CSRF validation for session based authentication.
|
||||
resp = CsrfViewMiddleware().process_view(request, None, (), {})
|
||||
|
||||
if resp is None: # csrf passed
|
||||
return request.user
|
||||
return None
|
||||
|
||||
|
||||
# TODO: TokenAuthentication, DigestAuthentication, OAuthAuthentication
|
|
@ -1,736 +0,0 @@
|
|||
"""
|
||||
The :mod:`mixins` module provides a set of reusable `mixin`
|
||||
classes that can be added to a `View`.
|
||||
"""
|
||||
|
||||
from django.contrib.auth.models import AnonymousUser
|
||||
from django.core.paginator import Paginator
|
||||
from django.db.models.fields.related import ForeignKey
|
||||
from django.http import HttpResponse
|
||||
from urlobject import URLObject
|
||||
|
||||
from djangorestframework import status
|
||||
from djangorestframework.renderers import BaseRenderer
|
||||
from djangorestframework.resources import Resource, FormResource, ModelResource
|
||||
from djangorestframework.response import Response, ErrorResponse
|
||||
from djangorestframework.utils import as_tuple, MSIE_USER_AGENT_REGEX
|
||||
from djangorestframework.utils.mediatypes import is_form_media_type, order_by_precedence
|
||||
|
||||
from StringIO import StringIO
|
||||
|
||||
|
||||
__all__ = (
|
||||
# Base behavior mixins
|
||||
'RequestMixin',
|
||||
'ResponseMixin',
|
||||
'AuthMixin',
|
||||
'ResourceMixin',
|
||||
# Model behavior mixins
|
||||
'ReadModelMixin',
|
||||
'CreateModelMixin',
|
||||
'UpdateModelMixin',
|
||||
'DeleteModelMixin',
|
||||
'ListModelMixin',
|
||||
'PaginatorMixin'
|
||||
)
|
||||
|
||||
|
||||
########## Request Mixin ##########
|
||||
|
||||
class RequestMixin(object):
|
||||
"""
|
||||
`Mixin` class to provide request parsing behavior.
|
||||
"""
|
||||
|
||||
_USE_FORM_OVERLOADING = True
|
||||
_METHOD_PARAM = '_method'
|
||||
_CONTENTTYPE_PARAM = '_content_type'
|
||||
_CONTENT_PARAM = '_content'
|
||||
|
||||
parsers = ()
|
||||
"""
|
||||
The set of request parsers that the view can handle.
|
||||
|
||||
Should be a tuple/list of classes as described in the :mod:`parsers` module.
|
||||
"""
|
||||
|
||||
@property
|
||||
def method(self):
|
||||
"""
|
||||
Returns the HTTP method.
|
||||
|
||||
This should be used instead of just reading :const:`request.method`, as it allows the `method`
|
||||
to be overridden by using a hidden `form` field on a form POST request.
|
||||
"""
|
||||
if not hasattr(self, '_method'):
|
||||
self._load_method_and_content_type()
|
||||
return self._method
|
||||
|
||||
@property
|
||||
def content_type(self):
|
||||
"""
|
||||
Returns the content type header.
|
||||
|
||||
This should be used instead of ``request.META.get('HTTP_CONTENT_TYPE')``,
|
||||
as it allows the content type to be overridden by using a hidden form
|
||||
field on a form POST request.
|
||||
"""
|
||||
if not hasattr(self, '_content_type'):
|
||||
self._load_method_and_content_type()
|
||||
return self._content_type
|
||||
|
||||
@property
|
||||
def DATA(self):
|
||||
"""
|
||||
Parses the request body and returns the data.
|
||||
|
||||
Similar to ``request.POST``, except that it handles arbitrary parsers,
|
||||
and also works on methods other than POST (eg PUT).
|
||||
"""
|
||||
if not hasattr(self, '_data'):
|
||||
self._load_data_and_files()
|
||||
return self._data
|
||||
|
||||
@property
|
||||
def FILES(self):
|
||||
"""
|
||||
Parses the request body and returns the files.
|
||||
Similar to ``request.FILES``, except that it handles arbitrary parsers,
|
||||
and also works on methods other than POST (eg PUT).
|
||||
"""
|
||||
if not hasattr(self, '_files'):
|
||||
self._load_data_and_files()
|
||||
return self._files
|
||||
|
||||
def _load_data_and_files(self):
|
||||
"""
|
||||
Parse the request content into self.DATA and self.FILES.
|
||||
"""
|
||||
if not hasattr(self, '_content_type'):
|
||||
self._load_method_and_content_type()
|
||||
|
||||
if not hasattr(self, '_data'):
|
||||
(self._data, self._files) = self._parse(self._get_stream(), self._content_type)
|
||||
|
||||
def _load_method_and_content_type(self):
|
||||
"""
|
||||
Set the method and content_type, and then check if they've been overridden.
|
||||
"""
|
||||
self._method = self.request.method
|
||||
self._content_type = self.request.META.get('HTTP_CONTENT_TYPE', self.request.META.get('CONTENT_TYPE', ''))
|
||||
self._perform_form_overloading()
|
||||
|
||||
def _get_stream(self):
|
||||
"""
|
||||
Returns an object that may be used to stream the request content.
|
||||
"""
|
||||
request = self.request
|
||||
|
||||
try:
|
||||
content_length = int(request.META.get('CONTENT_LENGTH', request.META.get('HTTP_CONTENT_LENGTH')))
|
||||
except (ValueError, TypeError):
|
||||
content_length = 0
|
||||
|
||||
# TODO: Add 1.3's LimitedStream to compat and use that.
|
||||
# NOTE: Currently only supports parsing request body as a stream with 1.3
|
||||
if content_length == 0:
|
||||
return None
|
||||
elif hasattr(request, 'read'):
|
||||
return request
|
||||
return StringIO(request.raw_post_data)
|
||||
|
||||
def _perform_form_overloading(self):
|
||||
"""
|
||||
If this is a form POST request, then we need to check if the method and content/content_type have been
|
||||
overridden by setting them in hidden form fields or not.
|
||||
"""
|
||||
|
||||
# We only need to use form overloading on form POST requests.
|
||||
if not self._USE_FORM_OVERLOADING or self._method != 'POST' or not is_form_media_type(self._content_type):
|
||||
return
|
||||
|
||||
# At this point we're committed to parsing the request as form data.
|
||||
self._data = data = self.request.POST.copy()
|
||||
self._files = self.request.FILES
|
||||
|
||||
# Method overloading - change the method and remove the param from the content.
|
||||
if self._METHOD_PARAM in data:
|
||||
# NOTE: unlike `get`, `pop` on a `QueryDict` seems to return a list of values.
|
||||
self._method = self._data.pop(self._METHOD_PARAM)[0].upper()
|
||||
|
||||
# Content overloading - modify the content type, and re-parse.
|
||||
if self._CONTENT_PARAM in data and self._CONTENTTYPE_PARAM in data:
|
||||
self._content_type = self._data.pop(self._CONTENTTYPE_PARAM)[0]
|
||||
stream = StringIO(self._data.pop(self._CONTENT_PARAM)[0])
|
||||
(self._data, self._files) = self._parse(stream, self._content_type)
|
||||
|
||||
def _parse(self, stream, content_type):
|
||||
"""
|
||||
Parse the request content.
|
||||
|
||||
May raise a 415 ErrorResponse (Unsupported Media Type), or a 400 ErrorResponse (Bad Request).
|
||||
"""
|
||||
if stream is None or content_type is None:
|
||||
return (None, None)
|
||||
|
||||
parsers = as_tuple(self.parsers)
|
||||
|
||||
for parser_cls in parsers:
|
||||
parser = parser_cls(self)
|
||||
if parser.can_handle_request(content_type):
|
||||
return parser.parse(stream)
|
||||
|
||||
raise ErrorResponse(status.HTTP_415_UNSUPPORTED_MEDIA_TYPE,
|
||||
{'detail': 'Unsupported media type in request \'%s\'.' %
|
||||
content_type})
|
||||
|
||||
@property
|
||||
def _parsed_media_types(self):
|
||||
"""
|
||||
Return a list of all the media types that this view can parse.
|
||||
"""
|
||||
return [parser.media_type for parser in self.parsers]
|
||||
|
||||
@property
|
||||
def _default_parser(self):
|
||||
"""
|
||||
Return the view's default parser class.
|
||||
"""
|
||||
return self.parsers[0]
|
||||
|
||||
|
||||
########## ResponseMixin ##########
|
||||
|
||||
class ResponseMixin(object):
|
||||
"""
|
||||
Adds behavior for pluggable `Renderers` to a :class:`views.View` class.
|
||||
|
||||
Default behavior is to use standard HTTP Accept header content negotiation.
|
||||
Also supports overriding the content type by specifying an ``_accept=`` parameter in the URL.
|
||||
Ignores Accept headers from Internet Explorer user agents and uses a sensible browser Accept header instead.
|
||||
"""
|
||||
|
||||
_ACCEPT_QUERY_PARAM = '_accept' # Allow override of Accept header in URL query params
|
||||
_IGNORE_IE_ACCEPT_HEADER = True
|
||||
|
||||
renderers = ()
|
||||
"""
|
||||
The set of response renderers that the view can handle.
|
||||
|
||||
Should be a tuple/list of classes as described in the :mod:`renderers` module.
|
||||
"""
|
||||
|
||||
def get_renderers(self):
|
||||
"""
|
||||
Return an iterable of available renderers. Override if you want to change
|
||||
this list at runtime, say depending on what settings you have enabled.
|
||||
"""
|
||||
return self.renderers
|
||||
|
||||
# TODO: wrap this behavior around dispatch(), ensuring it works
|
||||
# out of the box with existing Django classes that use render_to_response.
|
||||
def render(self, response):
|
||||
"""
|
||||
Takes a :obj:`Response` object and returns an :obj:`HttpResponse`.
|
||||
"""
|
||||
self.response = response
|
||||
|
||||
try:
|
||||
renderer, media_type = self._determine_renderer(self.request)
|
||||
except ErrorResponse, exc:
|
||||
renderer = self._default_renderer(self)
|
||||
media_type = renderer.media_type
|
||||
response = exc.response
|
||||
|
||||
# Set the media type of the response
|
||||
# Note that the renderer *could* override it in .render() if required.
|
||||
response.media_type = renderer.media_type
|
||||
|
||||
# Serialize the response content
|
||||
if response.has_content_body:
|
||||
content = renderer.render(response.cleaned_content, media_type)
|
||||
else:
|
||||
content = renderer.render()
|
||||
|
||||
# Build the HTTP Response
|
||||
resp = HttpResponse(content, mimetype=response.media_type, status=response.status)
|
||||
for (key, val) in response.headers.items():
|
||||
resp[key] = val
|
||||
|
||||
return resp
|
||||
|
||||
def _determine_renderer(self, request):
|
||||
"""
|
||||
Determines the appropriate renderer for the output, given the client's 'Accept' header,
|
||||
and the :attr:`renderers` set on this class.
|
||||
|
||||
Returns a 2-tuple of `(renderer, media_type)`
|
||||
|
||||
See: RFC 2616, Section 14 - http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
|
||||
"""
|
||||
|
||||
if self._ACCEPT_QUERY_PARAM and request.GET.get(self._ACCEPT_QUERY_PARAM, None):
|
||||
# Use _accept parameter override
|
||||
accept_list = [request.GET.get(self._ACCEPT_QUERY_PARAM)]
|
||||
elif (self._IGNORE_IE_ACCEPT_HEADER and
|
||||
'HTTP_USER_AGENT' in request.META and
|
||||
MSIE_USER_AGENT_REGEX.match(request.META['HTTP_USER_AGENT']) and
|
||||
request.META.get('HTTP_X_REQUESTED_WITH', '') != 'XMLHttpRequest'):
|
||||
# Ignore MSIE's broken accept behavior and do something sensible instead
|
||||
accept_list = ['text/html', '*/*']
|
||||
elif 'HTTP_ACCEPT' in request.META:
|
||||
# Use standard HTTP Accept negotiation
|
||||
accept_list = [token.strip() for token in request.META['HTTP_ACCEPT'].split(',')]
|
||||
else:
|
||||
# No accept header specified
|
||||
accept_list = ['*/*']
|
||||
|
||||
# Check the acceptable media types against each renderer,
|
||||
# attempting more specific media types first
|
||||
# NB. The inner loop here isn't as bad as it first looks :)
|
||||
# Worst case is we're looping over len(accept_list) * len(self.renderers)
|
||||
renderers = [renderer_cls(self) for renderer_cls in self.get_renderers()]
|
||||
|
||||
for accepted_media_type_lst in order_by_precedence(accept_list):
|
||||
for renderer in renderers:
|
||||
for accepted_media_type in accepted_media_type_lst:
|
||||
if renderer.can_handle_response(accepted_media_type):
|
||||
return renderer, accepted_media_type
|
||||
|
||||
# No acceptable renderers were found
|
||||
raise ErrorResponse(status.HTTP_406_NOT_ACCEPTABLE,
|
||||
{'detail': 'Could not satisfy the client\'s Accept header',
|
||||
'available_types': self._rendered_media_types})
|
||||
|
||||
@property
|
||||
def _rendered_media_types(self):
|
||||
"""
|
||||
Return an list of all the media types that this view can render.
|
||||
"""
|
||||
return [renderer.media_type for renderer in self.renderers]
|
||||
|
||||
@property
|
||||
def _rendered_formats(self):
|
||||
"""
|
||||
Return a list of all the formats that this view can render.
|
||||
"""
|
||||
return [renderer.format for renderer in self.renderers]
|
||||
|
||||
@property
|
||||
def _default_renderer(self):
|
||||
"""
|
||||
Return the view's default renderer class.
|
||||
"""
|
||||
return self.renderers[0]
|
||||
|
||||
|
||||
########## Auth Mixin ##########
|
||||
|
||||
class AuthMixin(object):
|
||||
"""
|
||||
Simple :class:`mixin` class to add authentication and permission checking to a :class:`View` class.
|
||||
"""
|
||||
|
||||
authentication = ()
|
||||
"""
|
||||
The set of authentication types that this view can handle.
|
||||
|
||||
Should be a tuple/list of classes as described in the :mod:`authentication` module.
|
||||
"""
|
||||
|
||||
permissions = ()
|
||||
"""
|
||||
The set of permissions that will be enforced on this view.
|
||||
|
||||
Should be a tuple/list of classes as described in the :mod:`permissions` module.
|
||||
"""
|
||||
|
||||
@property
|
||||
def user(self):
|
||||
"""
|
||||
Returns the :obj:`user` for the current request, as determined by the set of
|
||||
:class:`authentication` classes applied to the :class:`View`.
|
||||
"""
|
||||
if not hasattr(self, '_user'):
|
||||
self._user = self._authenticate()
|
||||
return self._user
|
||||
|
||||
def _authenticate(self):
|
||||
"""
|
||||
Attempt to authenticate the request using each authentication class in turn.
|
||||
Returns a ``User`` object, which may be ``AnonymousUser``.
|
||||
"""
|
||||
for authentication_cls in self.authentication:
|
||||
authentication = authentication_cls(self)
|
||||
user = authentication.authenticate(self.request)
|
||||
if user:
|
||||
return user
|
||||
return AnonymousUser()
|
||||
|
||||
# TODO: wrap this behavior around dispatch()
|
||||
def _check_permissions(self):
|
||||
"""
|
||||
Check user permissions and either raise an ``ErrorResponse`` or return.
|
||||
"""
|
||||
user = self.user
|
||||
for permission_cls in self.permissions:
|
||||
permission = permission_cls(self)
|
||||
permission.check_permission(user)
|
||||
|
||||
|
||||
########## Resource Mixin ##########
|
||||
|
||||
class ResourceMixin(object):
|
||||
"""
|
||||
Provides request validation and response filtering behavior.
|
||||
|
||||
Should be a class as described in the :mod:`resources` module.
|
||||
|
||||
The :obj:`resource` is an object that maps a view onto it's representation on the server.
|
||||
|
||||
It provides validation on the content of incoming requests,
|
||||
and filters the object representation into a serializable object for the response.
|
||||
"""
|
||||
resource = None
|
||||
|
||||
@property
|
||||
def CONTENT(self):
|
||||
"""
|
||||
Returns the cleaned, validated request content.
|
||||
|
||||
May raise an :class:`response.ErrorResponse` with status code 400 (Bad Request).
|
||||
"""
|
||||
if not hasattr(self, '_content'):
|
||||
self._content = self.validate_request(self.DATA, self.FILES)
|
||||
return self._content
|
||||
|
||||
@property
|
||||
def PARAMS(self):
|
||||
"""
|
||||
Returns the cleaned, validated query parameters.
|
||||
|
||||
May raise an :class:`response.ErrorResponse` with status code 400 (Bad Request).
|
||||
"""
|
||||
return self.validate_request(self.request.GET)
|
||||
|
||||
@property
|
||||
def _resource(self):
|
||||
if self.resource:
|
||||
return self.resource(self)
|
||||
elif getattr(self, 'model', None):
|
||||
return ModelResource(self)
|
||||
elif getattr(self, 'form', None):
|
||||
return FormResource(self)
|
||||
elif getattr(self, '%s_form' % self.method.lower(), None):
|
||||
return FormResource(self)
|
||||
return Resource(self)
|
||||
|
||||
def validate_request(self, data, files=None):
|
||||
"""
|
||||
Given the request *data* and optional *files*, return the cleaned, validated content.
|
||||
May raise an :class:`response.ErrorResponse` with status code 400 (Bad Request) on failure.
|
||||
"""
|
||||
return self._resource.validate_request(data, files)
|
||||
|
||||
def filter_response(self, obj):
|
||||
"""
|
||||
Given the response content, filter it into a serializable object.
|
||||
"""
|
||||
return self._resource.filter_response(obj)
|
||||
|
||||
def get_bound_form(self, content=None, method=None):
|
||||
if hasattr(self._resource, 'get_bound_form'):
|
||||
return self._resource.get_bound_form(content, method=method)
|
||||
else:
|
||||
return None
|
||||
|
||||
|
||||
########## Model Mixins ##########
|
||||
|
||||
class ModelMixin(object):
|
||||
""" Implements mechanisms used by other classes (like *ModelMixin group) to
|
||||
define a query that represents Model instances the Mixin is working with.
|
||||
|
||||
If a *ModelMixin is going to retrive an instance (or queryset) using args and kwargs
|
||||
passed by as URL arguments, it should provied arguments to objects.get and objects.filter
|
||||
methods wrapped in by `build_query`
|
||||
|
||||
If a *ModelMixin is going to create/update an instance get_instance_data
|
||||
handles the instance data creation/preaparation.
|
||||
"""
|
||||
|
||||
queryset = None
|
||||
|
||||
def get_query_kwargs(self, *args, **kwargs):
|
||||
"""
|
||||
Return a dict of kwargs that will be used to build the
|
||||
model instance retrieval or to filter querysets.
|
||||
"""
|
||||
|
||||
kwargs = dict(kwargs)
|
||||
|
||||
# If the URLconf includes a .(?P<format>\w+) pattern to match against
|
||||
# a .json, .xml suffix, then drop the 'format' kwarg before
|
||||
# constructing the query.
|
||||
if BaseRenderer._FORMAT_QUERY_PARAM in kwargs:
|
||||
del kwargs[BaseRenderer._FORMAT_QUERY_PARAM]
|
||||
|
||||
return kwargs
|
||||
|
||||
def get_instance_data(self, model, content, **kwargs):
|
||||
"""
|
||||
Returns the dict with the data for model instance creation/update.
|
||||
|
||||
Arguments:
|
||||
- model: model class (django.db.models.Model subclass) to work with
|
||||
- content: a dictionary with instance data
|
||||
- kwargs: a dict of URL provided keyword arguments
|
||||
|
||||
The create/update queries are created basicly with the contet provided
|
||||
with POST/PUT HTML methods and kwargs passed in the URL. This methods
|
||||
simply merges the URL data and the content preaparing the ready-to-use
|
||||
data dictionary.
|
||||
"""
|
||||
|
||||
tmp = dict(kwargs)
|
||||
|
||||
for field in model._meta.fields:
|
||||
if isinstance(field, ForeignKey) and field.name in tmp:
|
||||
# translate 'related_field' kwargs into 'related_field_id'
|
||||
tmp[field.name + '_id'] = tmp[field.name]
|
||||
del tmp[field.name]
|
||||
|
||||
all_kw_args = dict(content.items() + tmp.items())
|
||||
|
||||
return all_kw_args
|
||||
|
||||
def get_instance(self, **kwargs):
|
||||
"""
|
||||
Get a model instance for read/update/delete requests.
|
||||
"""
|
||||
return self.get_queryset().get(**kwargs)
|
||||
|
||||
def get_queryset(self):
|
||||
"""
|
||||
Return the queryset for this view.
|
||||
"""
|
||||
return getattr(self.resource, 'queryset',
|
||||
self.resource.model.objects.all())
|
||||
|
||||
def get_ordering(self):
|
||||
"""
|
||||
Return the ordering for this view.
|
||||
"""
|
||||
return getattr(self.resource, 'ordering', None)
|
||||
|
||||
|
||||
class ReadModelMixin(ModelMixin):
|
||||
"""
|
||||
Behavior to read a `model` instance on GET requests
|
||||
"""
|
||||
def get(self, request, *args, **kwargs):
|
||||
model = self.resource.model
|
||||
query_kwargs = self.get_query_kwargs(request, *args, **kwargs)
|
||||
|
||||
try:
|
||||
self.model_instance = self.get_instance(**query_kwargs)
|
||||
except model.DoesNotExist:
|
||||
raise ErrorResponse(status.HTTP_404_NOT_FOUND)
|
||||
|
||||
return self.model_instance
|
||||
|
||||
|
||||
class CreateModelMixin(ModelMixin):
|
||||
"""
|
||||
Behavior to create a `model` instance on POST requests
|
||||
"""
|
||||
def post(self, request, *args, **kwargs):
|
||||
model = self.resource.model
|
||||
|
||||
# Copy the dict to keep self.CONTENT intact
|
||||
content = dict(self.CONTENT)
|
||||
m2m_data = {}
|
||||
|
||||
for field in model._meta.many_to_many:
|
||||
if field.name in content:
|
||||
m2m_data[field.name] = (
|
||||
field.m2m_reverse_field_name(), content[field.name]
|
||||
)
|
||||
del content[field.name]
|
||||
|
||||
instance = model(**self.get_instance_data(model, content, *args, **kwargs))
|
||||
instance.save()
|
||||
|
||||
for fieldname in m2m_data:
|
||||
manager = getattr(instance, fieldname)
|
||||
|
||||
if hasattr(manager, 'add'):
|
||||
manager.add(*m2m_data[fieldname][1])
|
||||
else:
|
||||
data = {}
|
||||
data[manager.source_field_name] = instance
|
||||
|
||||
for related_item in m2m_data[fieldname][1]:
|
||||
data[m2m_data[fieldname][0]] = related_item
|
||||
manager.through(**data).save()
|
||||
|
||||
headers = {}
|
||||
if hasattr(self.resource, 'url'):
|
||||
headers['Location'] = self.resource(self).url(instance)
|
||||
return Response(status.HTTP_201_CREATED, instance, headers)
|
||||
|
||||
|
||||
class UpdateModelMixin(ModelMixin):
|
||||
"""
|
||||
Behavior to update a `model` instance on PUT requests
|
||||
"""
|
||||
def put(self, request, *args, **kwargs):
|
||||
model = self.resource.model
|
||||
query_kwargs = self.get_query_kwargs(request, *args, **kwargs)
|
||||
|
||||
# TODO: update on the url of a non-existing resource url doesn't work
|
||||
# correctly at the moment - will end up with a new url
|
||||
try:
|
||||
self.model_instance = self.get_instance(**query_kwargs)
|
||||
|
||||
for (key, val) in self.CONTENT.items():
|
||||
setattr(self.model_instance, key, val)
|
||||
except model.DoesNotExist:
|
||||
self.model_instance = model(**self.get_instance_data(model, self.CONTENT, *args, **kwargs))
|
||||
self.model_instance.save()
|
||||
return self.model_instance
|
||||
|
||||
|
||||
class DeleteModelMixin(ModelMixin):
|
||||
"""
|
||||
Behavior to delete a `model` instance on DELETE requests
|
||||
"""
|
||||
def delete(self, request, *args, **kwargs):
|
||||
model = self.resource.model
|
||||
query_kwargs = self.get_query_kwargs(request, *args, **kwargs)
|
||||
|
||||
try:
|
||||
instance = self.get_instance(**query_kwargs)
|
||||
except model.DoesNotExist:
|
||||
raise ErrorResponse(status.HTTP_404_NOT_FOUND, None, {})
|
||||
|
||||
instance.delete()
|
||||
return
|
||||
|
||||
|
||||
class ListModelMixin(ModelMixin):
|
||||
"""
|
||||
Behavior to list a set of `model` instances on GET requests
|
||||
"""
|
||||
|
||||
def get(self, request, *args, **kwargs):
|
||||
queryset = self.get_queryset()
|
||||
ordering = self.get_ordering()
|
||||
query_kwargs = self.get_query_kwargs(request, *args, **kwargs)
|
||||
|
||||
queryset = queryset.filter(**query_kwargs)
|
||||
if ordering:
|
||||
queryset = queryset.order_by(*ordering)
|
||||
|
||||
return queryset
|
||||
|
||||
|
||||
########## Pagination Mixins ##########
|
||||
|
||||
class PaginatorMixin(object):
|
||||
"""
|
||||
Adds pagination support to GET requests
|
||||
Obviously should only be used on lists :)
|
||||
|
||||
A default limit can be set by setting `limit` on the object. This will also
|
||||
be used as the maximum if the client sets the `limit` GET param
|
||||
"""
|
||||
limit = 20
|
||||
|
||||
def get_limit(self):
|
||||
"""
|
||||
Helper method to determine what the `limit` should be
|
||||
"""
|
||||
try:
|
||||
limit = int(self.request.GET.get('limit', self.limit))
|
||||
return min(limit, self.limit)
|
||||
except ValueError:
|
||||
return self.limit
|
||||
|
||||
def url_with_page_number(self, page_number):
|
||||
"""
|
||||
Constructs a url used for getting the next/previous urls
|
||||
"""
|
||||
url = URLObject(self.request.get_full_path())
|
||||
url = url.set_query_param('page', str(page_number))
|
||||
|
||||
limit = self.get_limit()
|
||||
if limit != self.limit:
|
||||
url = url.set_query_param('limit', str(limit))
|
||||
|
||||
return url
|
||||
|
||||
def next(self, page):
|
||||
"""
|
||||
Returns a url to the next page of results (if any)
|
||||
"""
|
||||
if not page.has_next():
|
||||
return None
|
||||
|
||||
return self.url_with_page_number(page.next_page_number())
|
||||
|
||||
def previous(self, page):
|
||||
""" Returns a url to the previous page of results (if any) """
|
||||
if not page.has_previous():
|
||||
return None
|
||||
|
||||
return self.url_with_page_number(page.previous_page_number())
|
||||
|
||||
def serialize_page_info(self, page):
|
||||
"""
|
||||
This is some useful information that is added to the response
|
||||
"""
|
||||
return {
|
||||
'next': self.next(page),
|
||||
'page': page.number,
|
||||
'pages': page.paginator.num_pages,
|
||||
'per_page': self.get_limit(),
|
||||
'previous': self.previous(page),
|
||||
'total': page.paginator.count,
|
||||
}
|
||||
|
||||
def filter_response(self, obj):
|
||||
"""
|
||||
Given the response content, paginate and then serialize.
|
||||
|
||||
The response is modified to include to useful data relating to the number
|
||||
of objects, number of pages, next/previous urls etc. etc.
|
||||
|
||||
The serialised objects are put into `results` on this new, modified
|
||||
response
|
||||
"""
|
||||
|
||||
# We don't want to paginate responses for anything other than GET requests
|
||||
if self.method.upper() != 'GET':
|
||||
return self._resource.filter_response(obj)
|
||||
|
||||
paginator = Paginator(obj, self.get_limit())
|
||||
|
||||
try:
|
||||
page_num = int(self.request.GET.get('page', '1'))
|
||||
except ValueError:
|
||||
raise ErrorResponse(status.HTTP_404_NOT_FOUND,
|
||||
{'detail': 'That page contains no results'})
|
||||
|
||||
if page_num not in paginator.page_range:
|
||||
raise ErrorResponse(status.HTTP_404_NOT_FOUND,
|
||||
{'detail': 'That page contains no results'})
|
||||
|
||||
page = paginator.page(page_num)
|
||||
|
||||
serialized_object_list = self._resource.filter_response(page.object_list)
|
||||
serialized_page_info = self.serialize_page_info(page)
|
||||
|
||||
serialized_page_info['results'] = serialized_object_list
|
||||
|
||||
return serialized_page_info
|
|
@ -1,258 +0,0 @@
|
|||
"""
|
||||
Django supports parsing the content of an HTTP request, but only for form POST requests.
|
||||
That behavior is sufficient for dealing with standard HTML forms, but it doesn't map well
|
||||
to general HTTP requests.
|
||||
|
||||
We need a method to be able to:
|
||||
|
||||
1.) Determine the parsed content on a request for methods other than POST (eg typically also PUT)
|
||||
|
||||
2.) Determine the parsed content on a request for media types other than application/x-www-form-urlencoded
|
||||
and multipart/form-data. (eg also handle multipart/json)
|
||||
"""
|
||||
|
||||
from django.http import QueryDict
|
||||
from django.http.multipartparser import MultiPartParser as DjangoMultiPartParser
|
||||
from django.http.multipartparser import MultiPartParserError
|
||||
from django.utils import simplejson as json
|
||||
from djangorestframework import status
|
||||
from djangorestframework.compat import yaml
|
||||
from djangorestframework.response import ErrorResponse
|
||||
from djangorestframework.utils.mediatypes import media_type_matches
|
||||
from xml.etree import ElementTree as ET
|
||||
from djangorestframework.compat import ETParseError
|
||||
from xml.parsers.expat import ExpatError
|
||||
import datetime
|
||||
import decimal
|
||||
|
||||
|
||||
__all__ = (
|
||||
'BaseParser',
|
||||
'JSONParser',
|
||||
'PlainTextParser',
|
||||
'FormParser',
|
||||
'MultiPartParser',
|
||||
'YAMLParser',
|
||||
'XMLParser'
|
||||
)
|
||||
|
||||
|
||||
class BaseParser(object):
|
||||
"""
|
||||
All parsers should extend :class:`BaseParser`, specifying a :attr:`media_type` attribute,
|
||||
and overriding the :meth:`parse` method.
|
||||
"""
|
||||
|
||||
media_type = None
|
||||
|
||||
def __init__(self, view):
|
||||
"""
|
||||
Initialize the parser with the ``View`` instance as state,
|
||||
in case the parser needs to access any metadata on the :obj:`View` object.
|
||||
"""
|
||||
self.view = view
|
||||
|
||||
def can_handle_request(self, content_type):
|
||||
"""
|
||||
Returns :const:`True` if this parser is able to deal with the given *content_type*.
|
||||
|
||||
The default implementation for this function is to check the *content_type*
|
||||
argument against the :attr:`media_type` attribute set on the class to see if
|
||||
they match.
|
||||
|
||||
This may be overridden to provide for other behavior, but typically you'll
|
||||
instead want to just set the :attr:`media_type` attribute on the class.
|
||||
"""
|
||||
return media_type_matches(self.media_type, content_type)
|
||||
|
||||
def parse(self, stream):
|
||||
"""
|
||||
Given a *stream* to read from, return the deserialized output.
|
||||
Should return a 2-tuple of (data, files).
|
||||
"""
|
||||
raise NotImplementedError("BaseParser.parse() Must be overridden to be implemented.")
|
||||
|
||||
|
||||
class JSONParser(BaseParser):
|
||||
"""
|
||||
Parses JSON-serialized data.
|
||||
"""
|
||||
|
||||
media_type = 'application/json'
|
||||
|
||||
def parse(self, stream):
|
||||
"""
|
||||
Returns a 2-tuple of `(data, files)`.
|
||||
|
||||
`data` will be an object which is the parsed content of the response.
|
||||
`files` will always be `None`.
|
||||
"""
|
||||
try:
|
||||
return (json.load(stream), None)
|
||||
except ValueError, exc:
|
||||
raise ErrorResponse(status.HTTP_400_BAD_REQUEST,
|
||||
{'detail': 'JSON parse error - %s' % unicode(exc)})
|
||||
|
||||
|
||||
class YAMLParser(BaseParser):
|
||||
"""
|
||||
Parses YAML-serialized data.
|
||||
"""
|
||||
|
||||
media_type = 'application/yaml'
|
||||
|
||||
def parse(self, stream):
|
||||
"""
|
||||
Returns a 2-tuple of `(data, files)`.
|
||||
|
||||
`data` will be an object which is the parsed content of the response.
|
||||
`files` will always be `None`.
|
||||
"""
|
||||
try:
|
||||
return (yaml.safe_load(stream), None)
|
||||
except (ValueError, yaml.parser.ParserError), exc:
|
||||
content = {'detail': 'YAML parse error - %s' % unicode(exc)}
|
||||
raise ErrorResponse(status.HTTP_400_BAD_REQUEST, content)
|
||||
|
||||
|
||||
class PlainTextParser(BaseParser):
|
||||
"""
|
||||
Plain text parser.
|
||||
"""
|
||||
|
||||
media_type = 'text/plain'
|
||||
|
||||
def parse(self, stream):
|
||||
"""
|
||||
Returns a 2-tuple of `(data, files)`.
|
||||
|
||||
`data` will simply be a string representing the body of the request.
|
||||
`files` will always be `None`.
|
||||
"""
|
||||
return (stream.read(), None)
|
||||
|
||||
|
||||
class FormParser(BaseParser):
|
||||
"""
|
||||
Parser for form data.
|
||||
"""
|
||||
|
||||
media_type = 'application/x-www-form-urlencoded'
|
||||
|
||||
def parse(self, stream):
|
||||
"""
|
||||
Returns a 2-tuple of `(data, files)`.
|
||||
|
||||
`data` will be a :class:`QueryDict` containing all the form parameters.
|
||||
`files` will always be :const:`None`.
|
||||
"""
|
||||
data = QueryDict(stream.read())
|
||||
return (data, None)
|
||||
|
||||
|
||||
class MultiPartParser(BaseParser):
|
||||
"""
|
||||
Parser for multipart form data, which may include file data.
|
||||
"""
|
||||
|
||||
media_type = 'multipart/form-data'
|
||||
|
||||
def parse(self, stream):
|
||||
"""
|
||||
Returns a 2-tuple of `(data, files)`.
|
||||
|
||||
`data` will be a :class:`QueryDict` containing all the form parameters.
|
||||
`files` will be a :class:`QueryDict` containing all the form files.
|
||||
"""
|
||||
upload_handlers = self.view.request._get_upload_handlers()
|
||||
try:
|
||||
django_parser = DjangoMultiPartParser(self.view.request.META, stream, upload_handlers)
|
||||
return django_parser.parse()
|
||||
except MultiPartParserError, exc:
|
||||
raise ErrorResponse(status.HTTP_400_BAD_REQUEST,
|
||||
{'detail': 'multipart parse error - %s' % unicode(exc)})
|
||||
|
||||
|
||||
class XMLParser(BaseParser):
|
||||
"""
|
||||
XML parser.
|
||||
"""
|
||||
|
||||
media_type = 'application/xml'
|
||||
|
||||
def parse(self, stream):
|
||||
"""
|
||||
Returns a 2-tuple of `(data, files)`.
|
||||
|
||||
`data` will simply be a string representing the body of the request.
|
||||
`files` will always be `None`.
|
||||
"""
|
||||
try:
|
||||
tree = ET.parse(stream)
|
||||
except (ExpatError, ETParseError, ValueError), exc:
|
||||
content = {'detail': 'XML parse error - %s' % unicode(exc)}
|
||||
raise ErrorResponse(status.HTTP_400_BAD_REQUEST, content)
|
||||
data = self._xml_convert(tree.getroot())
|
||||
|
||||
return (data, None)
|
||||
|
||||
def _xml_convert(self, element):
|
||||
"""
|
||||
convert the xml `element` into the corresponding python object
|
||||
"""
|
||||
|
||||
children = element.getchildren()
|
||||
|
||||
if len(children) == 0:
|
||||
return self._type_convert(element.text)
|
||||
else:
|
||||
# if the fist child tag is list-item means all children are list-item
|
||||
if children[0].tag == "list-item":
|
||||
data = []
|
||||
for child in children:
|
||||
data.append(self._xml_convert(child))
|
||||
else:
|
||||
data = {}
|
||||
for child in children:
|
||||
data[child.tag] = self._xml_convert(child)
|
||||
|
||||
return data
|
||||
|
||||
def _type_convert(self, value):
|
||||
"""
|
||||
Converts the value returned by the XMl parse into the equivalent
|
||||
Python type
|
||||
"""
|
||||
if value is None:
|
||||
return value
|
||||
|
||||
try:
|
||||
return datetime.datetime.strptime(value, '%Y-%m-%d %H:%M:%S')
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
try:
|
||||
return int(value)
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
try:
|
||||
return decimal.Decimal(value)
|
||||
except decimal.InvalidOperation:
|
||||
pass
|
||||
|
||||
return value
|
||||
|
||||
|
||||
DEFAULT_PARSERS = (
|
||||
JSONParser,
|
||||
FormParser,
|
||||
MultiPartParser,
|
||||
XMLParser
|
||||
)
|
||||
|
||||
if yaml:
|
||||
DEFAULT_PARSERS += (YAMLParser, )
|
||||
else:
|
||||
YAMLParser = None
|
||||
|
|
@ -1,267 +0,0 @@
|
|||
"""
|
||||
The :mod:`permissions` module bundles a set of permission classes that are used
|
||||
for checking if a request passes a certain set of constraints. You can assign a permission
|
||||
class to your view by setting your View's :attr:`permissions` class attribute.
|
||||
"""
|
||||
|
||||
from django.core.cache import cache
|
||||
from djangorestframework import status
|
||||
from djangorestframework.response import ErrorResponse
|
||||
import time
|
||||
|
||||
__all__ = (
|
||||
'BasePermission',
|
||||
'FullAnonAccess',
|
||||
'IsAuthenticated',
|
||||
'IsAdminUser',
|
||||
'IsUserOrIsAnonReadOnly',
|
||||
'PerUserThrottling',
|
||||
'PerViewThrottling',
|
||||
'PerResourceThrottling'
|
||||
)
|
||||
|
||||
SAFE_METHODS = ['GET', 'HEAD', 'OPTIONS']
|
||||
|
||||
|
||||
_403_FORBIDDEN_RESPONSE = ErrorResponse(
|
||||
status.HTTP_403_FORBIDDEN,
|
||||
{'detail': 'You do not have permission to access this resource. ' +
|
||||
'You may need to login or otherwise authenticate the request.'})
|
||||
|
||||
_503_SERVICE_UNAVAILABLE = ErrorResponse(
|
||||
status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
{'detail': 'request was throttled'})
|
||||
|
||||
|
||||
class BasePermission(object):
|
||||
"""
|
||||
A base class from which all permission classes should inherit.
|
||||
"""
|
||||
def __init__(self, view):
|
||||
"""
|
||||
Permission classes are always passed the current view on creation.
|
||||
"""
|
||||
self.view = view
|
||||
|
||||
def check_permission(self, auth):
|
||||
"""
|
||||
Should simply return, or raise an :exc:`response.ErrorResponse`.
|
||||
"""
|
||||
pass
|
||||
|
||||
|
||||
class FullAnonAccess(BasePermission):
|
||||
"""
|
||||
Allows full access.
|
||||
"""
|
||||
|
||||
def check_permission(self, user):
|
||||
pass
|
||||
|
||||
|
||||
class IsAuthenticated(BasePermission):
|
||||
"""
|
||||
Allows access only to authenticated users.
|
||||
"""
|
||||
|
||||
def check_permission(self, user):
|
||||
if not user.is_authenticated():
|
||||
raise _403_FORBIDDEN_RESPONSE
|
||||
|
||||
|
||||
class IsAdminUser(BasePermission):
|
||||
"""
|
||||
Allows access only to admin users.
|
||||
"""
|
||||
|
||||
def check_permission(self, user):
|
||||
if not user.is_staff:
|
||||
raise _403_FORBIDDEN_RESPONSE
|
||||
|
||||
|
||||
class IsUserOrIsAnonReadOnly(BasePermission):
|
||||
"""
|
||||
The request is authenticated as a user, or is a read-only request.
|
||||
"""
|
||||
|
||||
def check_permission(self, user):
|
||||
if (not user.is_authenticated() and
|
||||
self.view.method not in SAFE_METHODS):
|
||||
raise _403_FORBIDDEN_RESPONSE
|
||||
|
||||
|
||||
class DjangoModelPermissions(BasePermission):
|
||||
"""
|
||||
The request is authenticated using `django.contrib.auth` permissions.
|
||||
See: https://docs.djangoproject.com/en/dev/topics/auth/#permissions
|
||||
|
||||
It ensures that the user is authenticated, and has the appropriate
|
||||
`add`/`change`/`delete` permissions on the model.
|
||||
|
||||
This permission should only be used on views with a `ModelResource`.
|
||||
"""
|
||||
|
||||
# Map methods into required permission codes.
|
||||
# Override this if you need to also provide 'read' permissions,
|
||||
# or if you want to provide custom permission codes.
|
||||
perms_map = {
|
||||
'GET': [],
|
||||
'OPTIONS': [],
|
||||
'HEAD': [],
|
||||
'POST': ['%(app_label)s.add_%(model_name)s'],
|
||||
'PUT': ['%(app_label)s.change_%(model_name)s'],
|
||||
'PATCH': ['%(app_label)s.change_%(model_name)s'],
|
||||
'DELETE': ['%(app_label)s.delete_%(model_name)s'],
|
||||
}
|
||||
|
||||
def get_required_permissions(self, method, model_cls):
|
||||
"""
|
||||
Given a model and an HTTP method, return the list of permission
|
||||
codes that the user is required to have.
|
||||
"""
|
||||
kwargs = {
|
||||
'app_label': model_cls._meta.app_label,
|
||||
'model_name': model_cls._meta.module_name
|
||||
}
|
||||
try:
|
||||
return [perm % kwargs for perm in self.perms_map[method]]
|
||||
except KeyError:
|
||||
ErrorResponse(status.HTTP_405_METHOD_NOT_ALLOWED)
|
||||
|
||||
def check_permission(self, user):
|
||||
method = self.view.method
|
||||
model_cls = self.view.resource.model
|
||||
perms = self.get_required_permissions(method, model_cls)
|
||||
|
||||
if not user.is_authenticated or not user.has_perms(perms):
|
||||
raise _403_FORBIDDEN_RESPONSE
|
||||
|
||||
|
||||
class BaseThrottle(BasePermission):
|
||||
"""
|
||||
Rate throttling of requests.
|
||||
|
||||
The rate (requests / seconds) is set by a :attr:`throttle` attribute
|
||||
on the :class:`.View` class. The attribute is a string of the form 'number of
|
||||
requests/period'.
|
||||
|
||||
Period should be one of: ('s', 'sec', 'm', 'min', 'h', 'hour', 'd', 'day')
|
||||
|
||||
Previous request information used for throttling is stored in the cache.
|
||||
"""
|
||||
|
||||
attr_name = 'throttle'
|
||||
default = '0/sec'
|
||||
timer = time.time
|
||||
|
||||
def get_cache_key(self):
|
||||
"""
|
||||
Should return a unique cache-key which can be used for throttling.
|
||||
Must be overridden.
|
||||
"""
|
||||
pass
|
||||
|
||||
def check_permission(self, auth):
|
||||
"""
|
||||
Check the throttling.
|
||||
Return `None` or raise an :exc:`.ErrorResponse`.
|
||||
"""
|
||||
num, period = getattr(self.view, self.attr_name, self.default).split('/')
|
||||
self.num_requests = int(num)
|
||||
self.duration = {'s': 1, 'm': 60, 'h': 3600, 'd': 86400}[period[0]]
|
||||
self.auth = auth
|
||||
self.check_throttle()
|
||||
|
||||
def check_throttle(self):
|
||||
"""
|
||||
Implement the check to see if the request should be throttled.
|
||||
|
||||
On success calls :meth:`throttle_success`.
|
||||
On failure calls :meth:`throttle_failure`.
|
||||
"""
|
||||
self.key = self.get_cache_key()
|
||||
self.history = cache.get(self.key, [])
|
||||
self.now = self.timer()
|
||||
|
||||
# Drop any requests from the history which have now passed the
|
||||
# throttle duration
|
||||
while self.history and self.history[-1] <= self.now - self.duration:
|
||||
self.history.pop()
|
||||
if len(self.history) >= self.num_requests:
|
||||
self.throttle_failure()
|
||||
else:
|
||||
self.throttle_success()
|
||||
|
||||
def throttle_success(self):
|
||||
"""
|
||||
Inserts the current request's timestamp along with the key
|
||||
into the cache.
|
||||
"""
|
||||
self.history.insert(0, self.now)
|
||||
cache.set(self.key, self.history, self.duration)
|
||||
header = 'status=SUCCESS; next=%s sec' % self.next()
|
||||
self.view.add_header('X-Throttle', header)
|
||||
|
||||
def throttle_failure(self):
|
||||
"""
|
||||
Called when a request to the API has failed due to throttling.
|
||||
Raises a '503 service unavailable' response.
|
||||
"""
|
||||
header = 'status=FAILURE; next=%s sec' % self.next()
|
||||
self.view.add_header('X-Throttle', header)
|
||||
raise _503_SERVICE_UNAVAILABLE
|
||||
|
||||
def next(self):
|
||||
"""
|
||||
Returns the recommended next request time in seconds.
|
||||
"""
|
||||
if self.history:
|
||||
remaining_duration = self.duration - (self.now - self.history[-1])
|
||||
else:
|
||||
remaining_duration = self.duration
|
||||
|
||||
available_requests = self.num_requests - len(self.history) + 1
|
||||
|
||||
return '%.2f' % (remaining_duration / float(available_requests))
|
||||
|
||||
|
||||
class PerUserThrottling(BaseThrottle):
|
||||
"""
|
||||
Limits the rate of API calls that may be made by a given user.
|
||||
|
||||
The user id will be used as a unique identifier if the user is
|
||||
authenticated. For anonymous requests, the IP address of the client will
|
||||
be used.
|
||||
"""
|
||||
|
||||
def get_cache_key(self):
|
||||
if self.auth.is_authenticated():
|
||||
ident = self.auth.id
|
||||
else:
|
||||
ident = self.view.request.META.get('REMOTE_ADDR', None)
|
||||
return 'throttle_user_%s' % ident
|
||||
|
||||
|
||||
class PerViewThrottling(BaseThrottle):
|
||||
"""
|
||||
Limits the rate of API calls that may be used on a given view.
|
||||
|
||||
The class name of the view is used as a unique identifier to
|
||||
throttle against.
|
||||
"""
|
||||
|
||||
def get_cache_key(self):
|
||||
return 'throttle_view_%s' % self.view.__class__.__name__
|
||||
|
||||
|
||||
class PerResourceThrottling(BaseThrottle):
|
||||
"""
|
||||
Limits the rate of API calls that may be used against all views on
|
||||
a given resource.
|
||||
|
||||
The class name of the resource is used as a unique identifier to
|
||||
throttle against.
|
||||
"""
|
||||
|
||||
def get_cache_key(self):
|
||||
return 'throttle_resource_%s' % self.view.resource.__class__.__name__
|
|
@ -1,417 +0,0 @@
|
|||
"""
|
||||
Renderers are used to serialize a View's output into specific media types.
|
||||
|
||||
Django REST framework also provides HTML and PlainText renderers that help self-document the API,
|
||||
by serializing the output along with documentation regarding the View, output status and headers,
|
||||
and providing forms and links depending on the allowed methods, renderers and parsers on the View.
|
||||
"""
|
||||
from django import forms
|
||||
from django.conf import settings
|
||||
from django.core.serializers.json import DateTimeAwareJSONEncoder
|
||||
from django.template import RequestContext, loader
|
||||
from django.utils import simplejson as json
|
||||
|
||||
|
||||
from djangorestframework.compat import yaml
|
||||
from djangorestframework.utils import dict2xml, url_resolves
|
||||
from djangorestframework.utils.breadcrumbs import get_breadcrumbs
|
||||
from djangorestframework.utils.mediatypes import get_media_type_params, add_media_type_param, media_type_matches
|
||||
from djangorestframework import VERSION
|
||||
|
||||
import string
|
||||
from urllib import quote_plus
|
||||
|
||||
__all__ = (
|
||||
'BaseRenderer',
|
||||
'TemplateRenderer',
|
||||
'JSONRenderer',
|
||||
'JSONPRenderer',
|
||||
'DocumentingHTMLRenderer',
|
||||
'DocumentingXHTMLRenderer',
|
||||
'DocumentingPlainTextRenderer',
|
||||
'XMLRenderer',
|
||||
'YAMLRenderer'
|
||||
)
|
||||
|
||||
|
||||
class BaseRenderer(object):
|
||||
"""
|
||||
All renderers must extend this class, set the :attr:`media_type` attribute,
|
||||
and override the :meth:`render` method.
|
||||
"""
|
||||
|
||||
_FORMAT_QUERY_PARAM = 'format'
|
||||
|
||||
media_type = None
|
||||
format = None
|
||||
|
||||
def __init__(self, view):
|
||||
self.view = view
|
||||
|
||||
def can_handle_response(self, accept):
|
||||
"""
|
||||
Returns :const:`True` if this renderer is able to deal with the given
|
||||
*accept* media type.
|
||||
|
||||
The default implementation for this function is to check the *accept*
|
||||
argument against the :attr:`media_type` attribute set on the class to see if
|
||||
they match.
|
||||
|
||||
This may be overridden to provide for other behavior, but typically you'll
|
||||
instead want to just set the :attr:`media_type` attribute on the class.
|
||||
"""
|
||||
format = self.view.kwargs.get(self._FORMAT_QUERY_PARAM, None)
|
||||
if format is None:
|
||||
format = self.view.request.GET.get(self._FORMAT_QUERY_PARAM, None)
|
||||
if format is not None:
|
||||
return format == self.format
|
||||
return media_type_matches(self.media_type, accept)
|
||||
|
||||
def render(self, obj=None, media_type=None):
|
||||
"""
|
||||
Given an object render it into a string.
|
||||
|
||||
The requested media type is also passed to this method,
|
||||
as it may contain parameters relevant to how the parser
|
||||
should render the output.
|
||||
EG: ``application/json; indent=4``
|
||||
|
||||
By default render simply returns the output as-is.
|
||||
Override this method to provide for other behavior.
|
||||
"""
|
||||
if obj is None:
|
||||
return ''
|
||||
|
||||
return str(obj)
|
||||
|
||||
|
||||
class JSONRenderer(BaseRenderer):
|
||||
"""
|
||||
Renderer which serializes to JSON
|
||||
"""
|
||||
|
||||
media_type = 'application/json'
|
||||
format = 'json'
|
||||
|
||||
def render(self, obj=None, media_type=None):
|
||||
"""
|
||||
Renders *obj* into serialized JSON.
|
||||
"""
|
||||
if obj is None:
|
||||
return ''
|
||||
|
||||
# If the media type looks like 'application/json; indent=4', then
|
||||
# pretty print the result.
|
||||
indent = get_media_type_params(media_type).get('indent', None)
|
||||
sort_keys = False
|
||||
try:
|
||||
indent = max(min(int(indent), 8), 0)
|
||||
sort_keys = True
|
||||
except (ValueError, TypeError):
|
||||
indent = None
|
||||
|
||||
return json.dumps(obj, cls=DateTimeAwareJSONEncoder, indent=indent, sort_keys=sort_keys)
|
||||
|
||||
|
||||
class JSONPRenderer(JSONRenderer):
|
||||
"""
|
||||
Renderer which serializes to JSONP
|
||||
"""
|
||||
|
||||
media_type = 'application/json-p'
|
||||
format = 'json-p'
|
||||
renderer_class = JSONRenderer
|
||||
callback_parameter = 'callback'
|
||||
|
||||
def _get_callback(self):
|
||||
return self.view.request.GET.get(self.callback_parameter, self.callback_parameter)
|
||||
|
||||
def _get_renderer(self):
|
||||
return self.renderer_class(self.view)
|
||||
|
||||
def render(self, obj=None, media_type=None):
|
||||
callback = self._get_callback()
|
||||
json = self._get_renderer().render(obj, media_type)
|
||||
return "%s(%s);" % (callback, json)
|
||||
|
||||
|
||||
class XMLRenderer(BaseRenderer):
|
||||
"""
|
||||
Renderer which serializes to XML.
|
||||
"""
|
||||
|
||||
media_type = 'application/xml'
|
||||
format = 'xml'
|
||||
|
||||
def render(self, obj=None, media_type=None):
|
||||
"""
|
||||
Renders *obj* into serialized XML.
|
||||
"""
|
||||
if obj is None:
|
||||
return ''
|
||||
return dict2xml(obj)
|
||||
|
||||
|
||||
class YAMLRenderer(BaseRenderer):
|
||||
"""
|
||||
Renderer which serializes to YAML.
|
||||
"""
|
||||
|
||||
media_type = 'application/yaml'
|
||||
format = 'yaml'
|
||||
|
||||
def render(self, obj=None, media_type=None):
|
||||
"""
|
||||
Renders *obj* into serialized YAML.
|
||||
"""
|
||||
if obj is None:
|
||||
return ''
|
||||
|
||||
return yaml.safe_dump(obj)
|
||||
|
||||
|
||||
class TemplateRenderer(BaseRenderer):
|
||||
"""
|
||||
A Base class provided for convenience.
|
||||
|
||||
Render the object simply by using the given template.
|
||||
To create a template renderer, subclass this class, and set
|
||||
the :attr:`media_type` and :attr:`template` attributes.
|
||||
"""
|
||||
|
||||
media_type = None
|
||||
template = None
|
||||
|
||||
def __init__(self, view):
|
||||
super(TemplateRenderer, self).__init__(view)
|
||||
self.template = getattr(self.view, "template", self.template)
|
||||
|
||||
def render(self, obj=None, media_type=None):
|
||||
"""
|
||||
Renders *obj* using the :attr:`template` specified on the class.
|
||||
"""
|
||||
if obj is None:
|
||||
return ''
|
||||
|
||||
template = loader.get_template(self.template)
|
||||
context = RequestContext(self.view.request, {'object': obj})
|
||||
return template.render(context)
|
||||
|
||||
|
||||
class DocumentingTemplateRenderer(BaseRenderer):
|
||||
"""
|
||||
Base class for renderers used to self-document the API.
|
||||
Implementing classes should extend this class and set the template attribute.
|
||||
"""
|
||||
|
||||
template = None
|
||||
|
||||
def __init__(self, view):
|
||||
super(DocumentingTemplateRenderer, self).__init__(view)
|
||||
self.template = getattr(self.view, "template", self.template)
|
||||
|
||||
def _get_content(self, view, request, obj, media_type):
|
||||
"""
|
||||
Get the content as if it had been rendered by a non-documenting renderer.
|
||||
|
||||
(Typically this will be the content as it would have been if the Resource had been
|
||||
requested with an 'Accept: */*' header, although with verbose style formatting if appropriate.)
|
||||
"""
|
||||
|
||||
# Find the first valid renderer and render the content. (Don't use another documenting renderer.)
|
||||
renderers = [renderer for renderer in view.renderers if not issubclass(renderer, DocumentingTemplateRenderer)]
|
||||
if not renderers:
|
||||
return '[No renderers were found]'
|
||||
|
||||
media_type = add_media_type_param(media_type, 'indent', '4')
|
||||
content = renderers[0](view).render(obj, media_type)
|
||||
if not all(char in string.printable for char in content):
|
||||
return '[%d bytes of binary content]'
|
||||
|
||||
return content
|
||||
|
||||
def _get_form_instance(self, view, method):
|
||||
"""
|
||||
Get a form, possibly bound to either the input or output data.
|
||||
In the absence on of the Resource having an associated form then
|
||||
provide a form that can be used to submit arbitrary content.
|
||||
"""
|
||||
|
||||
# Get the form instance if we have one bound to the input
|
||||
form_instance = None
|
||||
if method == getattr(view, 'method', view.request.method).lower():
|
||||
form_instance = getattr(view, 'bound_form_instance', None)
|
||||
|
||||
if not form_instance and hasattr(view, 'get_bound_form'):
|
||||
# Otherwise if we have a response that is valid against the form then use that
|
||||
if view.response.has_content_body:
|
||||
try:
|
||||
form_instance = view.get_bound_form(view.response.cleaned_content, method=method)
|
||||
if form_instance and not form_instance.is_valid():
|
||||
form_instance = None
|
||||
except Exception:
|
||||
form_instance = None
|
||||
|
||||
# If we still don't have a form instance then try to get an unbound form
|
||||
if not form_instance:
|
||||
try:
|
||||
form_instance = view.get_bound_form(method=method)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# If we still don't have a form instance then try to get an unbound form which can tunnel arbitrary content types
|
||||
if not form_instance:
|
||||
form_instance = self._get_generic_content_form(view)
|
||||
|
||||
return form_instance
|
||||
|
||||
def _get_generic_content_form(self, view):
|
||||
"""
|
||||
Returns a form that allows for arbitrary content types to be tunneled via standard HTML forms
|
||||
(Which are typically application/x-www-form-urlencoded)
|
||||
"""
|
||||
|
||||
# If we're not using content overloading there's no point in supplying a generic form,
|
||||
# as the view won't treat the form's value as the content of the request.
|
||||
if not getattr(view, '_USE_FORM_OVERLOADING', False):
|
||||
return None
|
||||
|
||||
# NB. http://jacobian.org/writing/dynamic-form-generation/
|
||||
class GenericContentForm(forms.Form):
|
||||
def __init__(self, view):
|
||||
"""We don't know the names of the fields we want to set until the point the form is instantiated,
|
||||
as they are determined by the Resource the form is being created against.
|
||||
Add the fields dynamically."""
|
||||
super(GenericContentForm, self).__init__()
|
||||
|
||||
contenttype_choices = [(media_type, media_type) for media_type in view._parsed_media_types]
|
||||
initial_contenttype = view._default_parser.media_type
|
||||
|
||||
self.fields[view._CONTENTTYPE_PARAM] = forms.ChoiceField(label='Content Type',
|
||||
choices=contenttype_choices,
|
||||
initial=initial_contenttype)
|
||||
self.fields[view._CONTENT_PARAM] = forms.CharField(label='Content',
|
||||
widget=forms.Textarea)
|
||||
|
||||
# If either of these reserved parameters are turned off then content tunneling is not possible
|
||||
if self.view._CONTENTTYPE_PARAM is None or self.view._CONTENT_PARAM is None:
|
||||
return None
|
||||
|
||||
# Okey doke, let's do it
|
||||
return GenericContentForm(view)
|
||||
|
||||
def get_name(self):
|
||||
try:
|
||||
return self.view.get_name()
|
||||
except AttributeError:
|
||||
return self.view.__doc__
|
||||
|
||||
def get_description(self, html=None):
|
||||
if html is None:
|
||||
html = bool('html' in self.format)
|
||||
try:
|
||||
return self.view.get_description(html)
|
||||
except AttributeError:
|
||||
return self.view.__doc__
|
||||
|
||||
def render(self, obj=None, media_type=None):
|
||||
"""
|
||||
Renders *obj* using the :attr:`template` set on the class.
|
||||
|
||||
The context used in the template contains all the information
|
||||
needed to self-document the response to this request.
|
||||
"""
|
||||
|
||||
content = self._get_content(self.view, self.view.request, obj, media_type)
|
||||
|
||||
put_form_instance = self._get_form_instance(self.view, 'put')
|
||||
post_form_instance = self._get_form_instance(self.view, 'post')
|
||||
|
||||
if url_resolves(settings.LOGIN_URL) and url_resolves(settings.LOGOUT_URL):
|
||||
login_url = "%s?next=%s" % (settings.LOGIN_URL, quote_plus(self.view.request.path))
|
||||
logout_url = "%s?next=%s" % (settings.LOGOUT_URL, quote_plus(self.view.request.path))
|
||||
else:
|
||||
login_url = None
|
||||
logout_url = None
|
||||
|
||||
name = self.get_name()
|
||||
description = self.get_description()
|
||||
|
||||
breadcrumb_list = get_breadcrumbs(self.view.request.path)
|
||||
|
||||
template = loader.get_template(self.template)
|
||||
context = RequestContext(self.view.request, {
|
||||
'content': content,
|
||||
'view': self.view,
|
||||
'request': self.view.request,
|
||||
'response': self.view.response,
|
||||
'description': description,
|
||||
'name': name,
|
||||
'version': VERSION,
|
||||
'breadcrumblist': breadcrumb_list,
|
||||
'available_formats': self.view._rendered_formats,
|
||||
'put_form': put_form_instance,
|
||||
'post_form': post_form_instance,
|
||||
'FORMAT_PARAM': self._FORMAT_QUERY_PARAM,
|
||||
'METHOD_PARAM': getattr(self.view, '_METHOD_PARAM', None),
|
||||
})
|
||||
|
||||
ret = template.render(context)
|
||||
|
||||
# Munge DELETE Response code to allow us to return content
|
||||
# (Do this *after* we've rendered the template so that we include
|
||||
# the normal deletion response code in the output)
|
||||
if self.view.response.status == 204:
|
||||
self.view.response.status = 200
|
||||
|
||||
return ret
|
||||
|
||||
|
||||
class DocumentingHTMLRenderer(DocumentingTemplateRenderer):
|
||||
"""
|
||||
Renderer which provides a browsable HTML interface for an API.
|
||||
See the examples at http://shielded-mountain-6732.herokuapp.com to see this in action.
|
||||
"""
|
||||
|
||||
media_type = 'text/html'
|
||||
format = 'html'
|
||||
template = 'djangorestframework/api.html'
|
||||
|
||||
|
||||
class DocumentingXHTMLRenderer(DocumentingTemplateRenderer):
|
||||
"""
|
||||
Identical to DocumentingHTMLRenderer, except with an xhtml media type.
|
||||
We need this to be listed in preference to xml in order to return HTML to WebKit based browsers,
|
||||
given their Accept headers.
|
||||
"""
|
||||
|
||||
media_type = 'application/xhtml+xml'
|
||||
format = 'xhtml'
|
||||
template = 'djangorestframework/api.html'
|
||||
|
||||
|
||||
class DocumentingPlainTextRenderer(DocumentingTemplateRenderer):
|
||||
"""
|
||||
Renderer that serializes the object with the default renderer, but also provides plain-text
|
||||
documentation of the returned status and headers, and of the resource's name and description.
|
||||
Useful for browsing an API with command line tools.
|
||||
"""
|
||||
|
||||
media_type = 'text/plain'
|
||||
format = 'txt'
|
||||
template = 'djangorestframework/api.txt'
|
||||
|
||||
|
||||
DEFAULT_RENDERERS = (
|
||||
JSONRenderer,
|
||||
JSONPRenderer,
|
||||
DocumentingHTMLRenderer,
|
||||
DocumentingXHTMLRenderer,
|
||||
DocumentingPlainTextRenderer,
|
||||
XMLRenderer
|
||||
)
|
||||
|
||||
if yaml:
|
||||
DEFAULT_RENDERERS += (YAMLRenderer, )
|
||||
else:
|
||||
YAMLRenderer = None
|
|
@ -1,345 +0,0 @@
|
|||
from django import forms
|
||||
|
||||
from djangorestframework.response import ErrorResponse
|
||||
from djangorestframework.serializer import Serializer
|
||||
from djangorestframework.utils import as_tuple
|
||||
|
||||
|
||||
class BaseResource(Serializer):
|
||||
"""
|
||||
Base class for all Resource classes, which simply defines the interface
|
||||
they provide.
|
||||
"""
|
||||
fields = None
|
||||
include = None
|
||||
exclude = None
|
||||
|
||||
def __init__(self, view=None, depth=None, stack=[], **kwargs):
|
||||
super(BaseResource, self).__init__(depth, stack, **kwargs)
|
||||
self.view = view
|
||||
self.request = getattr(view, 'request', None)
|
||||
|
||||
def validate_request(self, data, files=None):
|
||||
"""
|
||||
Given the request content return the cleaned, validated content.
|
||||
Typically raises a :exc:`response.ErrorResponse` with status code 400
|
||||
(Bad Request) on failure.
|
||||
"""
|
||||
return data
|
||||
|
||||
def filter_response(self, obj):
|
||||
"""
|
||||
Given the response content, filter it into a serializable object.
|
||||
"""
|
||||
return self.serialize(obj)
|
||||
|
||||
|
||||
class Resource(BaseResource):
|
||||
"""
|
||||
A Resource determines how a python object maps to some serializable data.
|
||||
Objects that a resource can act on include plain Python object instances,
|
||||
Django Models, and Django QuerySets.
|
||||
"""
|
||||
|
||||
# The model attribute refers to the Django Model which this Resource maps to.
|
||||
# (The Model's class, rather than an instance of the Model)
|
||||
model = None
|
||||
|
||||
# By default the set of returned fields will be the set of:
|
||||
#
|
||||
# 0. All the fields on the model, excluding 'id'.
|
||||
# 1. All the properties on the model.
|
||||
# 2. The absolute_url of the model, if a get_absolute_url method exists for the model.
|
||||
#
|
||||
# If you wish to override this behaviour,
|
||||
# you should explicitly set the fields attribute on your class.
|
||||
fields = None
|
||||
|
||||
|
||||
class FormResource(Resource):
|
||||
"""
|
||||
Resource class that uses forms for validation.
|
||||
Also provides a :meth:`get_bound_form` method which may be used by some renderers.
|
||||
|
||||
On calling :meth:`validate_request` this validator may set a :attr:`bound_form_instance` attribute on the
|
||||
view, which may be used by some renderers.
|
||||
"""
|
||||
|
||||
form = None
|
||||
"""
|
||||
The :class:`Form` class that should be used for request validation.
|
||||
This can be overridden by a :attr:`form` attribute on the :class:`views.View`.
|
||||
"""
|
||||
|
||||
allow_unknown_form_fields = False
|
||||
"""
|
||||
Flag to check for unknown fields when validating a form. If set to false and
|
||||
we receive request data that is not expected by the form it raises an
|
||||
:exc:`response.ErrorResponse` with status code 400. If set to true, only
|
||||
expected fields are validated.
|
||||
"""
|
||||
|
||||
def validate_request(self, data, files=None):
|
||||
"""
|
||||
Given some content as input return some cleaned, validated content.
|
||||
Raises a :exc:`response.ErrorResponse` with status code 400 (Bad Request) on failure.
|
||||
|
||||
Validation is standard form validation, with an additional constraint that *no extra unknown fields* may be supplied
|
||||
if :attr:`self.allow_unknown_form_fields` is ``False``.
|
||||
|
||||
On failure the :exc:`response.ErrorResponse` content is a dict which may contain :obj:`'errors'` and :obj:`'field-errors'` keys.
|
||||
If the :obj:`'errors'` key exists it is a list of strings of non-field errors.
|
||||
If the :obj:`'field-errors'` key exists it is a dict of ``{'field name as string': ['errors as strings', ...]}``.
|
||||
"""
|
||||
return self._validate(data, files)
|
||||
|
||||
def _validate(self, data, files, allowed_extra_fields=(), fake_data=None):
|
||||
"""
|
||||
Wrapped by validate to hide the extra flags that are used in the implementation.
|
||||
|
||||
allowed_extra_fields is a list of fields which are not defined by the form, but which we still
|
||||
expect to see on the input.
|
||||
|
||||
fake_data is a string that should be used as an extra key, as a kludge to force .errors
|
||||
to be populated when an empty dict is supplied in `data`
|
||||
"""
|
||||
|
||||
# We'd like nice error messages even if no content is supplied.
|
||||
# Typically if an empty dict is given to a form Django will
|
||||
# return .is_valid() == False, but .errors == {}
|
||||
#
|
||||
# To get around this case we revalidate with some fake data.
|
||||
if fake_data:
|
||||
data[fake_data] = '_fake_data'
|
||||
allowed_extra_fields = tuple(allowed_extra_fields) + ('_fake_data',)
|
||||
|
||||
bound_form = self.get_bound_form(data, files)
|
||||
|
||||
if bound_form is None:
|
||||
return data
|
||||
|
||||
self.view.bound_form_instance = bound_form
|
||||
|
||||
data = data and data or {}
|
||||
files = files and files or {}
|
||||
|
||||
seen_fields_set = set(data.keys())
|
||||
form_fields_set = set(bound_form.fields.keys())
|
||||
allowed_extra_fields_set = set(allowed_extra_fields)
|
||||
|
||||
# In addition to regular validation we also ensure no additional fields are being passed in...
|
||||
unknown_fields = seen_fields_set - (form_fields_set | allowed_extra_fields_set)
|
||||
unknown_fields = unknown_fields - set(('csrfmiddlewaretoken', '_accept', '_method')) # TODO: Ugh.
|
||||
|
||||
# Check using both regular validation, and our stricter no additional fields rule
|
||||
if bound_form.is_valid() and (self.allow_unknown_form_fields or not unknown_fields):
|
||||
# Validation succeeded...
|
||||
cleaned_data = bound_form.cleaned_data
|
||||
|
||||
# Add in any extra fields to the cleaned content...
|
||||
for key in (allowed_extra_fields_set & seen_fields_set) - set(cleaned_data.keys()):
|
||||
cleaned_data[key] = data[key]
|
||||
|
||||
return cleaned_data
|
||||
|
||||
# Validation failed...
|
||||
detail = {}
|
||||
|
||||
if not bound_form.errors and not unknown_fields:
|
||||
# is_valid() was False, but errors was empty.
|
||||
# If we havn't already done so attempt revalidation with some fake data
|
||||
# to force django to give us an errors dict.
|
||||
if fake_data is None:
|
||||
return self._validate(data, files, allowed_extra_fields, '_fake_data')
|
||||
|
||||
# If we've already set fake_dict and we're still here, fallback gracefully.
|
||||
detail = {u'errors': [u'No content was supplied.']}
|
||||
|
||||
else:
|
||||
# Add any non-field errors
|
||||
if bound_form.non_field_errors():
|
||||
detail[u'errors'] = bound_form.non_field_errors()
|
||||
|
||||
# Add standard field errors
|
||||
field_errors = dict(
|
||||
(key, map(unicode, val))
|
||||
for (key, val)
|
||||
in bound_form.errors.iteritems()
|
||||
if not key.startswith('__')
|
||||
)
|
||||
|
||||
# Add any unknown field errors
|
||||
if not self.allow_unknown_form_fields:
|
||||
for key in unknown_fields:
|
||||
field_errors[key] = [u'This field does not exist.']
|
||||
|
||||
if field_errors:
|
||||
detail[u'field_errors'] = field_errors
|
||||
|
||||
# Return HTTP 400 response (BAD REQUEST)
|
||||
raise ErrorResponse(400, detail)
|
||||
|
||||
def get_form_class(self, method=None):
|
||||
"""
|
||||
Returns the form class used to validate this resource.
|
||||
"""
|
||||
# A form on the view overrides a form on the resource.
|
||||
form = getattr(self.view, 'form', None) or self.form
|
||||
|
||||
# Use the requested method or determine the request method
|
||||
if method is None and hasattr(self.view, 'request') and hasattr(self.view, 'method'):
|
||||
method = self.view.method
|
||||
elif method is None and hasattr(self.view, 'request'):
|
||||
method = self.view.request.method
|
||||
|
||||
# A method form on the view or resource overrides the general case.
|
||||
# Method forms are attributes like `get_form` `post_form` `put_form`.
|
||||
if method:
|
||||
form = getattr(self, '%s_form' % method.lower(), form)
|
||||
form = getattr(self.view, '%s_form' % method.lower(), form)
|
||||
|
||||
return form
|
||||
|
||||
def get_bound_form(self, data=None, files=None, method=None):
|
||||
"""
|
||||
Given some content return a Django form bound to that content.
|
||||
If form validation is turned off (:attr:`form` class attribute is :const:`None`) then returns :const:`None`.
|
||||
"""
|
||||
form = self.get_form_class(method)
|
||||
|
||||
if not form:
|
||||
return None
|
||||
|
||||
if data is not None or files is not None:
|
||||
return form(data, files)
|
||||
|
||||
return form()
|
||||
|
||||
|
||||
class ModelResource(FormResource):
|
||||
"""
|
||||
Resource class that uses forms for validation and otherwise falls back to a model form if no form is set.
|
||||
Also provides a :meth:`get_bound_form` method which may be used by some renderers.
|
||||
"""
|
||||
|
||||
form = None
|
||||
"""
|
||||
The form class that should be used for request validation.
|
||||
If set to :const:`None` then the default model form validation will be used.
|
||||
|
||||
This can be overridden by a :attr:`form` attribute on the :class:`views.View`.
|
||||
"""
|
||||
|
||||
model = None
|
||||
"""
|
||||
The model class which this resource maps to.
|
||||
|
||||
This can be overridden by a :attr:`model` attribute on the :class:`views.View`.
|
||||
"""
|
||||
|
||||
fields = None
|
||||
"""
|
||||
The list of fields to use on the output.
|
||||
|
||||
May be any of:
|
||||
|
||||
The name of a model field. To view nested resources, give the field as a tuple of ("fieldName", resource) where `resource` may be any of ModelResource reference, the name of a ModelResourc reference as a string or a tuple of strings representing fields on the nested model.
|
||||
The name of an attribute on the model.
|
||||
The name of an attribute on the resource.
|
||||
The name of a method on the model, with a signature like ``func(self)``.
|
||||
The name of a method on the resource, with a signature like ``func(self, instance)``.
|
||||
"""
|
||||
|
||||
exclude = ('id', 'pk')
|
||||
"""
|
||||
The list of fields to exclude. This is only used if :attr:`fields` is not set.
|
||||
"""
|
||||
|
||||
include = ()
|
||||
"""
|
||||
The list of extra fields to include. This is only used if :attr:`fields` is not set.
|
||||
"""
|
||||
|
||||
def __init__(self, view=None, depth=None, stack=[], **kwargs):
|
||||
"""
|
||||
Allow :attr:`form` and :attr:`model` attributes set on the
|
||||
:class:`View` to override the :attr:`form` and :attr:`model`
|
||||
attributes set on the :class:`Resource`.
|
||||
"""
|
||||
super(ModelResource, self).__init__(view, depth, stack, **kwargs)
|
||||
|
||||
self.model = getattr(view, 'model', None) or self.model
|
||||
|
||||
def validate_request(self, data, files=None):
|
||||
"""
|
||||
Given some content as input return some cleaned, validated content.
|
||||
Raises a :exc:`response.ErrorResponse` with status code 400 (Bad Request) on failure.
|
||||
|
||||
Validation is standard form or model form validation,
|
||||
with an additional constraint that no extra unknown fields may be supplied,
|
||||
and that all fields specified by the fields class attribute must be supplied,
|
||||
even if they are not validated by the form/model form.
|
||||
|
||||
On failure the ErrorResponse content is a dict which may contain :obj:`'errors'` and :obj:`'field-errors'` keys.
|
||||
If the :obj:`'errors'` key exists it is a list of strings of non-field errors.
|
||||
If the ''field-errors'` key exists it is a dict of {field name as string: list of errors as strings}.
|
||||
"""
|
||||
return self._validate(data, files, allowed_extra_fields=self._property_fields_set)
|
||||
|
||||
def get_bound_form(self, data=None, files=None, method=None):
|
||||
"""
|
||||
Given some content return a ``Form`` instance bound to that content.
|
||||
|
||||
If the :attr:`form` class attribute has been explicitly set then that class will be used
|
||||
to create the Form, otherwise the model will be used to create a ModelForm.
|
||||
"""
|
||||
form = self.get_form_class(method)
|
||||
|
||||
if not form and self.model:
|
||||
# Fall back to ModelForm which we create on the fly
|
||||
class OnTheFlyModelForm(forms.ModelForm):
|
||||
class Meta:
|
||||
model = self.model
|
||||
#fields = tuple(self._model_fields_set)
|
||||
|
||||
form = OnTheFlyModelForm
|
||||
|
||||
# Both form and model not set? Okay bruv, whatevs...
|
||||
if not form:
|
||||
return None
|
||||
|
||||
# Instantiate the ModelForm as appropriate
|
||||
if data is not None or files is not None:
|
||||
if issubclass(form, forms.ModelForm) and hasattr(self.view, 'model_instance'):
|
||||
# Bound to an existing model instance
|
||||
return form(data, files, instance=self.view.model_instance)
|
||||
else:
|
||||
return form(data, files)
|
||||
|
||||
return form()
|
||||
|
||||
@property
|
||||
def _model_fields_set(self):
|
||||
"""
|
||||
Return a set containing the names of validated fields on the model.
|
||||
"""
|
||||
model_fields = set(field.name for field in self.model._meta.fields)
|
||||
|
||||
if self.fields:
|
||||
return model_fields & set(as_tuple(self.fields))
|
||||
|
||||
return model_fields - set(as_tuple(self.exclude))
|
||||
|
||||
@property
|
||||
def _property_fields_set(self):
|
||||
"""
|
||||
Returns a set containing the names of validated properties on the model.
|
||||
"""
|
||||
property_fields = set(attr for attr in dir(self.model) if
|
||||
isinstance(getattr(self.model, attr, None), property)
|
||||
and not attr.startswith('_'))
|
||||
|
||||
if self.fields:
|
||||
return property_fields & set(as_tuple(self.fields))
|
||||
|
||||
return property_fields.union(set(as_tuple(self.include))) - set(as_tuple(self.exclude))
|
|
@ -1,44 +0,0 @@
|
|||
"""
|
||||
The :mod:`response` module provides Response classes you can use in your
|
||||
views to return a certain HTTP response. Typically a response is *rendered*
|
||||
into a HTTP response depending on what renderers are set on your view and
|
||||
als depending on the accept header of the request.
|
||||
"""
|
||||
|
||||
from django.core.handlers.wsgi import STATUS_CODE_TEXT
|
||||
|
||||
__all__ = ('Response', 'ErrorResponse')
|
||||
|
||||
# TODO: remove raw_content/cleaned_content and just use content?
|
||||
|
||||
|
||||
class Response(object):
|
||||
"""
|
||||
An HttpResponse that may include content that hasn't yet been serialized.
|
||||
"""
|
||||
|
||||
def __init__(self, status=200, content=None, headers=None):
|
||||
self.status = status
|
||||
self.media_type = None
|
||||
self.has_content_body = content is not None
|
||||
self.raw_content = content # content prior to filtering
|
||||
self.cleaned_content = content # content after filtering
|
||||
self.headers = headers or {}
|
||||
|
||||
@property
|
||||
def status_text(self):
|
||||
"""
|
||||
Return reason text corresponding to our HTTP response status code.
|
||||
Provided for convenience.
|
||||
"""
|
||||
return STATUS_CODE_TEXT.get(self.status, '')
|
||||
|
||||
|
||||
class ErrorResponse(Exception):
|
||||
"""
|
||||
An exception representing an Response that should be returned immediately.
|
||||
Any content should be serialized as-is, without being filtered.
|
||||
"""
|
||||
|
||||
def __init__(self, status, content=None, headers={}):
|
||||
self.response = Response(status, content=content, headers=headers)
|
|
@ -1,300 +0,0 @@
|
|||
"""
|
||||
Customizable serialization.
|
||||
"""
|
||||
from django.db import models
|
||||
from django.db.models.query import QuerySet, RawQuerySet
|
||||
from django.utils.encoding import smart_unicode, is_protected_type, smart_str
|
||||
|
||||
import inspect
|
||||
import types
|
||||
|
||||
|
||||
# We register serializer classes, so that we can refer to them by their
|
||||
# class names, if there are cyclical serialization heirachys.
|
||||
_serializers = {}
|
||||
|
||||
|
||||
def _field_to_tuple(field):
|
||||
"""
|
||||
Convert an item in the `fields` attribute into a 2-tuple.
|
||||
"""
|
||||
if isinstance(field, (tuple, list)):
|
||||
return (field[0], field[1])
|
||||
return (field, None)
|
||||
|
||||
|
||||
def _fields_to_list(fields):
|
||||
"""
|
||||
Return a list of field tuples.
|
||||
"""
|
||||
return [_field_to_tuple(field) for field in fields or ()]
|
||||
|
||||
|
||||
class _SkipField(Exception):
|
||||
"""
|
||||
Signals that a serialized field should be ignored.
|
||||
We use this mechanism as the default behavior for ensuring
|
||||
that we don't infinitely recurse when dealing with nested data.
|
||||
"""
|
||||
pass
|
||||
|
||||
|
||||
class _RegisterSerializer(type):
|
||||
"""
|
||||
Metaclass to register serializers.
|
||||
"""
|
||||
def __new__(cls, name, bases, attrs):
|
||||
# Build the class and register it.
|
||||
ret = super(_RegisterSerializer, cls).__new__(cls, name, bases, attrs)
|
||||
_serializers[name] = ret
|
||||
return ret
|
||||
|
||||
|
||||
class Serializer(object):
|
||||
"""
|
||||
Converts python objects into plain old native types suitable for
|
||||
serialization. In particular it handles models and querysets.
|
||||
|
||||
The output format is specified by setting a number of attributes
|
||||
on the class.
|
||||
|
||||
You may also override any of the serialization methods, to provide
|
||||
for more flexible behavior.
|
||||
|
||||
Valid output types include anything that may be directly rendered into
|
||||
json, xml etc...
|
||||
"""
|
||||
__metaclass__ = _RegisterSerializer
|
||||
|
||||
fields = ()
|
||||
"""
|
||||
Specify the fields to be serialized on a model or dict.
|
||||
Overrides `include` and `exclude`.
|
||||
"""
|
||||
|
||||
include = ()
|
||||
"""
|
||||
Fields to add to the default set to be serialized on a model/dict.
|
||||
"""
|
||||
|
||||
exclude = ()
|
||||
"""
|
||||
Fields to remove from the default set to be serialized on a model/dict.
|
||||
"""
|
||||
|
||||
rename = {}
|
||||
"""
|
||||
A dict of key->name to use for the field keys.
|
||||
"""
|
||||
|
||||
related_serializer = None
|
||||
"""
|
||||
The default serializer class to use for any related models.
|
||||
"""
|
||||
|
||||
depth = None
|
||||
"""
|
||||
The maximum depth to serialize to, or `None`.
|
||||
"""
|
||||
|
||||
parent = None
|
||||
"""
|
||||
A reference to the root serializer when descending down into fields.
|
||||
"""
|
||||
|
||||
def __init__(self, depth=None, stack=[], **kwargs):
|
||||
if depth is not None:
|
||||
self.depth = depth
|
||||
self.stack = stack
|
||||
|
||||
def get_fields(self, obj):
|
||||
fields = self.fields
|
||||
|
||||
# If `fields` is not set, we use the default fields and modify
|
||||
# them with `include` and `exclude`
|
||||
if not fields:
|
||||
default = self.get_default_fields(obj)
|
||||
include = self.include or ()
|
||||
exclude = self.exclude or ()
|
||||
fields = set(default + list(include)) - set(exclude)
|
||||
|
||||
return fields
|
||||
|
||||
def get_default_fields(self, obj):
|
||||
"""
|
||||
Return the default list of field names/keys for a model instance/dict.
|
||||
These are used if `fields` is not given.
|
||||
"""
|
||||
if isinstance(obj, models.Model):
|
||||
opts = obj._meta
|
||||
return [field.name for field in opts.fields + opts.many_to_many]
|
||||
else:
|
||||
return obj.keys()
|
||||
|
||||
def get_related_serializer(self, info):
|
||||
# If an element in `fields` is a 2-tuple of (str, tuple)
|
||||
# then the second element of the tuple is the fields to
|
||||
# set on the related serializer
|
||||
|
||||
class OnTheFlySerializer(self.__class__):
|
||||
fields = info
|
||||
parent = getattr(self, 'parent') or self
|
||||
|
||||
if isinstance(info, (list, tuple)):
|
||||
return OnTheFlySerializer
|
||||
|
||||
# If an element in `fields` is a 2-tuple of (str, Serializer)
|
||||
# then the second element of the tuple is the Serializer
|
||||
# class to use for that field.
|
||||
elif isinstance(info, type) and issubclass(info, Serializer):
|
||||
return info
|
||||
|
||||
# If an element in `fields` is a 2-tuple of (str, str)
|
||||
# then the second element of the tuple is the name of the Serializer
|
||||
# class to use for that field.
|
||||
#
|
||||
# Black magic to deal with cyclical Serializer dependancies.
|
||||
# Similar to what Django does for cyclically related models.
|
||||
elif isinstance(info, str) and info in _serializers:
|
||||
return _serializers[info]
|
||||
|
||||
# Otherwise use `related_serializer` or fall back to
|
||||
# `OnTheFlySerializer` preserve custom serialization methods.
|
||||
return getattr(self, 'related_serializer') or OnTheFlySerializer
|
||||
|
||||
def serialize_key(self, key):
|
||||
"""
|
||||
Keys serialize to their string value,
|
||||
unless they exist in the `rename` dict.
|
||||
"""
|
||||
return self.rename.get(smart_str(key), smart_str(key))
|
||||
|
||||
def serialize_val(self, key, obj, related_info):
|
||||
"""
|
||||
Convert a model field or dict value into a serializable representation.
|
||||
"""
|
||||
related_serializer = self.get_related_serializer(related_info)
|
||||
|
||||
if self.depth is None:
|
||||
depth = None
|
||||
elif self.depth <= 0:
|
||||
return self.serialize_max_depth(obj)
|
||||
else:
|
||||
depth = self.depth - 1
|
||||
|
||||
if obj in self.stack:
|
||||
return self.serialize_recursion(obj)
|
||||
else:
|
||||
stack = self.stack[:]
|
||||
stack.append(obj)
|
||||
|
||||
return related_serializer(depth=depth, stack=stack).serialize(
|
||||
obj, request=getattr(self, 'request', None))
|
||||
|
||||
def serialize_max_depth(self, obj):
|
||||
"""
|
||||
Determine how objects should be serialized once `depth` is exceeded.
|
||||
The default behavior is to ignore the field.
|
||||
"""
|
||||
raise _SkipField
|
||||
|
||||
def serialize_recursion(self, obj):
|
||||
"""
|
||||
Determine how objects should be serialized if recursion occurs.
|
||||
The default behavior is to ignore the field.
|
||||
"""
|
||||
raise _SkipField
|
||||
|
||||
def serialize_model(self, instance):
|
||||
"""
|
||||
Given a model instance or dict, serialize it to a dict..
|
||||
"""
|
||||
data = {}
|
||||
# Append the instance itself to the stack so that you never iterate
|
||||
# back into the first object.
|
||||
self.stack.append(instance)
|
||||
|
||||
fields = self.get_fields(instance)
|
||||
|
||||
# serialize each required field
|
||||
for fname, related_info in _fields_to_list(fields):
|
||||
try:
|
||||
# we first check for a method 'fname' on self,
|
||||
# 'fname's signature must be 'def fname(self, instance)'
|
||||
meth = getattr(self, fname, None)
|
||||
if (inspect.ismethod(meth) and
|
||||
len(inspect.getargspec(meth)[0]) == 2):
|
||||
obj = meth(instance)
|
||||
elif hasattr(instance, '__contains__') and fname in instance:
|
||||
# then check for a key 'fname' on the instance
|
||||
obj = instance[fname]
|
||||
elif hasattr(instance, smart_str(fname)):
|
||||
# finally check for an attribute 'fname' on the instance
|
||||
obj = getattr(instance, fname)
|
||||
else:
|
||||
continue
|
||||
|
||||
key = self.serialize_key(fname)
|
||||
val = self.serialize_val(fname, obj, related_info)
|
||||
data[key] = val
|
||||
except _SkipField:
|
||||
pass
|
||||
|
||||
return data
|
||||
|
||||
def serialize_iter(self, obj):
|
||||
"""
|
||||
Convert iterables into a serializable representation.
|
||||
"""
|
||||
return [self.serialize(item) for item in obj]
|
||||
|
||||
def serialize_func(self, obj):
|
||||
"""
|
||||
Convert no-arg methods and functions into a serializable representation.
|
||||
"""
|
||||
return self.serialize(obj())
|
||||
|
||||
def serialize_manager(self, obj):
|
||||
"""
|
||||
Convert a model manager into a serializable representation.
|
||||
"""
|
||||
return self.serialize_iter(obj.all())
|
||||
|
||||
def serialize_fallback(self, obj):
|
||||
"""
|
||||
Convert any unhandled object into a serializable representation.
|
||||
"""
|
||||
return smart_unicode(obj, strings_only=True)
|
||||
|
||||
def serialize(self, obj, request=None):
|
||||
"""
|
||||
Convert any object into a serializable representation.
|
||||
"""
|
||||
|
||||
# Request from related serializer.
|
||||
if request is not None:
|
||||
self.request = request
|
||||
|
||||
if isinstance(obj, (dict, models.Model)):
|
||||
# Model instances & dictionaries
|
||||
return self.serialize_model(obj)
|
||||
elif isinstance(obj, (tuple, list, set, QuerySet, RawQuerySet, types.GeneratorType)):
|
||||
# basic iterables
|
||||
return self.serialize_iter(obj)
|
||||
elif isinstance(obj, models.Manager):
|
||||
# Manager objects
|
||||
return self.serialize_manager(obj)
|
||||
elif inspect.isfunction(obj) and not inspect.getargspec(obj)[0]:
|
||||
# function with no args
|
||||
return self.serialize_func(obj)
|
||||
elif inspect.ismethod(obj) and len(inspect.getargspec(obj)[0]) <= 1:
|
||||
# bound method
|
||||
return self.serialize_func(obj)
|
||||
|
||||
# Protected types are passed through as is.
|
||||
# (i.e. Primitives like None, numbers, dates, and Decimals.)
|
||||
if is_protected_type(obj):
|
||||
return obj
|
||||
|
||||
# All other values are converted to string.
|
||||
return self.serialize_fallback(obj)
|
File diff suppressed because it is too large
Load Diff
|
@ -1,8 +0,0 @@
|
|||
{% autoescape off %}{{ name }}
|
||||
|
||||
{{ description }}
|
||||
|
||||
HTTP/1.0 {{ response.status }} {{ response.status_text }}
|
||||
{% for key, val in response.headers.items %}{{ key }}: {{ val }}
|
||||
{% endfor %}
|
||||
{{ content }}{% endautoescape %}
|
|
@ -1,150 +0,0 @@
|
|||
{% load url from future %}
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
|
||||
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
|
||||
{% load urlize_quoted_links %}
|
||||
{% load add_query_param %}
|
||||
{% load static %}
|
||||
<html xmlns="http://www.w3.org/1999/xhtml">
|
||||
<head>
|
||||
<link rel="stylesheet" type="text/css" href='{% get_static_prefix %}djangorestframework/css/style.css'/>
|
||||
{% block extrastyle %}{% endblock %}
|
||||
<title>{% block title %}Django REST framework - {{ name }}{% endblock %}</title>
|
||||
{% block extrahead %}{% endblock %}
|
||||
{% block blockbots %}<meta name="robots" content="NONE,NOARCHIVE" />{% endblock %}
|
||||
</head>
|
||||
<body class="{% block bodyclass %}{% endblock %}">
|
||||
<div id="container">
|
||||
|
||||
<div id="header">
|
||||
<div id="branding">
|
||||
<h1 id="site-name">{% block branding %}<a href='http://django-rest-framework.org'>Django REST framework</a> <span class="version"> v {{ version }}</span>{% endblock %}</h1>
|
||||
</div>
|
||||
<div id="user-tools">
|
||||
{% block userlinks %}
|
||||
{% if user.is_active %}
|
||||
Welcome, {{ user }}.
|
||||
<a href='{% url 'djangorestframework:logout' %}?next={{ request.path }}'>Log out</a>
|
||||
{% else %}
|
||||
Anonymous
|
||||
<a href='{% url 'djangorestframework:login' %}?next={{ request.path }}'>Log in</a>
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
</div>
|
||||
{% block nav-global %}{% endblock %}
|
||||
</div>
|
||||
|
||||
<div class="breadcrumbs">
|
||||
{% block breadcrumbs %}
|
||||
{% for breadcrumb_name, breadcrumb_url in breadcrumblist %}
|
||||
<a href="{{ breadcrumb_url }}">{{ breadcrumb_name }}</a> {% if not forloop.last %}›{% endif %}
|
||||
{% endfor %}
|
||||
{% endblock %}
|
||||
</div>
|
||||
|
||||
<!-- Content -->
|
||||
<div id="content" class="{% block coltype %}colM{% endblock %}">
|
||||
|
||||
{% if 'OPTIONS' in view.allowed_methods %}
|
||||
<form action="{{ request.get_full_path }}" method="post">
|
||||
{% csrf_token %}
|
||||
<input type="hidden" name="{{ METHOD_PARAM }}" value="OPTIONS" />
|
||||
<input type="submit" value="OPTIONS" class="default" />
|
||||
</form>
|
||||
{% endif %}
|
||||
|
||||
<div class='content-main'>
|
||||
<h1>{{ name }}</h1>
|
||||
<p>{{ description }}</p>
|
||||
<div class='module'>
|
||||
<pre><b>{{ response.status }} {{ response.status_text }}</b>{% autoescape off %}
|
||||
{% for key, val in response.headers.items %}<b>{{ key }}:</b> {{ val|urlize_quoted_links }}
|
||||
{% endfor %}
|
||||
{{ content|urlize_quoted_links }}</pre>{% endautoescape %}</div>
|
||||
|
||||
{% if 'GET' in view.allowed_methods %}
|
||||
<form>
|
||||
<fieldset class='module aligned'>
|
||||
<h2>GET {{ name }}</h2>
|
||||
<div class='submit-row' style='margin: 0; border: 0'>
|
||||
<a href='{{ request.get_full_path }}' rel="nofollow" style='float: left'>GET</a>
|
||||
{% for format in available_formats %}
|
||||
{% with FORMAT_PARAM|add:"="|add:format as param %}
|
||||
[<a href='{{ request.get_full_path|add_query_param:param }}' rel="nofollow">{{ format }}</a>]
|
||||
{% endwith %}
|
||||
{% endfor %}
|
||||
</div>
|
||||
</fieldset>
|
||||
</form>
|
||||
{% endif %}
|
||||
|
||||
{# Only display the POST/PUT/DELETE forms if method tunneling via POST forms is enabled and the user has permissions on this view. #}
|
||||
{% if METHOD_PARAM and response.status != 403 %}
|
||||
|
||||
{% if 'POST' in view.allowed_methods %}
|
||||
<form action="{{ request.get_full_path }}" method="post" {% if post_form.is_multipart %}enctype="multipart/form-data"{% endif %}>
|
||||
<fieldset class='module aligned'>
|
||||
<h2>POST {{ name }}</h2>
|
||||
{% csrf_token %}
|
||||
{{ post_form.non_field_errors }}
|
||||
{% for field in post_form %}
|
||||
<div class='form-row'>
|
||||
{{ field.label_tag }}
|
||||
{{ field }}
|
||||
<span class='help'>{{ field.help_text }}</span>
|
||||
{{ field.errors }}
|
||||
</div>
|
||||
{% endfor %}
|
||||
<div class='submit-row' style='margin: 0; border: 0'>
|
||||
<input type="submit" value="POST" class="default" />
|
||||
</div>
|
||||
</fieldset>
|
||||
</form>
|
||||
{% endif %}
|
||||
|
||||
{% if 'PUT' in view.allowed_methods %}
|
||||
<form action="{{ request.get_full_path }}" method="post" {% if put_form.is_multipart %}enctype="multipart/form-data"{% endif %}>
|
||||
<fieldset class='module aligned'>
|
||||
<h2>PUT {{ name }}</h2>
|
||||
<input type="hidden" name="{{ METHOD_PARAM }}" value="PUT" />
|
||||
{% csrf_token %}
|
||||
{{ put_form.non_field_errors }}
|
||||
{% for field in put_form %}
|
||||
<div class='form-row'>
|
||||
{{ field.label_tag }}
|
||||
{{ field }}
|
||||
<span class='help'>{{ field.help_text }}</span>
|
||||
{{ field.errors }}
|
||||
</div>
|
||||
{% endfor %}
|
||||
<div class='submit-row' style='margin: 0; border: 0'>
|
||||
<input type="submit" value="PUT" class="default" />
|
||||
</div>
|
||||
</fieldset>
|
||||
</form>
|
||||
{% endif %}
|
||||
|
||||
{% if 'DELETE' in view.allowed_methods %}
|
||||
<form action="{{ request.get_full_path }}" method="post">
|
||||
<fieldset class='module aligned'>
|
||||
<h2>DELETE {{ name }}</h2>
|
||||
{% csrf_token %}
|
||||
<input type="hidden" name="{{ METHOD_PARAM }}" value="DELETE" />
|
||||
<div class='submit-row' style='margin: 0; border: 0'>
|
||||
<input type="submit" value="DELETE" class="default" />
|
||||
</div>
|
||||
</fieldset>
|
||||
</form>
|
||||
{% endif %}
|
||||
|
||||
{% endif %}
|
||||
</div>
|
||||
<!-- END content-main -->
|
||||
|
||||
</div>
|
||||
<!-- END Content -->
|
||||
|
||||
{% block footer %}<div id="footer"></div>{% endblock %}
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
|
@ -1,45 +0,0 @@
|
|||
{% load static %}
|
||||
{% load url from future %}
|
||||
<html>
|
||||
|
||||
<head>
|
||||
<link rel="stylesheet" type="text/css" href='{% get_static_prefix %}djangorestframework/css/style.css'/>
|
||||
</head>
|
||||
|
||||
<body class="login">
|
||||
|
||||
<div id="container">
|
||||
|
||||
<div id="header">
|
||||
<div id="branding">
|
||||
<h1 id="site-name">Django REST framework</h1>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="content" class="colM">
|
||||
<div id="content-main">
|
||||
<form method="post" action="{% url 'djangorestframework:login' %}" id="login-form">
|
||||
{% csrf_token %}
|
||||
<div class="form-row">
|
||||
<label for="id_username">Username:</label> {{ form.username }}
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label for="id_password">Password:</label> {{ form.password }}
|
||||
<input type="hidden" name="next" value="{{ next }}" />
|
||||
</div>
|
||||
<div class="form-row">
|
||||
<label> </label><input type="submit" value="Log in">
|
||||
</div>
|
||||
</form>
|
||||
<script type="text/javascript">
|
||||
document.getElementById('id_username').focus()
|
||||
</script>
|
||||
</div>
|
||||
<br class="clear">
|
||||
</div>
|
||||
|
||||
<div id="footer"></div>
|
||||
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
|
@ -1,10 +0,0 @@
|
|||
from django.template import Library
|
||||
from urlobject import URLObject
|
||||
register = Library()
|
||||
|
||||
|
||||
def add_query_param(url, param):
|
||||
return unicode(URLObject(url).add_query_param(*param.split('=')))
|
||||
|
||||
|
||||
register.filter('add_query_param', add_query_param)
|
|
@ -1,13 +0,0 @@
|
|||
"""Force import of all modules in this package in order to get the standard test runner to pick up the tests. Yowzers."""
|
||||
import os
|
||||
|
||||
modules = [filename.rsplit('.', 1)[0]
|
||||
for filename in os.listdir(os.path.dirname(__file__))
|
||||
if filename.endswith('.py') and not filename.startswith('_')]
|
||||
__test__ = dict()
|
||||
|
||||
for module in modules:
|
||||
exec("from djangorestframework.tests.%s import __doc__ as module_doc" % module)
|
||||
exec("from djangorestframework.tests.%s import *" % module)
|
||||
__test__[module] = module_doc or ""
|
||||
|
|
@ -1,86 +0,0 @@
|
|||
from django.conf.urls.defaults import patterns, url, include
|
||||
from django.test import TestCase
|
||||
from djangorestframework.compat import RequestFactory
|
||||
from djangorestframework.views import View
|
||||
|
||||
|
||||
# See: http://www.useragentstring.com/
|
||||
MSIE_9_USER_AGENT = 'Mozilla/5.0 (Windows; U; MSIE 9.0; WIndows NT 9.0; en-US))'
|
||||
MSIE_8_USER_AGENT = 'Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; Media Center PC 4.0; SLCC1; .NET CLR 3.0.04320)'
|
||||
MSIE_7_USER_AGENT = 'Mozilla/5.0 (Windows; U; MSIE 7.0; Windows NT 6.0; en-US)'
|
||||
FIREFOX_4_0_USER_AGENT = 'Mozilla/5.0 (Windows; U; Windows NT 6.1; ru; rv:1.9.2.3) Gecko/20100401 Firefox/4.0 (.NET CLR 3.5.30729)'
|
||||
CHROME_11_0_USER_AGENT = 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.17 (KHTML, like Gecko) Chrome/11.0.655.0 Safari/534.17'
|
||||
SAFARI_5_0_USER_AGENT = 'Mozilla/5.0 (X11; U; Linux x86_64; en-ca) AppleWebKit/531.2+ (KHTML, like Gecko) Version/5.0 Safari/531.2+'
|
||||
OPERA_11_0_MSIE_USER_AGENT = 'Mozilla/4.0 (compatible; MSIE 8.0; X11; Linux x86_64; pl) Opera 11.00'
|
||||
OPERA_11_0_OPERA_USER_AGENT = 'Opera/9.80 (X11; Linux x86_64; U; pl) Presto/2.7.62 Version/11.00'
|
||||
|
||||
|
||||
urlpatterns = patterns('',
|
||||
url(r'^api', include('djangorestframework.urls', namespace='djangorestframework'))
|
||||
)
|
||||
|
||||
|
||||
class UserAgentMungingTest(TestCase):
|
||||
"""
|
||||
We need to fake up the accept headers when we deal with MSIE. Blergh.
|
||||
http://www.gethifi.com/blog/browser-rest-http-accept-headers
|
||||
"""
|
||||
|
||||
urls = 'djangorestframework.tests.accept'
|
||||
|
||||
def setUp(self):
|
||||
|
||||
class MockView(View):
|
||||
permissions = ()
|
||||
|
||||
def get(self, request):
|
||||
return {'a':1, 'b':2, 'c':3}
|
||||
|
||||
self.req = RequestFactory()
|
||||
self.MockView = MockView
|
||||
self.view = MockView.as_view()
|
||||
|
||||
def test_munge_msie_accept_header(self):
|
||||
"""Send MSIE user agent strings and ensure that we get an HTML response,
|
||||
even if we set a */* accept header."""
|
||||
for user_agent in (MSIE_9_USER_AGENT,
|
||||
MSIE_8_USER_AGENT,
|
||||
MSIE_7_USER_AGENT):
|
||||
req = self.req.get('/', HTTP_ACCEPT='*/*', HTTP_USER_AGENT=user_agent)
|
||||
resp = self.view(req)
|
||||
self.assertEqual(resp['Content-Type'], 'text/html')
|
||||
|
||||
def test_dont_munge_msie_with_x_requested_with_header(self):
|
||||
"""Send MSIE user agent strings, and an X-Requested-With header, and
|
||||
ensure that we get a JSON response if we set a */* Accept header."""
|
||||
for user_agent in (MSIE_9_USER_AGENT,
|
||||
MSIE_8_USER_AGENT,
|
||||
MSIE_7_USER_AGENT):
|
||||
req = self.req.get('/', HTTP_ACCEPT='*/*', HTTP_USER_AGENT=user_agent, HTTP_X_REQUESTED_WITH='XMLHttpRequest')
|
||||
resp = self.view(req)
|
||||
self.assertEqual(resp['Content-Type'], 'application/json')
|
||||
|
||||
def test_dont_rewrite_msie_accept_header(self):
|
||||
"""Turn off _IGNORE_IE_ACCEPT_HEADER, send MSIE user agent strings and ensure
|
||||
that we get a JSON response if we set a */* accept header."""
|
||||
view = self.MockView.as_view(_IGNORE_IE_ACCEPT_HEADER=False)
|
||||
|
||||
for user_agent in (MSIE_9_USER_AGENT,
|
||||
MSIE_8_USER_AGENT,
|
||||
MSIE_7_USER_AGENT):
|
||||
req = self.req.get('/', HTTP_ACCEPT='*/*', HTTP_USER_AGENT=user_agent)
|
||||
resp = view(req)
|
||||
self.assertEqual(resp['Content-Type'], 'application/json')
|
||||
|
||||
def test_dont_munge_nice_browsers_accept_header(self):
|
||||
"""Send Non-MSIE user agent strings and ensure that we get a JSON response,
|
||||
if we set a */* Accept header. (Other browsers will correctly set the Accept header)"""
|
||||
for user_agent in (FIREFOX_4_0_USER_AGENT,
|
||||
CHROME_11_0_USER_AGENT,
|
||||
SAFARI_5_0_USER_AGENT,
|
||||
OPERA_11_0_MSIE_USER_AGENT,
|
||||
OPERA_11_0_OPERA_USER_AGENT):
|
||||
req = self.req.get('/', HTTP_ACCEPT='*/*', HTTP_USER_AGENT=user_agent)
|
||||
resp = self.view(req)
|
||||
self.assertEqual(resp['Content-Type'], 'application/json')
|
||||
|
|
@ -1,233 +0,0 @@
|
|||
"""
|
||||
Tests for content parsing, and form-overloaded content parsing.
|
||||
"""
|
||||
from django.conf.urls.defaults import patterns
|
||||
from django.contrib.auth.models import User
|
||||
from django.test import TestCase, Client
|
||||
from djangorestframework import status
|
||||
from djangorestframework.authentication import UserLoggedInAuthentication
|
||||
from djangorestframework.compat import RequestFactory, unittest
|
||||
from djangorestframework.mixins import RequestMixin
|
||||
from djangorestframework.parsers import FormParser, MultiPartParser, \
|
||||
PlainTextParser, JSONParser
|
||||
from djangorestframework.response import Response
|
||||
from djangorestframework.views import View
|
||||
|
||||
class MockView(View):
|
||||
authentication = (UserLoggedInAuthentication,)
|
||||
def post(self, request):
|
||||
if request.POST.get('example') is not None:
|
||||
return Response(status.HTTP_200_OK)
|
||||
|
||||
return Response(status.INTERNAL_SERVER_ERROR)
|
||||
|
||||
urlpatterns = patterns('',
|
||||
(r'^$', MockView.as_view()),
|
||||
)
|
||||
|
||||
class TestContentParsing(TestCase):
|
||||
def setUp(self):
|
||||
self.req = RequestFactory()
|
||||
|
||||
def ensure_determines_no_content_GET(self, view):
|
||||
"""Ensure view.DATA returns None for GET request with no content."""
|
||||
view.request = self.req.get('/')
|
||||
self.assertEqual(view.DATA, None)
|
||||
|
||||
def ensure_determines_no_content_HEAD(self, view):
|
||||
"""Ensure view.DATA returns None for HEAD request."""
|
||||
view.request = self.req.head('/')
|
||||
self.assertEqual(view.DATA, None)
|
||||
|
||||
def ensure_determines_form_content_POST(self, view):
|
||||
"""Ensure view.DATA returns content for POST request with form content."""
|
||||
form_data = {'qwerty': 'uiop'}
|
||||
view.parsers = (FormParser, MultiPartParser)
|
||||
view.request = self.req.post('/', data=form_data)
|
||||
self.assertEqual(view.DATA.items(), form_data.items())
|
||||
|
||||
def ensure_determines_non_form_content_POST(self, view):
|
||||
"""Ensure view.RAW_CONTENT returns content for POST request with non-form content."""
|
||||
content = 'qwerty'
|
||||
content_type = 'text/plain'
|
||||
view.parsers = (PlainTextParser,)
|
||||
view.request = self.req.post('/', content, content_type=content_type)
|
||||
self.assertEqual(view.DATA, content)
|
||||
|
||||
def ensure_determines_form_content_PUT(self, view):
|
||||
"""Ensure view.RAW_CONTENT returns content for PUT request with form content."""
|
||||
form_data = {'qwerty': 'uiop'}
|
||||
view.parsers = (FormParser, MultiPartParser)
|
||||
view.request = self.req.put('/', data=form_data)
|
||||
self.assertEqual(view.DATA.items(), form_data.items())
|
||||
|
||||
def ensure_determines_non_form_content_PUT(self, view):
|
||||
"""Ensure view.RAW_CONTENT returns content for PUT request with non-form content."""
|
||||
content = 'qwerty'
|
||||
content_type = 'text/plain'
|
||||
view.parsers = (PlainTextParser,)
|
||||
view.request = self.req.post('/', content, content_type=content_type)
|
||||
self.assertEqual(view.DATA, content)
|
||||
|
||||
def test_standard_behaviour_determines_no_content_GET(self):
|
||||
"""Ensure view.DATA returns None for GET request with no content."""
|
||||
self.ensure_determines_no_content_GET(RequestMixin())
|
||||
|
||||
def test_standard_behaviour_determines_no_content_HEAD(self):
|
||||
"""Ensure view.DATA returns None for HEAD request."""
|
||||
self.ensure_determines_no_content_HEAD(RequestMixin())
|
||||
|
||||
def test_standard_behaviour_determines_form_content_POST(self):
|
||||
"""Ensure view.DATA returns content for POST request with form content."""
|
||||
self.ensure_determines_form_content_POST(RequestMixin())
|
||||
|
||||
def test_standard_behaviour_determines_non_form_content_POST(self):
|
||||
"""Ensure view.DATA returns content for POST request with non-form content."""
|
||||
self.ensure_determines_non_form_content_POST(RequestMixin())
|
||||
|
||||
# def test_standard_behaviour_determines_form_content_PUT(self):
|
||||
# """Ensure view.DATA returns content for PUT request with form content."""
|
||||
# self.ensure_determines_form_content_PUT(RequestMixin())
|
||||
|
||||
def test_standard_behaviour_determines_non_form_content_PUT(self):
|
||||
"""Ensure view.DATA returns content for PUT request with non-form content."""
|
||||
self.ensure_determines_non_form_content_PUT(RequestMixin())
|
||||
|
||||
def test_overloaded_behaviour_allows_content_tunnelling(self):
|
||||
"""Ensure request.DATA returns content for overloaded POST request"""
|
||||
content = 'qwerty'
|
||||
content_type = 'text/plain'
|
||||
view = RequestMixin()
|
||||
form_data = {view._CONTENT_PARAM: content,
|
||||
view._CONTENTTYPE_PARAM: content_type}
|
||||
view.request = self.req.post('/', form_data)
|
||||
view.parsers = (PlainTextParser,)
|
||||
self.assertEqual(view.DATA, content)
|
||||
|
||||
def test_accessing_post_after_data_form(self):
|
||||
"""Ensures request.POST can be accessed after request.DATA in form request"""
|
||||
form_data = {'qwerty': 'uiop'}
|
||||
view = RequestMixin()
|
||||
view.parsers = (FormParser, MultiPartParser)
|
||||
view.request = self.req.post('/', data=form_data)
|
||||
|
||||
self.assertEqual(view.DATA.items(), form_data.items())
|
||||
self.assertEqual(view.request.POST.items(), form_data.items())
|
||||
|
||||
@unittest.skip('This test was disabled some time ago for some reason')
|
||||
def test_accessing_post_after_data_for_json(self):
|
||||
"""Ensures request.POST can be accessed after request.DATA in json request"""
|
||||
from django.utils import simplejson as json
|
||||
|
||||
data = {'qwerty': 'uiop'}
|
||||
content = json.dumps(data)
|
||||
content_type = 'application/json'
|
||||
|
||||
view = RequestMixin()
|
||||
view.parsers = (JSONParser,)
|
||||
|
||||
view.request = self.req.post('/', content, content_type=content_type)
|
||||
|
||||
self.assertEqual(view.DATA.items(), data.items())
|
||||
self.assertEqual(view.request.POST.items(), [])
|
||||
|
||||
def test_accessing_post_after_data_for_overloaded_json(self):
|
||||
"""Ensures request.POST can be accessed after request.DATA in overloaded json request"""
|
||||
from django.utils import simplejson as json
|
||||
|
||||
data = {'qwerty': 'uiop'}
|
||||
content = json.dumps(data)
|
||||
content_type = 'application/json'
|
||||
|
||||
view = RequestMixin()
|
||||
view.parsers = (JSONParser,)
|
||||
|
||||
form_data = {view._CONTENT_PARAM: content,
|
||||
view._CONTENTTYPE_PARAM: content_type}
|
||||
|
||||
view.request = self.req.post('/', data=form_data)
|
||||
|
||||
self.assertEqual(view.DATA.items(), data.items())
|
||||
self.assertEqual(view.request.POST.items(), form_data.items())
|
||||
|
||||
def test_accessing_data_after_post_form(self):
|
||||
"""Ensures request.DATA can be accessed after request.POST in form request"""
|
||||
form_data = {'qwerty': 'uiop'}
|
||||
view = RequestMixin()
|
||||
view.parsers = (FormParser, MultiPartParser)
|
||||
view.request = self.req.post('/', data=form_data)
|
||||
|
||||
self.assertEqual(view.request.POST.items(), form_data.items())
|
||||
self.assertEqual(view.DATA.items(), form_data.items())
|
||||
|
||||
def test_accessing_data_after_post_for_json(self):
|
||||
"""Ensures request.DATA can be accessed after request.POST in json request"""
|
||||
from django.utils import simplejson as json
|
||||
|
||||
data = {'qwerty': 'uiop'}
|
||||
content = json.dumps(data)
|
||||
content_type = 'application/json'
|
||||
|
||||
view = RequestMixin()
|
||||
view.parsers = (JSONParser,)
|
||||
|
||||
view.request = self.req.post('/', content, content_type=content_type)
|
||||
|
||||
post_items = view.request.POST.items()
|
||||
|
||||
self.assertEqual(len(post_items), 1)
|
||||
self.assertEqual(len(post_items[0]), 2)
|
||||
self.assertEqual(post_items[0][0], content)
|
||||
self.assertEqual(view.DATA.items(), data.items())
|
||||
|
||||
def test_accessing_data_after_post_for_overloaded_json(self):
|
||||
"""Ensures request.DATA can be accessed after request.POST in overloaded json request"""
|
||||
from django.utils import simplejson as json
|
||||
|
||||
data = {'qwerty': 'uiop'}
|
||||
content = json.dumps(data)
|
||||
content_type = 'application/json'
|
||||
|
||||
view = RequestMixin()
|
||||
view.parsers = (JSONParser,)
|
||||
|
||||
form_data = {view._CONTENT_PARAM: content,
|
||||
view._CONTENTTYPE_PARAM: content_type}
|
||||
|
||||
view.request = self.req.post('/', data=form_data)
|
||||
|
||||
self.assertEqual(view.request.POST.items(), form_data.items())
|
||||
self.assertEqual(view.DATA.items(), data.items())
|
||||
|
||||
class TestContentParsingWithAuthentication(TestCase):
|
||||
urls = 'djangorestframework.tests.content'
|
||||
|
||||
def setUp(self):
|
||||
self.csrf_client = Client(enforce_csrf_checks=True)
|
||||
self.username = 'john'
|
||||
self.email = 'lennon@thebeatles.com'
|
||||
self.password = 'password'
|
||||
self.user = User.objects.create_user(self.username, self.email, self.password)
|
||||
self.req = RequestFactory()
|
||||
|
||||
def test_user_logged_in_authentication_has_post_when_not_logged_in(self):
|
||||
"""Ensures request.POST exists after UserLoggedInAuthentication when user doesn't log in"""
|
||||
content = {'example': 'example'}
|
||||
|
||||
response = self.client.post('/', content)
|
||||
self.assertEqual(status.HTTP_200_OK, response.status_code, "POST data is malformed")
|
||||
|
||||
response = self.csrf_client.post('/', content)
|
||||
self.assertEqual(status.HTTP_200_OK, response.status_code, "POST data is malformed")
|
||||
|
||||
# def test_user_logged_in_authentication_has_post_when_logged_in(self):
|
||||
# """Ensures request.POST exists after UserLoggedInAuthentication when user does log in"""
|
||||
# self.client.login(username='john', password='password')
|
||||
# self.csrf_client.login(username='john', password='password')
|
||||
# content = {'example': 'example'}
|
||||
|
||||
# response = self.client.post('/', content)
|
||||
# self.assertEqual(status.OK, response.status_code, "POST data is malformed")
|
||||
|
||||
# response = self.csrf_client.post('/', content)
|
||||
# self.assertEqual(status.OK, response.status_code, "POST data is malformed")
|
|
@ -1,32 +0,0 @@
|
|||
from django.test import TestCase
|
||||
from django import forms
|
||||
from djangorestframework.compat import RequestFactory
|
||||
from djangorestframework.views import View
|
||||
from djangorestframework.resources import FormResource
|
||||
import StringIO
|
||||
|
||||
class UploadFilesTests(TestCase):
|
||||
"""Check uploading of files"""
|
||||
def setUp(self):
|
||||
self.factory = RequestFactory()
|
||||
|
||||
def test_upload_file(self):
|
||||
|
||||
class FileForm(forms.Form):
|
||||
file = forms.FileField()
|
||||
|
||||
class MockView(View):
|
||||
permissions = ()
|
||||
form = FileForm
|
||||
|
||||
def post(self, request, *args, **kwargs):
|
||||
return {'FILE_NAME': self.CONTENT['file'].name,
|
||||
'FILE_CONTENT': self.CONTENT['file'].read()}
|
||||
|
||||
file = StringIO.StringIO('stuff')
|
||||
file.name = 'stuff.txt'
|
||||
request = self.factory.post('/', {'file': file})
|
||||
view = MockView.as_view()
|
||||
response = view(request)
|
||||
self.assertEquals(response.content, '{"FILE_CONTENT": "stuff", "FILE_NAME": "stuff.txt"}')
|
||||
|
|
@ -1,32 +0,0 @@
|
|||
from django.test import TestCase
|
||||
from djangorestframework.compat import RequestFactory
|
||||
from djangorestframework.mixins import RequestMixin
|
||||
|
||||
|
||||
class TestMethodOverloading(TestCase):
|
||||
def setUp(self):
|
||||
self.req = RequestFactory()
|
||||
|
||||
def test_standard_behaviour_determines_GET(self):
|
||||
"""GET requests identified"""
|
||||
view = RequestMixin()
|
||||
view.request = self.req.get('/')
|
||||
self.assertEqual(view.method, 'GET')
|
||||
|
||||
def test_standard_behaviour_determines_POST(self):
|
||||
"""POST requests identified"""
|
||||
view = RequestMixin()
|
||||
view.request = self.req.post('/')
|
||||
self.assertEqual(view.method, 'POST')
|
||||
|
||||
def test_overloaded_POST_behaviour_determines_overloaded_method(self):
|
||||
"""POST requests can be overloaded to another method by setting a reserved form field"""
|
||||
view = RequestMixin()
|
||||
view.request = self.req.post('/', {view._METHOD_PARAM: 'DELETE'})
|
||||
self.assertEqual(view.method, 'DELETE')
|
||||
|
||||
def test_HEAD_is_a_valid_method(self):
|
||||
"""HEAD requests identified"""
|
||||
view = RequestMixin()
|
||||
view.request = self.req.head('/')
|
||||
self.assertEqual(view.method, 'HEAD')
|
|
@ -1,291 +0,0 @@
|
|||
"""Tests for the mixin module"""
|
||||
from django.test import TestCase
|
||||
from django.utils import simplejson as json
|
||||
from djangorestframework import status
|
||||
from djangorestframework.compat import RequestFactory
|
||||
from django.contrib.auth.models import Group, User
|
||||
from djangorestframework.mixins import CreateModelMixin, PaginatorMixin, ReadModelMixin
|
||||
from djangorestframework.resources import ModelResource
|
||||
from djangorestframework.response import Response, ErrorResponse
|
||||
from djangorestframework.tests.models import CustomUser
|
||||
from djangorestframework.tests.testcases import TestModelsTestCase
|
||||
from djangorestframework.views import View
|
||||
|
||||
|
||||
class TestModelRead(TestModelsTestCase):
|
||||
"""Tests on ReadModelMixin"""
|
||||
|
||||
def setUp(self):
|
||||
super(TestModelRead, self).setUp()
|
||||
self.req = RequestFactory()
|
||||
|
||||
def test_read(self):
|
||||
Group.objects.create(name='other group')
|
||||
group = Group.objects.create(name='my group')
|
||||
|
||||
class GroupResource(ModelResource):
|
||||
model = Group
|
||||
|
||||
request = self.req.get('/groups')
|
||||
mixin = ReadModelMixin()
|
||||
mixin.resource = GroupResource
|
||||
|
||||
response = mixin.get(request, id=group.id)
|
||||
self.assertEquals(group.name, response.name)
|
||||
|
||||
def test_read_404(self):
|
||||
class GroupResource(ModelResource):
|
||||
model = Group
|
||||
|
||||
request = self.req.get('/groups')
|
||||
mixin = ReadModelMixin()
|
||||
mixin.resource = GroupResource
|
||||
|
||||
self.assertRaises(ErrorResponse, mixin.get, request, id=12345)
|
||||
|
||||
|
||||
class TestModelCreation(TestModelsTestCase):
|
||||
"""Tests on CreateModelMixin"""
|
||||
|
||||
def setUp(self):
|
||||
super(TestModelsTestCase, self).setUp()
|
||||
self.req = RequestFactory()
|
||||
|
||||
def test_creation(self):
|
||||
self.assertEquals(0, Group.objects.count())
|
||||
|
||||
class GroupResource(ModelResource):
|
||||
model = Group
|
||||
|
||||
form_data = {'name': 'foo'}
|
||||
request = self.req.post('/groups', data=form_data)
|
||||
mixin = CreateModelMixin()
|
||||
mixin.resource = GroupResource
|
||||
mixin.CONTENT = form_data
|
||||
|
||||
response = mixin.post(request)
|
||||
self.assertEquals(1, Group.objects.count())
|
||||
self.assertEquals('foo', response.cleaned_content.name)
|
||||
|
||||
def test_creation_with_m2m_relation(self):
|
||||
class UserResource(ModelResource):
|
||||
model = User
|
||||
|
||||
def url(self, instance):
|
||||
return "/users/%i" % instance.id
|
||||
|
||||
group = Group(name='foo')
|
||||
group.save()
|
||||
|
||||
form_data = {
|
||||
'username': 'bar',
|
||||
'password': 'baz',
|
||||
'groups': [group.id]
|
||||
}
|
||||
request = self.req.post('/groups', data=form_data)
|
||||
cleaned_data = dict(form_data)
|
||||
cleaned_data['groups'] = [group]
|
||||
mixin = CreateModelMixin()
|
||||
mixin.resource = UserResource
|
||||
mixin.CONTENT = cleaned_data
|
||||
|
||||
response = mixin.post(request)
|
||||
self.assertEquals(1, User.objects.count())
|
||||
self.assertEquals(1, response.cleaned_content.groups.count())
|
||||
self.assertEquals('foo', response.cleaned_content.groups.all()[0].name)
|
||||
|
||||
def test_creation_with_m2m_relation_through(self):
|
||||
"""
|
||||
Tests creation where the m2m relation uses a through table
|
||||
"""
|
||||
class UserResource(ModelResource):
|
||||
model = CustomUser
|
||||
|
||||
def url(self, instance):
|
||||
return "/customusers/%i" % instance.id
|
||||
|
||||
form_data = {'username': 'bar0', 'groups': []}
|
||||
request = self.req.post('/groups', data=form_data)
|
||||
cleaned_data = dict(form_data)
|
||||
cleaned_data['groups'] = []
|
||||
mixin = CreateModelMixin()
|
||||
mixin.resource = UserResource
|
||||
mixin.CONTENT = cleaned_data
|
||||
|
||||
response = mixin.post(request)
|
||||
self.assertEquals(1, CustomUser.objects.count())
|
||||
self.assertEquals(0, response.cleaned_content.groups.count())
|
||||
|
||||
group = Group(name='foo1')
|
||||
group.save()
|
||||
|
||||
form_data = {'username': 'bar1', 'groups': [group.id]}
|
||||
request = self.req.post('/groups', data=form_data)
|
||||
cleaned_data = dict(form_data)
|
||||
cleaned_data['groups'] = [group]
|
||||
mixin = CreateModelMixin()
|
||||
mixin.resource = UserResource
|
||||
mixin.CONTENT = cleaned_data
|
||||
|
||||
response = mixin.post(request)
|
||||
self.assertEquals(2, CustomUser.objects.count())
|
||||
self.assertEquals(1, response.cleaned_content.groups.count())
|
||||
self.assertEquals('foo1', response.cleaned_content.groups.all()[0].name)
|
||||
|
||||
group2 = Group(name='foo2')
|
||||
group2.save()
|
||||
|
||||
form_data = {'username': 'bar2', 'groups': [group.id, group2.id]}
|
||||
request = self.req.post('/groups', data=form_data)
|
||||
cleaned_data = dict(form_data)
|
||||
cleaned_data['groups'] = [group, group2]
|
||||
mixin = CreateModelMixin()
|
||||
mixin.resource = UserResource
|
||||
mixin.CONTENT = cleaned_data
|
||||
|
||||
response = mixin.post(request)
|
||||
self.assertEquals(3, CustomUser.objects.count())
|
||||
self.assertEquals(2, response.cleaned_content.groups.count())
|
||||
self.assertEquals('foo1', response.cleaned_content.groups.all()[0].name)
|
||||
self.assertEquals('foo2', response.cleaned_content.groups.all()[1].name)
|
||||
|
||||
|
||||
class MockPaginatorView(PaginatorMixin, View):
|
||||
total = 60
|
||||
|
||||
def get(self, request):
|
||||
return range(0, self.total)
|
||||
|
||||
def post(self, request):
|
||||
return Response(status.HTTP_201_CREATED, {'status': 'OK'})
|
||||
|
||||
|
||||
class TestPagination(TestCase):
|
||||
def setUp(self):
|
||||
self.req = RequestFactory()
|
||||
|
||||
def test_default_limit(self):
|
||||
""" Tests if pagination works without overwriting the limit """
|
||||
request = self.req.get('/paginator')
|
||||
response = MockPaginatorView.as_view()(request)
|
||||
|
||||
content = json.loads(response.content)
|
||||
|
||||
self.assertEqual(response.status_code, status.HTTP_200_OK)
|
||||
self.assertEqual(MockPaginatorView.total, content['total'])
|
||||
self.assertEqual(MockPaginatorView.limit, content['per_page'])
|
||||
|
||||
self.assertEqual(range(0, MockPaginatorView.limit), content['results'])
|
||||
|
||||
def test_overwriting_limit(self):
|
||||
""" Tests if the limit can be overwritten """
|
||||
limit = 10
|
||||
|
||||
request = self.req.get('/paginator')
|
||||
response = MockPaginatorView.as_view(limit=limit)(request)
|
||||
|
||||
content = json.loads(response.content)
|
||||
|
||||
self.assertEqual(response.status_code, status.HTTP_200_OK)
|
||||
self.assertEqual(content['per_page'], limit)
|
||||
|
||||
self.assertEqual(range(0, limit), content['results'])
|
||||
|
||||
def test_limit_param(self):
|
||||
""" Tests if the client can set the limit """
|
||||
from math import ceil
|
||||
|
||||
limit = 5
|
||||
num_pages = int(ceil(MockPaginatorView.total / float(limit)))
|
||||
|
||||
request = self.req.get('/paginator/?limit=%d' % limit)
|
||||
response = MockPaginatorView.as_view()(request)
|
||||
|
||||
content = json.loads(response.content)
|
||||
|
||||
self.assertEqual(response.status_code, status.HTTP_200_OK)
|
||||
self.assertEqual(MockPaginatorView.total, content['total'])
|
||||
self.assertEqual(limit, content['per_page'])
|
||||
self.assertEqual(num_pages, content['pages'])
|
||||
|
||||
def test_exceeding_limit(self):
|
||||
""" Makes sure the client cannot exceed the default limit """
|
||||
from math import ceil
|
||||
|
||||
limit = MockPaginatorView.limit + 10
|
||||
num_pages = int(ceil(MockPaginatorView.total / float(limit)))
|
||||
|
||||
request = self.req.get('/paginator/?limit=%d' % limit)
|
||||
response = MockPaginatorView.as_view()(request)
|
||||
|
||||
content = json.loads(response.content)
|
||||
|
||||
self.assertEqual(response.status_code, status.HTTP_200_OK)
|
||||
self.assertEqual(MockPaginatorView.total, content['total'])
|
||||
self.assertNotEqual(limit, content['per_page'])
|
||||
self.assertNotEqual(num_pages, content['pages'])
|
||||
self.assertEqual(MockPaginatorView.limit, content['per_page'])
|
||||
|
||||
def test_only_works_for_get(self):
|
||||
""" Pagination should only work for GET requests """
|
||||
request = self.req.post('/paginator', data={'content': 'spam'})
|
||||
response = MockPaginatorView.as_view()(request)
|
||||
|
||||
content = json.loads(response.content)
|
||||
|
||||
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
|
||||
self.assertEqual(None, content.get('per_page'))
|
||||
self.assertEqual('OK', content['status'])
|
||||
|
||||
def test_non_int_page(self):
|
||||
""" Tests that it can handle invalid values """
|
||||
request = self.req.get('/paginator/?page=spam')
|
||||
response = MockPaginatorView.as_view()(request)
|
||||
|
||||
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
|
||||
|
||||
def test_page_range(self):
|
||||
""" Tests that the page range is handle correctly """
|
||||
request = self.req.get('/paginator/?page=0')
|
||||
response = MockPaginatorView.as_view()(request)
|
||||
content = json.loads(response.content)
|
||||
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
|
||||
|
||||
request = self.req.get('/paginator/')
|
||||
response = MockPaginatorView.as_view()(request)
|
||||
content = json.loads(response.content)
|
||||
self.assertEqual(response.status_code, status.HTTP_200_OK)
|
||||
self.assertEqual(range(0, MockPaginatorView.limit), content['results'])
|
||||
|
||||
num_pages = content['pages']
|
||||
|
||||
request = self.req.get('/paginator/?page=%d' % num_pages)
|
||||
response = MockPaginatorView.as_view()(request)
|
||||
content = json.loads(response.content)
|
||||
self.assertEqual(response.status_code, status.HTTP_200_OK)
|
||||
self.assertEqual(range(MockPaginatorView.limit*(num_pages-1), MockPaginatorView.total), content['results'])
|
||||
|
||||
request = self.req.get('/paginator/?page=%d' % (num_pages + 1,))
|
||||
response = MockPaginatorView.as_view()(request)
|
||||
content = json.loads(response.content)
|
||||
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
|
||||
|
||||
def test_existing_query_parameters_are_preserved(self):
|
||||
""" Tests that existing query parameters are preserved when
|
||||
generating next/previous page links """
|
||||
request = self.req.get('/paginator/?foo=bar&another=something')
|
||||
response = MockPaginatorView.as_view()(request)
|
||||
content = json.loads(response.content)
|
||||
self.assertEqual(response.status_code, status.HTTP_200_OK)
|
||||
self.assertTrue('foo=bar' in content['next'])
|
||||
self.assertTrue('another=something' in content['next'])
|
||||
self.assertTrue('page=2' in content['next'])
|
||||
|
||||
def test_duplicate_parameters_are_not_created(self):
|
||||
""" Regression: ensure duplicate "page" parameters are not added to
|
||||
paginated URLs. So page 1 should contain ?page=2, not ?page=1&page=2 """
|
||||
request = self.req.get('/paginator/?page=1')
|
||||
response = MockPaginatorView.as_view()(request)
|
||||
content = json.loads(response.content)
|
||||
self.assertTrue('page=2' in content['next'])
|
||||
self.assertFalse('page=1' in content['next'])
|
|
@ -1,28 +0,0 @@
|
|||
from django.db import models
|
||||
from django.contrib.auth.models import Group
|
||||
|
||||
class CustomUser(models.Model):
|
||||
"""
|
||||
A custom user model, which uses a 'through' table for the foreign key
|
||||
"""
|
||||
username = models.CharField(max_length=255, unique=True)
|
||||
groups = models.ManyToManyField(
|
||||
to=Group, blank=True, null=True, through='UserGroupMap'
|
||||
)
|
||||
|
||||
@models.permalink
|
||||
def get_absolute_url(self):
|
||||
return ('custom_user', (), {
|
||||
'pk': self.id
|
||||
})
|
||||
|
||||
|
||||
class UserGroupMap(models.Model):
|
||||
user = models.ForeignKey(to=CustomUser)
|
||||
group = models.ForeignKey(to=Group)
|
||||
|
||||
@models.permalink
|
||||
def get_absolute_url(self):
|
||||
return ('user_group_map', (), {
|
||||
'pk': self.id
|
||||
})
|
|
@ -1,90 +0,0 @@
|
|||
from django.conf.urls.defaults import patterns, url
|
||||
from django.forms import ModelForm
|
||||
from django.contrib.auth.models import Group, User
|
||||
from djangorestframework.resources import ModelResource
|
||||
from djangorestframework.views import ListOrCreateModelView, InstanceModelView
|
||||
from djangorestframework.tests.models import CustomUser
|
||||
from djangorestframework.tests.testcases import TestModelsTestCase
|
||||
|
||||
|
||||
class GroupResource(ModelResource):
|
||||
model = Group
|
||||
|
||||
|
||||
class UserForm(ModelForm):
|
||||
class Meta:
|
||||
model = User
|
||||
exclude = ('last_login', 'date_joined')
|
||||
|
||||
|
||||
class UserResource(ModelResource):
|
||||
model = User
|
||||
form = UserForm
|
||||
|
||||
|
||||
class CustomUserResource(ModelResource):
|
||||
model = CustomUser
|
||||
|
||||
urlpatterns = patterns('',
|
||||
url(r'^users/$', ListOrCreateModelView.as_view(resource=UserResource), name='users'),
|
||||
url(r'^users/(?P<id>[0-9]+)/$', InstanceModelView.as_view(resource=UserResource)),
|
||||
url(r'^customusers/$', ListOrCreateModelView.as_view(resource=CustomUserResource), name='customusers'),
|
||||
url(r'^customusers/(?P<id>[0-9]+)/$', InstanceModelView.as_view(resource=CustomUserResource)),
|
||||
url(r'^groups/$', ListOrCreateModelView.as_view(resource=GroupResource), name='groups'),
|
||||
url(r'^groups/(?P<id>[0-9]+)/$', InstanceModelView.as_view(resource=GroupResource)),
|
||||
)
|
||||
|
||||
|
||||
class ModelViewTests(TestModelsTestCase):
|
||||
"""Test the model views djangorestframework provides"""
|
||||
urls = 'djangorestframework.tests.modelviews'
|
||||
|
||||
def test_creation(self):
|
||||
"""Ensure that a model object can be created"""
|
||||
self.assertEqual(0, Group.objects.count())
|
||||
|
||||
response = self.client.post('/groups/', {'name': 'foo'})
|
||||
|
||||
self.assertEqual(response.status_code, 201)
|
||||
self.assertEqual(1, Group.objects.count())
|
||||
self.assertEqual('foo', Group.objects.all()[0].name)
|
||||
|
||||
def test_creation_with_m2m_relation(self):
|
||||
"""Ensure that a model object with a m2m relation can be created"""
|
||||
group = Group(name='foo')
|
||||
group.save()
|
||||
self.assertEqual(0, User.objects.count())
|
||||
|
||||
response = self.client.post('/users/', {'username': 'bar', 'password': 'baz', 'groups': [group.id]})
|
||||
|
||||
self.assertEqual(response.status_code, 201)
|
||||
self.assertEqual(1, User.objects.count())
|
||||
|
||||
user = User.objects.all()[0]
|
||||
self.assertEqual('bar', user.username)
|
||||
self.assertEqual('baz', user.password)
|
||||
self.assertEqual(1, user.groups.count())
|
||||
|
||||
group = user.groups.all()[0]
|
||||
self.assertEqual('foo', group.name)
|
||||
|
||||
def test_creation_with_m2m_relation_through(self):
|
||||
"""
|
||||
Ensure that a model object with a m2m relation can be created where that
|
||||
relation uses a through table
|
||||
"""
|
||||
group = Group(name='foo')
|
||||
group.save()
|
||||
self.assertEqual(0, User.objects.count())
|
||||
|
||||
response = self.client.post('/customusers/', {'username': 'bar', 'groups': [group.id]})
|
||||
|
||||
self.assertEqual(response.status_code, 201)
|
||||
self.assertEqual(1, CustomUser.objects.count())
|
||||
|
||||
user = CustomUser.objects.all()[0]
|
||||
self.assertEqual('bar', user.username)
|
||||
self.assertEqual(1, user.groups.count())
|
||||
|
||||
group = user.groups.all()[0]
|
||||
self.assertEqual('foo', group.name)
|
|
@ -1,212 +0,0 @@
|
|||
import time
|
||||
|
||||
from django.conf.urls.defaults import patterns, url, include
|
||||
from django.contrib.auth.models import User
|
||||
from django.test import Client, TestCase
|
||||
|
||||
from djangorestframework.views import View
|
||||
|
||||
# Since oauth2 / django-oauth-plus are optional dependancies, we don't want to
|
||||
# always run these tests.
|
||||
|
||||
# Unfortunatly we can't skip tests easily until 2.7, se we'll just do this for now.
|
||||
try:
|
||||
import oauth2 as oauth
|
||||
from oauth_provider.decorators import oauth_required
|
||||
from oauth_provider.models import Resource, Consumer, Token
|
||||
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
else:
|
||||
# Alrighty, we're good to go here.
|
||||
class ClientView(View):
|
||||
def get(self, request):
|
||||
return {'resource': 'Protected!'}
|
||||
|
||||
urlpatterns = patterns('',
|
||||
url(r'^$', oauth_required(ClientView.as_view())),
|
||||
url(r'^oauth/', include('oauth_provider.urls')),
|
||||
url(r'^restframework/', include('djangorestframework.urls', namespace='djangorestframework')),
|
||||
)
|
||||
|
||||
|
||||
class OAuthTests(TestCase):
|
||||
"""
|
||||
OAuth authentication:
|
||||
* the user would like to access his API data from a third-party website
|
||||
* the third-party website proposes a link to get that API data
|
||||
* the user is redirected to the API and must log in if not authenticated
|
||||
* the API displays a webpage to confirm that the user trusts the third-party website
|
||||
* if confirmed, the user is redirected to the third-party website through the callback view
|
||||
* the third-party website is able to retrieve data from the API
|
||||
"""
|
||||
urls = 'djangorestframework.tests.oauthentication'
|
||||
|
||||
def setUp(self):
|
||||
self.client = Client()
|
||||
self.username = 'john'
|
||||
self.email = 'lennon@thebeatles.com'
|
||||
self.password = 'password'
|
||||
self.user = User.objects.create_user(self.username, self.email, self.password)
|
||||
|
||||
# OAuth requirements
|
||||
self.resource = Resource(name='data', url='/')
|
||||
self.resource.save()
|
||||
self.CONSUMER_KEY = 'dpf43f3p2l4k3l03'
|
||||
self.CONSUMER_SECRET = 'kd94hf93k423kf44'
|
||||
self.consumer = Consumer(key=self.CONSUMER_KEY, secret=self.CONSUMER_SECRET,
|
||||
name='api.example.com', user=self.user)
|
||||
self.consumer.save()
|
||||
|
||||
def test_oauth_invalid_and_anonymous_access(self):
|
||||
"""
|
||||
Verify that the resource is protected and the OAuth authorization view
|
||||
require the user to be logged in.
|
||||
"""
|
||||
response = self.client.get('/')
|
||||
self.assertEqual(response.content, 'Invalid request parameters.')
|
||||
self.assertEqual(response.status_code, 401)
|
||||
response = self.client.get('/oauth/authorize/', follow=True)
|
||||
self.assertRedirects(response, '/accounts/login/?next=/oauth/authorize/')
|
||||
|
||||
def test_oauth_authorize_access(self):
|
||||
"""
|
||||
Verify that once logged in, the user can access the authorization page
|
||||
but can't display the page because the request token is not specified.
|
||||
"""
|
||||
self.client.login(username=self.username, password=self.password)
|
||||
response = self.client.get('/oauth/authorize/', follow=True)
|
||||
self.assertEqual(response.content, 'No request token specified.')
|
||||
|
||||
def _create_request_token_parameters(self):
|
||||
"""
|
||||
A shortcut to create request's token parameters.
|
||||
"""
|
||||
return {
|
||||
'oauth_consumer_key': self.CONSUMER_KEY,
|
||||
'oauth_signature_method': 'PLAINTEXT',
|
||||
'oauth_signature': '%s&' % self.CONSUMER_SECRET,
|
||||
'oauth_timestamp': str(int(time.time())),
|
||||
'oauth_nonce': 'requestnonce',
|
||||
'oauth_version': '1.0',
|
||||
'oauth_callback': 'http://api.example.com/request_token_ready',
|
||||
'scope': 'data',
|
||||
}
|
||||
|
||||
def test_oauth_request_token_retrieval(self):
|
||||
"""
|
||||
Verify that the request token can be retrieved by the server.
|
||||
"""
|
||||
response = self.client.get("/oauth/request_token/",
|
||||
self._create_request_token_parameters())
|
||||
self.assertEqual(response.status_code, 200)
|
||||
token = list(Token.objects.all())[-1]
|
||||
self.failIf(token.key not in response.content)
|
||||
self.failIf(token.secret not in response.content)
|
||||
|
||||
def test_oauth_user_request_authorization(self):
|
||||
"""
|
||||
Verify that the user can access the authorization page once logged in
|
||||
and the request token has been retrieved.
|
||||
"""
|
||||
# Setup
|
||||
response = self.client.get("/oauth/request_token/",
|
||||
self._create_request_token_parameters())
|
||||
token = list(Token.objects.all())[-1]
|
||||
|
||||
# Starting the test here
|
||||
self.client.login(username=self.username, password=self.password)
|
||||
parameters = {'oauth_token': token.key,}
|
||||
response = self.client.get("/oauth/authorize/", parameters)
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.failIf(not response.content.startswith('Fake authorize view for api.example.com with params: oauth_token='))
|
||||
self.assertEqual(token.is_approved, 0)
|
||||
parameters['authorize_access'] = 1 # fake authorization by the user
|
||||
response = self.client.post("/oauth/authorize/", parameters)
|
||||
self.assertEqual(response.status_code, 302)
|
||||
self.failIf(not response['Location'].startswith('http://api.example.com/request_token_ready?oauth_verifier='))
|
||||
token = Token.objects.get(key=token.key)
|
||||
self.failIf(token.key not in response['Location'])
|
||||
self.assertEqual(token.is_approved, 1)
|
||||
|
||||
def _create_access_token_parameters(self, token):
|
||||
"""
|
||||
A shortcut to create access' token parameters.
|
||||
"""
|
||||
return {
|
||||
'oauth_consumer_key': self.CONSUMER_KEY,
|
||||
'oauth_token': token.key,
|
||||
'oauth_signature_method': 'PLAINTEXT',
|
||||
'oauth_signature': '%s&%s' % (self.CONSUMER_SECRET, token.secret),
|
||||
'oauth_timestamp': str(int(time.time())),
|
||||
'oauth_nonce': 'accessnonce',
|
||||
'oauth_version': '1.0',
|
||||
'oauth_verifier': token.verifier,
|
||||
'scope': 'data',
|
||||
}
|
||||
|
||||
def test_oauth_access_token_retrieval(self):
|
||||
"""
|
||||
Verify that the request token can be retrieved by the server.
|
||||
"""
|
||||
# Setup
|
||||
response = self.client.get("/oauth/request_token/",
|
||||
self._create_request_token_parameters())
|
||||
token = list(Token.objects.all())[-1]
|
||||
self.client.login(username=self.username, password=self.password)
|
||||
parameters = {'oauth_token': token.key,}
|
||||
response = self.client.get("/oauth/authorize/", parameters)
|
||||
parameters['authorize_access'] = 1 # fake authorization by the user
|
||||
response = self.client.post("/oauth/authorize/", parameters)
|
||||
token = Token.objects.get(key=token.key)
|
||||
|
||||
# Starting the test here
|
||||
response = self.client.get("/oauth/access_token/", self._create_access_token_parameters(token))
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.failIf(not response.content.startswith('oauth_token_secret='))
|
||||
access_token = list(Token.objects.filter(token_type=Token.ACCESS))[-1]
|
||||
self.failIf(access_token.key not in response.content)
|
||||
self.failIf(access_token.secret not in response.content)
|
||||
self.assertEqual(access_token.user.username, 'john')
|
||||
|
||||
def _create_access_parameters(self, access_token):
|
||||
"""
|
||||
A shortcut to create access' parameters.
|
||||
"""
|
||||
parameters = {
|
||||
'oauth_consumer_key': self.CONSUMER_KEY,
|
||||
'oauth_token': access_token.key,
|
||||
'oauth_signature_method': 'HMAC-SHA1',
|
||||
'oauth_timestamp': str(int(time.time())),
|
||||
'oauth_nonce': 'accessresourcenonce',
|
||||
'oauth_version': '1.0',
|
||||
}
|
||||
oauth_request = oauth.Request.from_token_and_callback(access_token,
|
||||
http_url='http://testserver/', parameters=parameters)
|
||||
signature_method = oauth.SignatureMethod_HMAC_SHA1()
|
||||
signature = signature_method.sign(oauth_request, self.consumer, access_token)
|
||||
parameters['oauth_signature'] = signature
|
||||
return parameters
|
||||
|
||||
def test_oauth_protected_resource_access(self):
|
||||
"""
|
||||
Verify that the request token can be retrieved by the server.
|
||||
"""
|
||||
# Setup
|
||||
response = self.client.get("/oauth/request_token/",
|
||||
self._create_request_token_parameters())
|
||||
token = list(Token.objects.all())[-1]
|
||||
self.client.login(username=self.username, password=self.password)
|
||||
parameters = {'oauth_token': token.key,}
|
||||
response = self.client.get("/oauth/authorize/", parameters)
|
||||
parameters['authorize_access'] = 1 # fake authorization by the user
|
||||
response = self.client.post("/oauth/authorize/", parameters)
|
||||
token = Token.objects.get(key=token.key)
|
||||
response = self.client.get("/oauth/access_token/", self._create_access_token_parameters(token))
|
||||
access_token = list(Token.objects.filter(token_type=Token.ACCESS))[-1]
|
||||
|
||||
# Starting the test here
|
||||
response = self.client.get("/", self._create_access_token_parameters(access_token))
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertEqual(response.content, '{"resource": "Protected!"}')
|
|
@ -1,11 +0,0 @@
|
|||
"""Tests for the djangorestframework package setup."""
|
||||
from django.test import TestCase
|
||||
import djangorestframework
|
||||
|
||||
class TestVersion(TestCase):
|
||||
"""Simple sanity test to check the VERSION exists"""
|
||||
|
||||
def test_version(self):
|
||||
"""Ensure the VERSION exists."""
|
||||
djangorestframework.VERSION
|
||||
|
|
@ -1,19 +0,0 @@
|
|||
# Right now we expect this test to fail - I'm just going to leave it commented out.
|
||||
# Looking forward to actually being able to raise ExpectedFailure sometime!
|
||||
#
|
||||
#from django.test import TestCase
|
||||
#from djangorestframework.response import Response
|
||||
#
|
||||
#
|
||||
#class TestResponse(TestCase):
|
||||
#
|
||||
# # Interface tests
|
||||
#
|
||||
# # This is mainly to remind myself that the Response interface needs to change slightly
|
||||
# def test_response_interface(self):
|
||||
# """Ensure the Response interface is as expected."""
|
||||
# response = Response()
|
||||
# getattr(response, 'status')
|
||||
# getattr(response, 'content')
|
||||
# getattr(response, 'headers')
|
||||
|
|
@ -1,52 +0,0 @@
|
|||
from django.conf.urls.defaults import patterns, url
|
||||
from django.test import TestCase
|
||||
from django.utils import simplejson as json
|
||||
|
||||
from djangorestframework.renderers import JSONRenderer
|
||||
from djangorestframework.reverse import reverse, reverse_lazy
|
||||
from djangorestframework.views import View
|
||||
|
||||
|
||||
class ReverseView(View):
|
||||
"""
|
||||
Mock resource which simply returns a URL, so that we can ensure
|
||||
that reversed URLs are fully qualified.
|
||||
"""
|
||||
renderers = (JSONRenderer, )
|
||||
|
||||
def get(self, request):
|
||||
return reverse('reverse', request=request)
|
||||
|
||||
|
||||
class LazyView(View):
|
||||
"""
|
||||
Mock resource which simply returns a URL, so that we can ensure
|
||||
that reversed URLs are fully qualified.
|
||||
"""
|
||||
renderers = (JSONRenderer, )
|
||||
|
||||
def get(self, request):
|
||||
return reverse_lazy('lazy', request=request)
|
||||
|
||||
|
||||
urlpatterns = patterns('',
|
||||
url(r'^reverse$', ReverseView.as_view(), name='reverse'),
|
||||
url(r'^lazy$', LazyView.as_view(), name='lazy'),
|
||||
)
|
||||
|
||||
|
||||
class ReverseTests(TestCase):
|
||||
"""
|
||||
Tests for fully qualifed URLs when using `reverse`.
|
||||
"""
|
||||
urls = 'djangorestframework.tests.reverse'
|
||||
|
||||
def test_reversed_urls_are_fully_qualified(self):
|
||||
response = self.client.get('/reverse')
|
||||
self.assertEqual(json.loads(response.content),
|
||||
'http://testserver/reverse')
|
||||
|
||||
#def test_reversed_lazy_urls_are_fully_qualified(self):
|
||||
# response = self.client.get('/lazy')
|
||||
# self.assertEqual(json.loads(response.content),
|
||||
# 'http://testserver/lazy')
|
|
@ -1,160 +0,0 @@
|
|||
"""Tests for the resource module"""
|
||||
from django.db import models
|
||||
from django.test import TestCase
|
||||
from django.utils.translation import ugettext_lazy
|
||||
from djangorestframework.serializer import Serializer
|
||||
|
||||
import datetime
|
||||
import decimal
|
||||
|
||||
class TestObjectToData(TestCase):
|
||||
"""
|
||||
Tests for the Serializer class.
|
||||
"""
|
||||
|
||||
def setUp(self):
|
||||
self.serializer = Serializer()
|
||||
self.serialize = self.serializer.serialize
|
||||
|
||||
def test_decimal(self):
|
||||
"""Decimals need to be converted to a string representation."""
|
||||
self.assertEquals(self.serialize(decimal.Decimal('1.5')), decimal.Decimal('1.5'))
|
||||
|
||||
def test_function(self):
|
||||
"""Functions with no arguments should be called."""
|
||||
def foo():
|
||||
return 1
|
||||
self.assertEquals(self.serialize(foo), 1)
|
||||
|
||||
def test_method(self):
|
||||
"""Methods with only a ``self`` argument should be called."""
|
||||
class Foo(object):
|
||||
def foo(self):
|
||||
return 1
|
||||
self.assertEquals(self.serialize(Foo().foo), 1)
|
||||
|
||||
def test_datetime(self):
|
||||
"""datetime objects are left as-is."""
|
||||
now = datetime.datetime.now()
|
||||
self.assertEquals(self.serialize(now), now)
|
||||
|
||||
def test_dict_method_name_collision(self):
|
||||
"""dict with key that collides with dict method name"""
|
||||
self.assertEquals(self.serialize({'items': 'foo'}), {'items': u'foo'})
|
||||
self.assertEquals(self.serialize({'keys': 'foo'}), {'keys': u'foo'})
|
||||
self.assertEquals(self.serialize({'values': 'foo'}), {'values': u'foo'})
|
||||
|
||||
def test_ugettext_lazy(self):
|
||||
self.assertEquals(self.serialize(ugettext_lazy('foobar')), u'foobar')
|
||||
|
||||
|
||||
class TestFieldNesting(TestCase):
|
||||
"""
|
||||
Test nesting the fields in the Serializer class
|
||||
"""
|
||||
def setUp(self):
|
||||
self.serializer = Serializer()
|
||||
self.serialize = self.serializer.serialize
|
||||
|
||||
class M1(models.Model):
|
||||
field1 = models.CharField(max_length=256)
|
||||
field2 = models.CharField(max_length=256)
|
||||
|
||||
class M2(models.Model):
|
||||
field = models.OneToOneField(M1)
|
||||
|
||||
class M3(models.Model):
|
||||
field = models.ForeignKey(M1)
|
||||
|
||||
self.m1 = M1(field1='foo', field2='bar')
|
||||
self.m2 = M2(field=self.m1)
|
||||
self.m3 = M3(field=self.m1)
|
||||
|
||||
|
||||
def test_tuple_nesting(self):
|
||||
"""
|
||||
Test tuple nesting on `fields` attr
|
||||
"""
|
||||
class SerializerM2(Serializer):
|
||||
fields = (('field', ('field1',)),)
|
||||
|
||||
class SerializerM3(Serializer):
|
||||
fields = (('field', ('field2',)),)
|
||||
|
||||
self.assertEqual(SerializerM2().serialize(self.m2), {'field': {'field1': u'foo'}})
|
||||
self.assertEqual(SerializerM3().serialize(self.m3), {'field': {'field2': u'bar'}})
|
||||
|
||||
|
||||
def test_serializer_class_nesting(self):
|
||||
"""
|
||||
Test related model serialization
|
||||
"""
|
||||
class NestedM2(Serializer):
|
||||
fields = ('field1', )
|
||||
|
||||
class NestedM3(Serializer):
|
||||
fields = ('field2', )
|
||||
|
||||
class SerializerM2(Serializer):
|
||||
fields = [('field', NestedM2)]
|
||||
|
||||
class SerializerM3(Serializer):
|
||||
fields = [('field', NestedM3)]
|
||||
|
||||
self.assertEqual(SerializerM2().serialize(self.m2), {'field': {'field1': u'foo'}})
|
||||
self.assertEqual(SerializerM3().serialize(self.m3), {'field': {'field2': u'bar'}})
|
||||
|
||||
# def test_serializer_no_fields(self):
|
||||
# """
|
||||
# Test related serializer works when the fields attr isn't present. Fix for
|
||||
# #178.
|
||||
# """
|
||||
# class NestedM2(Serializer):
|
||||
# fields = ('field1', )
|
||||
|
||||
# class NestedM3(Serializer):
|
||||
# fields = ('field2', )
|
||||
|
||||
# class SerializerM2(Serializer):
|
||||
# include = [('field', NestedM2)]
|
||||
# exclude = ('id', )
|
||||
|
||||
# class SerializerM3(Serializer):
|
||||
# fields = [('field', NestedM3)]
|
||||
|
||||
# self.assertEqual(SerializerM2().serialize(self.m2), {'field': {'field1': u'foo'}})
|
||||
# self.assertEqual(SerializerM3().serialize(self.m3), {'field': {'field2': u'bar'}})
|
||||
|
||||
def test_serializer_classname_nesting(self):
|
||||
"""
|
||||
Test related model serialization
|
||||
"""
|
||||
class SerializerM2(Serializer):
|
||||
fields = [('field', 'NestedM2')]
|
||||
|
||||
class SerializerM3(Serializer):
|
||||
fields = [('field', 'NestedM3')]
|
||||
|
||||
class NestedM2(Serializer):
|
||||
fields = ('field1', )
|
||||
|
||||
class NestedM3(Serializer):
|
||||
fields = ('field2', )
|
||||
|
||||
self.assertEqual(SerializerM2().serialize(self.m2), {'field': {'field1': u'foo'}})
|
||||
self.assertEqual(SerializerM3().serialize(self.m3), {'field': {'field2': u'bar'}})
|
||||
|
||||
def test_serializer_overridden_hook_method(self):
|
||||
"""
|
||||
Test serializing a model instance which overrides a class method on the
|
||||
serializer. Checks for correct behaviour in odd edge case.
|
||||
"""
|
||||
class SerializerM2(Serializer):
|
||||
fields = ('overridden', )
|
||||
|
||||
def overridden(self):
|
||||
return False
|
||||
|
||||
self.m2.overridden = True
|
||||
self.assertEqual(SerializerM2().serialize_model(self.m2),
|
||||
{'overridden': True})
|
|
@ -1,325 +0,0 @@
|
|||
from django import forms
|
||||
from django.db import models
|
||||
from django.test import TestCase
|
||||
from djangorestframework.resources import FormResource, ModelResource
|
||||
from djangorestframework.response import ErrorResponse
|
||||
from djangorestframework.views import View
|
||||
|
||||
|
||||
class TestDisabledValidations(TestCase):
|
||||
"""Tests on FormValidator with validation disabled by setting form to None"""
|
||||
|
||||
def test_disabled_form_validator_returns_content_unchanged(self):
|
||||
"""If the view's form attribute is None then FormValidator(view).validate_request(content, None)
|
||||
should just return the content unmodified."""
|
||||
class DisabledFormResource(FormResource):
|
||||
form = None
|
||||
|
||||
class MockView(View):
|
||||
resource = DisabledFormResource
|
||||
|
||||
view = MockView()
|
||||
content = {'qwerty': 'uiop'}
|
||||
self.assertEqual(FormResource(view).validate_request(content, None), content)
|
||||
|
||||
def test_disabled_form_validator_get_bound_form_returns_none(self):
|
||||
"""If the view's form attribute is None on then
|
||||
FormValidator(view).get_bound_form(content) should just return None."""
|
||||
class DisabledFormResource(FormResource):
|
||||
form = None
|
||||
|
||||
class MockView(View):
|
||||
resource = DisabledFormResource
|
||||
|
||||
view = MockView()
|
||||
content = {'qwerty': 'uiop'}
|
||||
self.assertEqual(FormResource(view).get_bound_form(content), None)
|
||||
|
||||
def test_disabled_model_form_validator_returns_content_unchanged(self):
|
||||
"""If the view's form is None and does not have a Resource with a model set then
|
||||
ModelFormValidator(view).validate_request(content, None) should just return the content unmodified."""
|
||||
|
||||
class DisabledModelFormView(View):
|
||||
resource = ModelResource
|
||||
|
||||
view = DisabledModelFormView()
|
||||
content = {'qwerty': 'uiop'}
|
||||
self.assertEqual(ModelResource(view).get_bound_form(content), None)
|
||||
|
||||
def test_disabled_model_form_validator_get_bound_form_returns_none(self):
|
||||
"""If the form attribute is None on FormValidatorMixin then get_bound_form(content) should just return None."""
|
||||
class DisabledModelFormView(View):
|
||||
resource = ModelResource
|
||||
|
||||
view = DisabledModelFormView()
|
||||
content = {'qwerty': 'uiop'}
|
||||
self.assertEqual(ModelResource(view).get_bound_form(content), None)
|
||||
|
||||
|
||||
class TestNonFieldErrors(TestCase):
|
||||
"""Tests against form validation errors caused by non-field errors. (eg as might be caused by some custom form validation)"""
|
||||
|
||||
def test_validate_failed_due_to_non_field_error_returns_appropriate_message(self):
|
||||
"""If validation fails with a non-field error, ensure the response a non-field error"""
|
||||
class MockForm(forms.Form):
|
||||
field1 = forms.CharField(required=False)
|
||||
field2 = forms.CharField(required=False)
|
||||
ERROR_TEXT = 'You may not supply both field1 and field2'
|
||||
|
||||
def clean(self):
|
||||
if 'field1' in self.cleaned_data and 'field2' in self.cleaned_data:
|
||||
raise forms.ValidationError(self.ERROR_TEXT)
|
||||
return self.cleaned_data
|
||||
|
||||
class MockResource(FormResource):
|
||||
form = MockForm
|
||||
|
||||
class MockView(View):
|
||||
pass
|
||||
|
||||
view = MockView()
|
||||
content = {'field1': 'example1', 'field2': 'example2'}
|
||||
try:
|
||||
MockResource(view).validate_request(content, None)
|
||||
except ErrorResponse, exc:
|
||||
self.assertEqual(exc.response.raw_content, {'errors': [MockForm.ERROR_TEXT]})
|
||||
else:
|
||||
self.fail('ErrorResponse was not raised')
|
||||
|
||||
|
||||
class TestFormValidation(TestCase):
|
||||
"""Tests which check basic form validation.
|
||||
Also includes the same set of tests with a ModelFormValidator for which the form has been explicitly set.
|
||||
(ModelFormValidator should behave as FormValidator if a form is set rather than relying on the default ModelForm)"""
|
||||
def setUp(self):
|
||||
class MockForm(forms.Form):
|
||||
qwerty = forms.CharField(required=True)
|
||||
|
||||
class MockFormResource(FormResource):
|
||||
form = MockForm
|
||||
|
||||
class MockModelResource(ModelResource):
|
||||
form = MockForm
|
||||
|
||||
class MockFormView(View):
|
||||
resource = MockFormResource
|
||||
|
||||
class MockModelFormView(View):
|
||||
resource = MockModelResource
|
||||
|
||||
self.MockFormResource = MockFormResource
|
||||
self.MockModelResource = MockModelResource
|
||||
self.MockFormView = MockFormView
|
||||
self.MockModelFormView = MockModelFormView
|
||||
|
||||
def validation_returns_content_unchanged_if_already_valid_and_clean(self, validator):
|
||||
"""If the content is already valid and clean then validate(content) should just return the content unmodified."""
|
||||
content = {'qwerty': 'uiop'}
|
||||
self.assertEqual(validator.validate_request(content, None), content)
|
||||
|
||||
def validation_failure_raises_response_exception(self, validator):
|
||||
"""If form validation fails a ResourceException 400 (Bad Request) should be raised."""
|
||||
content = {}
|
||||
self.assertRaises(ErrorResponse, validator.validate_request, content, None)
|
||||
|
||||
def validation_does_not_allow_extra_fields_by_default(self, validator):
|
||||
"""If some (otherwise valid) content includes fields that are not in the form then validation should fail.
|
||||
It might be okay on normal form submission, but for Web APIs we oughta get strict, as it'll help show up
|
||||
broken clients more easily (eg submitting content with a misnamed field)"""
|
||||
content = {'qwerty': 'uiop', 'extra': 'extra'}
|
||||
self.assertRaises(ErrorResponse, validator.validate_request, content, None)
|
||||
|
||||
def validation_allows_extra_fields_if_explicitly_set(self, validator):
|
||||
"""If we include an allowed_extra_fields paramater on _validate, then allow fields with those names."""
|
||||
content = {'qwerty': 'uiop', 'extra': 'extra'}
|
||||
validator._validate(content, None, allowed_extra_fields=('extra',))
|
||||
|
||||
def validation_allows_unknown_fields_if_explicitly_allowed(self, validator):
|
||||
"""If we set ``unknown_form_fields`` on the form resource, then don't
|
||||
raise errors on unexpected request data"""
|
||||
content = {'qwerty': 'uiop', 'extra': 'extra'}
|
||||
validator.allow_unknown_form_fields = True
|
||||
self.assertEqual({'qwerty': u'uiop'},
|
||||
validator.validate_request(content, None),
|
||||
"Resource didn't accept unknown fields.")
|
||||
validator.allow_unknown_form_fields = False
|
||||
|
||||
def validation_does_not_require_extra_fields_if_explicitly_set(self, validator):
|
||||
"""If we include an allowed_extra_fields paramater on _validate, then do not fail if we do not have fields with those names."""
|
||||
content = {'qwerty': 'uiop'}
|
||||
self.assertEqual(validator._validate(content, None, allowed_extra_fields=('extra',)), content)
|
||||
|
||||
def validation_failed_due_to_no_content_returns_appropriate_message(self, validator):
|
||||
"""If validation fails due to no content, ensure the response contains a single non-field error"""
|
||||
content = {}
|
||||
try:
|
||||
validator.validate_request(content, None)
|
||||
except ErrorResponse, exc:
|
||||
self.assertEqual(exc.response.raw_content, {'field_errors': {'qwerty': ['This field is required.']}})
|
||||
else:
|
||||
self.fail('ResourceException was not raised')
|
||||
|
||||
def validation_failed_due_to_field_error_returns_appropriate_message(self, validator):
|
||||
"""If validation fails due to a field error, ensure the response contains a single field error"""
|
||||
content = {'qwerty': ''}
|
||||
try:
|
||||
validator.validate_request(content, None)
|
||||
except ErrorResponse, exc:
|
||||
self.assertEqual(exc.response.raw_content, {'field_errors': {'qwerty': ['This field is required.']}})
|
||||
else:
|
||||
self.fail('ResourceException was not raised')
|
||||
|
||||
def validation_failed_due_to_invalid_field_returns_appropriate_message(self, validator):
|
||||
"""If validation fails due to an invalid field, ensure the response contains a single field error"""
|
||||
content = {'qwerty': 'uiop', 'extra': 'extra'}
|
||||
try:
|
||||
validator.validate_request(content, None)
|
||||
except ErrorResponse, exc:
|
||||
self.assertEqual(exc.response.raw_content, {'field_errors': {'extra': ['This field does not exist.']}})
|
||||
else:
|
||||
self.fail('ResourceException was not raised')
|
||||
|
||||
def validation_failed_due_to_multiple_errors_returns_appropriate_message(self, validator):
|
||||
"""If validation for multiple reasons, ensure the response contains each error"""
|
||||
content = {'qwerty': '', 'extra': 'extra'}
|
||||
try:
|
||||
validator.validate_request(content, None)
|
||||
except ErrorResponse, exc:
|
||||
self.assertEqual(exc.response.raw_content, {'field_errors': {'qwerty': ['This field is required.'],
|
||||
'extra': ['This field does not exist.']}})
|
||||
else:
|
||||
self.fail('ResourceException was not raised')
|
||||
|
||||
# Tests on FormResource
|
||||
|
||||
def test_form_validation_returns_content_unchanged_if_already_valid_and_clean(self):
|
||||
validator = self.MockFormResource(self.MockFormView())
|
||||
self.validation_returns_content_unchanged_if_already_valid_and_clean(validator)
|
||||
|
||||
def test_form_validation_failure_raises_response_exception(self):
|
||||
validator = self.MockFormResource(self.MockFormView())
|
||||
self.validation_failure_raises_response_exception(validator)
|
||||
|
||||
def test_validation_does_not_allow_extra_fields_by_default(self):
|
||||
validator = self.MockFormResource(self.MockFormView())
|
||||
self.validation_does_not_allow_extra_fields_by_default(validator)
|
||||
|
||||
def test_validation_allows_extra_fields_if_explicitly_set(self):
|
||||
validator = self.MockFormResource(self.MockFormView())
|
||||
self.validation_allows_extra_fields_if_explicitly_set(validator)
|
||||
|
||||
def test_validation_allows_unknown_fields_if_explicitly_allowed(self):
|
||||
validator = self.MockFormResource(self.MockFormView())
|
||||
self.validation_allows_unknown_fields_if_explicitly_allowed(validator)
|
||||
|
||||
def test_validation_does_not_require_extra_fields_if_explicitly_set(self):
|
||||
validator = self.MockFormResource(self.MockFormView())
|
||||
self.validation_does_not_require_extra_fields_if_explicitly_set(validator)
|
||||
|
||||
def test_validation_failed_due_to_no_content_returns_appropriate_message(self):
|
||||
validator = self.MockFormResource(self.MockFormView())
|
||||
self.validation_failed_due_to_no_content_returns_appropriate_message(validator)
|
||||
|
||||
def test_validation_failed_due_to_field_error_returns_appropriate_message(self):
|
||||
validator = self.MockFormResource(self.MockFormView())
|
||||
self.validation_failed_due_to_field_error_returns_appropriate_message(validator)
|
||||
|
||||
def test_validation_failed_due_to_invalid_field_returns_appropriate_message(self):
|
||||
validator = self.MockFormResource(self.MockFormView())
|
||||
self.validation_failed_due_to_invalid_field_returns_appropriate_message(validator)
|
||||
|
||||
def test_validation_failed_due_to_multiple_errors_returns_appropriate_message(self):
|
||||
validator = self.MockFormResource(self.MockFormView())
|
||||
self.validation_failed_due_to_multiple_errors_returns_appropriate_message(validator)
|
||||
|
||||
# Same tests on ModelResource
|
||||
|
||||
def test_modelform_validation_returns_content_unchanged_if_already_valid_and_clean(self):
|
||||
validator = self.MockModelResource(self.MockModelFormView())
|
||||
self.validation_returns_content_unchanged_if_already_valid_and_clean(validator)
|
||||
|
||||
def test_modelform_validation_failure_raises_response_exception(self):
|
||||
validator = self.MockModelResource(self.MockModelFormView())
|
||||
self.validation_failure_raises_response_exception(validator)
|
||||
|
||||
def test_modelform_validation_does_not_allow_extra_fields_by_default(self):
|
||||
validator = self.MockModelResource(self.MockModelFormView())
|
||||
self.validation_does_not_allow_extra_fields_by_default(validator)
|
||||
|
||||
def test_modelform_validation_allows_extra_fields_if_explicitly_set(self):
|
||||
validator = self.MockModelResource(self.MockModelFormView())
|
||||
self.validation_allows_extra_fields_if_explicitly_set(validator)
|
||||
|
||||
def test_modelform_validation_does_not_require_extra_fields_if_explicitly_set(self):
|
||||
validator = self.MockModelResource(self.MockModelFormView())
|
||||
self.validation_does_not_require_extra_fields_if_explicitly_set(validator)
|
||||
|
||||
def test_modelform_validation_failed_due_to_no_content_returns_appropriate_message(self):
|
||||
validator = self.MockModelResource(self.MockModelFormView())
|
||||
self.validation_failed_due_to_no_content_returns_appropriate_message(validator)
|
||||
|
||||
def test_modelform_validation_failed_due_to_field_error_returns_appropriate_message(self):
|
||||
validator = self.MockModelResource(self.MockModelFormView())
|
||||
self.validation_failed_due_to_field_error_returns_appropriate_message(validator)
|
||||
|
||||
def test_modelform_validation_failed_due_to_invalid_field_returns_appropriate_message(self):
|
||||
validator = self.MockModelResource(self.MockModelFormView())
|
||||
self.validation_failed_due_to_invalid_field_returns_appropriate_message(validator)
|
||||
|
||||
def test_modelform_validation_failed_due_to_multiple_errors_returns_appropriate_message(self):
|
||||
validator = self.MockModelResource(self.MockModelFormView())
|
||||
self.validation_failed_due_to_multiple_errors_returns_appropriate_message(validator)
|
||||
|
||||
|
||||
class TestModelFormValidator(TestCase):
|
||||
"""Tests specific to ModelFormValidatorMixin"""
|
||||
|
||||
def setUp(self):
|
||||
"""Create a validator for a model with two fields and a property."""
|
||||
class MockModel(models.Model):
|
||||
qwerty = models.CharField(max_length=256)
|
||||
uiop = models.CharField(max_length=256, blank=True)
|
||||
|
||||
@property
|
||||
def readonly(self):
|
||||
return 'read only'
|
||||
|
||||
class MockResource(ModelResource):
|
||||
model = MockModel
|
||||
|
||||
class MockView(View):
|
||||
resource = MockResource
|
||||
|
||||
self.validator = MockResource(MockView)
|
||||
|
||||
def test_property_fields_are_allowed_on_model_forms(self):
|
||||
"""Validation on ModelForms may include property fields that exist on the Model to be included in the input."""
|
||||
content = {'qwerty': 'example', 'uiop': 'example', 'readonly': 'read only'}
|
||||
self.assertEqual(self.validator.validate_request(content, None), content)
|
||||
|
||||
def test_property_fields_are_not_required_on_model_forms(self):
|
||||
"""Validation on ModelForms does not require property fields that exist on the Model to be included in the input."""
|
||||
content = {'qwerty': 'example', 'uiop': 'example'}
|
||||
self.assertEqual(self.validator.validate_request(content, None), content)
|
||||
|
||||
def test_extra_fields_not_allowed_on_model_forms(self):
|
||||
"""If some (otherwise valid) content includes fields that are not in the form then validation should fail.
|
||||
It might be okay on normal form submission, but for Web APIs we oughta get strict, as it'll help show up
|
||||
broken clients more easily (eg submitting content with a misnamed field)"""
|
||||
content = {'qwerty': 'example', 'uiop': 'example', 'readonly': 'read only', 'extra': 'extra'}
|
||||
self.assertRaises(ErrorResponse, self.validator.validate_request, content, None)
|
||||
|
||||
def test_validate_requires_fields_on_model_forms(self):
|
||||
"""If some (otherwise valid) content includes fields that are not in the form then validation should fail.
|
||||
It might be okay on normal form submission, but for Web APIs we oughta get strict, as it'll help show up
|
||||
broken clients more easily (eg submitting content with a misnamed field)"""
|
||||
content = {'readonly': 'read only'}
|
||||
self.assertRaises(ErrorResponse, self.validator.validate_request, content, None)
|
||||
|
||||
def test_validate_does_not_require_blankable_fields_on_model_forms(self):
|
||||
"""Test standard ModelForm validation behaviour - fields with blank=True are not required."""
|
||||
content = {'qwerty': 'example', 'readonly': 'read only'}
|
||||
self.validator.validate_request(content, None)
|
||||
|
||||
def test_model_form_validator_uses_model_forms(self):
|
||||
self.assertTrue(isinstance(self.validator.get_bound_form(), forms.ModelForm))
|
|
@ -1,137 +0,0 @@
|
|||
from django.core.urlresolvers import reverse
|
||||
from django.conf.urls.defaults import patterns, url, include
|
||||
from django.http import HttpResponse
|
||||
from django.test import TestCase
|
||||
from django.test import Client
|
||||
from django import forms
|
||||
from django.db import models
|
||||
|
||||
from djangorestframework.views import View
|
||||
from djangorestframework.parsers import JSONParser
|
||||
from djangorestframework.resources import ModelResource
|
||||
from djangorestframework.views import ListOrCreateModelView, InstanceModelView
|
||||
|
||||
from StringIO import StringIO
|
||||
|
||||
|
||||
class MockView(View):
|
||||
"""This is a basic mock view"""
|
||||
pass
|
||||
|
||||
|
||||
class MockViewFinal(View):
|
||||
"""View with final() override"""
|
||||
|
||||
def final(self, request, response, *args, **kwargs):
|
||||
return HttpResponse('{"test": "passed"}', content_type="application/json")
|
||||
|
||||
class ResourceMockView(View):
|
||||
"""This is a resource-based mock view"""
|
||||
|
||||
class MockForm(forms.Form):
|
||||
foo = forms.BooleanField(required=False)
|
||||
bar = forms.IntegerField(help_text='Must be an integer.')
|
||||
baz = forms.CharField(max_length=32)
|
||||
|
||||
form = MockForm
|
||||
|
||||
class MockResource(ModelResource):
|
||||
"""This is a mock model-based resource"""
|
||||
|
||||
class MockResourceModel(models.Model):
|
||||
foo = models.BooleanField()
|
||||
bar = models.IntegerField(help_text='Must be an integer.')
|
||||
baz = models.CharField(max_length=32, help_text='Free text. Max length 32 chars.')
|
||||
|
||||
model = MockResourceModel
|
||||
fields = ('foo', 'bar', 'baz')
|
||||
|
||||
urlpatterns = patterns('',
|
||||
url(r'^mock/$', MockView.as_view()),
|
||||
url(r'^mock/final/$', MockViewFinal.as_view()),
|
||||
url(r'^resourcemock/$', ResourceMockView.as_view()),
|
||||
url(r'^model/$', ListOrCreateModelView.as_view(resource=MockResource)),
|
||||
url(r'^model/(?P<pk>[^/]+)/$', InstanceModelView.as_view(resource=MockResource)),
|
||||
url(r'^restframework/', include('djangorestframework.urls', namespace='djangorestframework')),
|
||||
)
|
||||
|
||||
class BaseViewTests(TestCase):
|
||||
"""Test the base view class of djangorestframework"""
|
||||
urls = 'djangorestframework.tests.views'
|
||||
|
||||
def test_view_call_final(self):
|
||||
response = self.client.options('/mock/final/')
|
||||
self.assertEqual(response['Content-Type'].split(';')[0], "application/json")
|
||||
parser = JSONParser(None)
|
||||
(data, files) = parser.parse(StringIO(response.content))
|
||||
self.assertEqual(data['test'], 'passed')
|
||||
|
||||
def test_options_method_simple_view(self):
|
||||
response = self.client.options('/mock/')
|
||||
self._verify_options_response(response,
|
||||
name='Mock',
|
||||
description='This is a basic mock view')
|
||||
|
||||
def test_options_method_resource_view(self):
|
||||
response = self.client.options('/resourcemock/')
|
||||
self._verify_options_response(response,
|
||||
name='Resource Mock',
|
||||
description='This is a resource-based mock view',
|
||||
fields={'foo':'BooleanField',
|
||||
'bar':'IntegerField',
|
||||
'baz':'CharField',
|
||||
})
|
||||
|
||||
def test_options_method_model_resource_list_view(self):
|
||||
response = self.client.options('/model/')
|
||||
self._verify_options_response(response,
|
||||
name='Mock List',
|
||||
description='This is a mock model-based resource',
|
||||
fields={'foo':'BooleanField',
|
||||
'bar':'IntegerField',
|
||||
'baz':'CharField',
|
||||
})
|
||||
|
||||
def test_options_method_model_resource_detail_view(self):
|
||||
response = self.client.options('/model/0/')
|
||||
self._verify_options_response(response,
|
||||
name='Mock Instance',
|
||||
description='This is a mock model-based resource',
|
||||
fields={'foo':'BooleanField',
|
||||
'bar':'IntegerField',
|
||||
'baz':'CharField',
|
||||
})
|
||||
|
||||
def _verify_options_response(self, response, name, description, fields=None, status=200,
|
||||
mime_type='application/json'):
|
||||
self.assertEqual(response.status_code, status)
|
||||
self.assertEqual(response['Content-Type'].split(';')[0], mime_type)
|
||||
parser = JSONParser(None)
|
||||
(data, files) = parser.parse(StringIO(response.content))
|
||||
self.assertTrue('application/json' in data['renders'])
|
||||
self.assertEqual(name, data['name'])
|
||||
self.assertEqual(description, data['description'])
|
||||
if fields is None:
|
||||
self.assertFalse(hasattr(data, 'fields'))
|
||||
else:
|
||||
self.assertEqual(data['fields'], fields)
|
||||
|
||||
|
||||
class ExtraViewsTests(TestCase):
|
||||
"""Test the extra views djangorestframework provides"""
|
||||
urls = 'djangorestframework.tests.views'
|
||||
|
||||
def test_login_view(self):
|
||||
"""Ensure the login view exists"""
|
||||
response = self.client.get(reverse('djangorestframework:login'))
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertEqual(response['Content-Type'].split(';')[0], 'text/html')
|
||||
|
||||
def test_logout_view(self):
|
||||
"""Ensure the logout view exists"""
|
||||
response = self.client.get(reverse('djangorestframework:logout'))
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertEqual(response['Content-Type'].split(';')[0], 'text/html')
|
||||
|
||||
# TODO: Add login/logout behaviour tests
|
||||
|
|
@ -1,9 +0,0 @@
|
|||
from django.conf.urls.defaults import patterns, url
|
||||
|
||||
|
||||
template_name = {'template_name': 'djangorestframework/login.html'}
|
||||
|
||||
urlpatterns = patterns('django.contrib.auth.views',
|
||||
url(r'^login/$', 'login', template_name, name='login'),
|
||||
url(r'^logout/$', 'logout', template_name, name='logout'),
|
||||
)
|
|
@ -1,292 +0,0 @@
|
|||
"""
|
||||
The :mod:`views` module provides the Views you will most probably
|
||||
be subclassing in your implementation.
|
||||
|
||||
By setting or modifying class attributes on your view, you change it's predefined behaviour.
|
||||
"""
|
||||
|
||||
import re
|
||||
from django.http import HttpResponse
|
||||
from django.utils.html import escape
|
||||
from django.utils.safestring import mark_safe
|
||||
from django.views.decorators.csrf import csrf_exempt
|
||||
|
||||
from djangorestframework.compat import View as DjangoView, apply_markdown
|
||||
from djangorestframework.response import Response, ErrorResponse
|
||||
from djangorestframework.mixins import *
|
||||
from djangorestframework import resources, renderers, parsers, authentication, permissions, status
|
||||
|
||||
|
||||
__all__ = (
|
||||
'View',
|
||||
'ModelView',
|
||||
'InstanceModelView',
|
||||
'ListModelView',
|
||||
'ListOrCreateModelView'
|
||||
)
|
||||
|
||||
|
||||
def _remove_trailing_string(content, trailing):
|
||||
"""
|
||||
Strip trailing component `trailing` from `content` if it exists.
|
||||
Used when generating names from view/resource classes.
|
||||
"""
|
||||
if content.endswith(trailing) and content != trailing:
|
||||
return content[:-len(trailing)]
|
||||
return content
|
||||
|
||||
|
||||
def _remove_leading_indent(content):
|
||||
"""
|
||||
Remove leading indent from a block of text.
|
||||
Used when generating descriptions from docstrings.
|
||||
"""
|
||||
whitespace_counts = [len(line) - len(line.lstrip(' '))
|
||||
for line in content.splitlines()[1:] if line.lstrip()]
|
||||
|
||||
# unindent the content if needed
|
||||
if whitespace_counts:
|
||||
whitespace_pattern = '^' + (' ' * min(whitespace_counts))
|
||||
return re.sub(re.compile(whitespace_pattern, re.MULTILINE), '', content)
|
||||
return content
|
||||
|
||||
|
||||
def _camelcase_to_spaces(content):
|
||||
"""
|
||||
Translate 'CamelCaseNames' to 'Camel Case Names'.
|
||||
Used when generating names from view/resource classes.
|
||||
"""
|
||||
camelcase_boundry = '(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))'
|
||||
return re.sub(camelcase_boundry, ' \\1', content).strip()
|
||||
|
||||
|
||||
_resource_classes = (
|
||||
None,
|
||||
resources.Resource,
|
||||
resources.FormResource,
|
||||
resources.ModelResource
|
||||
)
|
||||
|
||||
|
||||
class View(ResourceMixin, RequestMixin, ResponseMixin, AuthMixin, DjangoView):
|
||||
"""
|
||||
Handles incoming requests and maps them to REST operations.
|
||||
Performs request deserialization, response serialization, authentication and input validation.
|
||||
"""
|
||||
|
||||
resource = None
|
||||
"""
|
||||
The resource to use when validating requests and filtering responses,
|
||||
or `None` to use default behaviour.
|
||||
"""
|
||||
|
||||
renderers = renderers.DEFAULT_RENDERERS
|
||||
"""
|
||||
List of renderers the resource can serialize the response with, ordered by preference.
|
||||
"""
|
||||
|
||||
parsers = parsers.DEFAULT_PARSERS
|
||||
"""
|
||||
List of parsers the resource can parse the request with.
|
||||
"""
|
||||
|
||||
authentication = (authentication.UserLoggedInAuthentication,
|
||||
authentication.BasicAuthentication)
|
||||
"""
|
||||
List of all authenticating methods to attempt.
|
||||
"""
|
||||
|
||||
permissions = (permissions.FullAnonAccess,)
|
||||
"""
|
||||
List of all permissions that must be checked.
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def as_view(cls, **initkwargs):
|
||||
"""
|
||||
Override the default :meth:`as_view` to store an instance of the view
|
||||
as an attribute on the callable function. This allows us to discover
|
||||
information about the view when we do URL reverse lookups.
|
||||
"""
|
||||
view = super(View, cls).as_view(**initkwargs)
|
||||
view.cls_instance = cls(**initkwargs)
|
||||
return view
|
||||
|
||||
@property
|
||||
def allowed_methods(self):
|
||||
"""
|
||||
Return the list of allowed HTTP methods, uppercased.
|
||||
"""
|
||||
return [method.upper() for method in self.http_method_names if hasattr(self, method)]
|
||||
|
||||
def get_name(self):
|
||||
"""
|
||||
Return the resource or view class name for use as this view's name.
|
||||
Override to customize.
|
||||
"""
|
||||
# If this view has a resource that's been overridden, then use that resource for the name
|
||||
if getattr(self, 'resource', None) not in _resource_classes:
|
||||
name = self.resource.__name__
|
||||
name = _remove_trailing_string(name, 'Resource')
|
||||
name += getattr(self, '_suffix', '')
|
||||
|
||||
# If it's a view class with no resource then grok the name from the class name
|
||||
else:
|
||||
name = self.__class__.__name__
|
||||
name = _remove_trailing_string(name, 'View')
|
||||
|
||||
return _camelcase_to_spaces(name)
|
||||
|
||||
def get_description(self, html=False):
|
||||
"""
|
||||
Return the resource or view docstring for use as this view's description.
|
||||
Override to customize.
|
||||
"""
|
||||
|
||||
description = None
|
||||
|
||||
# If this view has a resource that's been overridden,
|
||||
# then try to use the resource's docstring
|
||||
if getattr(self, 'resource', None) not in _resource_classes:
|
||||
description = self.resource.__doc__
|
||||
|
||||
# Otherwise use the view docstring
|
||||
if not description:
|
||||
description = self.__doc__ or ''
|
||||
|
||||
description = _remove_leading_indent(description)
|
||||
|
||||
if not isinstance(description, unicode):
|
||||
description = description.decode('UTF-8')
|
||||
|
||||
if html:
|
||||
return self.markup_description(description)
|
||||
return description
|
||||
|
||||
def markup_description(self, description):
|
||||
if apply_markdown:
|
||||
description = apply_markdown(description)
|
||||
else:
|
||||
description = escape(description).replace('\n', '<br />')
|
||||
return mark_safe(description)
|
||||
|
||||
def http_method_not_allowed(self, request, *args, **kwargs):
|
||||
"""
|
||||
Return an HTTP 405 error if an operation is called which does not have a handler method.
|
||||
"""
|
||||
raise ErrorResponse(status.HTTP_405_METHOD_NOT_ALLOWED,
|
||||
{'detail': 'Method \'%s\' not allowed on this resource.' % self.method})
|
||||
|
||||
def initial(self, request, *args, **kargs):
|
||||
"""
|
||||
Hook for any code that needs to run prior to anything else.
|
||||
Required if you want to do things like set `request.upload_handlers` before
|
||||
the authentication and dispatch handling is run.
|
||||
"""
|
||||
pass
|
||||
|
||||
def final(self, request, response, *args, **kargs):
|
||||
"""
|
||||
Hook for any code that needs to run after everything else in the view.
|
||||
"""
|
||||
# Always add these headers.
|
||||
response.headers['Allow'] = ', '.join(self.allowed_methods)
|
||||
# sample to allow caching using Vary http header
|
||||
response.headers['Vary'] = 'Authenticate, Accept'
|
||||
|
||||
# merge with headers possibly set at some point in the view
|
||||
response.headers.update(self.headers)
|
||||
return self.render(response)
|
||||
|
||||
def add_header(self, field, value):
|
||||
"""
|
||||
Add *field* and *value* to the :attr:`headers` attribute of the :class:`View` class.
|
||||
"""
|
||||
self.headers[field] = value
|
||||
|
||||
# Note: session based authentication is explicitly CSRF validated,
|
||||
# all other authentication is CSRF exempt.
|
||||
@csrf_exempt
|
||||
def dispatch(self, request, *args, **kwargs):
|
||||
self.request = request
|
||||
self.args = args
|
||||
self.kwargs = kwargs
|
||||
self.headers = {}
|
||||
|
||||
try:
|
||||
self.initial(request, *args, **kwargs)
|
||||
|
||||
# Authenticate and check request has the relevant permissions
|
||||
self._check_permissions()
|
||||
|
||||
# Get the appropriate handler method
|
||||
if self.method.lower() in self.http_method_names:
|
||||
handler = getattr(self, self.method.lower(), self.http_method_not_allowed)
|
||||
else:
|
||||
handler = self.http_method_not_allowed
|
||||
|
||||
response_obj = handler(request, *args, **kwargs)
|
||||
|
||||
# Allow return value to be either HttpResponse, Response, or an object, or None
|
||||
if isinstance(response_obj, HttpResponse):
|
||||
return response_obj
|
||||
elif isinstance(response_obj, Response):
|
||||
response = response_obj
|
||||
elif response_obj is not None:
|
||||
response = Response(status.HTTP_200_OK, response_obj)
|
||||
else:
|
||||
response = Response(status.HTTP_204_NO_CONTENT)
|
||||
|
||||
# Pre-serialize filtering (eg filter complex objects into natively serializable types)
|
||||
response.cleaned_content = self.filter_response(response.raw_content)
|
||||
|
||||
except ErrorResponse, exc:
|
||||
response = exc.response
|
||||
|
||||
return self.final(request, response, *args, **kwargs)
|
||||
|
||||
def options(self, request, *args, **kwargs):
|
||||
response_obj = {
|
||||
'name': self.get_name(),
|
||||
'description': self.get_description(),
|
||||
'renders': self._rendered_media_types,
|
||||
'parses': self._parsed_media_types,
|
||||
}
|
||||
form = self.get_bound_form()
|
||||
if form is not None:
|
||||
field_name_types = {}
|
||||
for name, field in form.fields.iteritems():
|
||||
field_name_types[name] = field.__class__.__name__
|
||||
response_obj['fields'] = field_name_types
|
||||
# Note 'ErrorResponse' is misleading, it's just any response
|
||||
# that should be rendered and returned immediately, without any
|
||||
# response filtering.
|
||||
raise ErrorResponse(status.HTTP_200_OK, response_obj)
|
||||
|
||||
|
||||
class ModelView(View):
|
||||
"""
|
||||
A RESTful view that maps to a model in the database.
|
||||
"""
|
||||
resource = resources.ModelResource
|
||||
|
||||
|
||||
class InstanceModelView(ReadModelMixin, UpdateModelMixin, DeleteModelMixin, ModelView):
|
||||
"""
|
||||
A view which provides default operations for read/update/delete against a model instance.
|
||||
"""
|
||||
_suffix = 'Instance'
|
||||
|
||||
|
||||
class ListModelView(ListModelMixin, ModelView):
|
||||
"""
|
||||
A view which provides default operations for list, against a model in the database.
|
||||
"""
|
||||
_suffix = 'List'
|
||||
|
||||
|
||||
class ListOrCreateModelView(ListModelMixin, CreateModelMixin, ModelView):
|
||||
"""
|
||||
A view which provides default operations for list and create, against a model in the database.
|
||||
"""
|
||||
_suffix = 'List'
|
126
docs/api-guide/authentication.md
Normal file
126
docs/api-guide/authentication.md
Normal file
|
@ -0,0 +1,126 @@
|
|||
<a class="github" href="authentication.py"></a>
|
||||
|
||||
# Authentication
|
||||
|
||||
> Auth needs to be pluggable.
|
||||
>
|
||||
> — Jacob Kaplan-Moss, ["REST worst practices"][cite]
|
||||
|
||||
Authentication is the mechanism of associating an incoming request with a set of identifying credentials, such as the user the request came from, or the token that it was signed with. The [permission] and [throttling] policies can then use those credentials to determine if the request should be permitted.
|
||||
|
||||
REST framework provides a number of authentication policies out of the box, and also allows you to implement custom policies.
|
||||
|
||||
Authentication will run the first time either the `request.user` or `request.auth` properties are accessed, and determines how those properties are initialized.
|
||||
|
||||
The `request.user` property will typically be set to an instance of the `contrib.auth` package's `User` class.
|
||||
|
||||
The `request.auth` property is used for any additional authentication information, for example, it may be used to represent an authentication token that the request was signed with.
|
||||
|
||||
## How authentication is determined
|
||||
|
||||
The authentication policy is always defined as a list of classes. REST framework will attempt to authenticate with each class in the list, and will set `request.user` and `request.auth` using the return value of the first class that successfully authenticates.
|
||||
|
||||
If no class authenticates, `request.user` will be set to an instance of `django.contrib.auth.models.AnonymousUser`, and `request.auth` will be set to `None`.
|
||||
|
||||
The value of `request.user` and `request.auth` for unauthenticated requests can be modified using the `UNAUTHENTICATED_USER` and `UNAUTHENTICATED_TOKEN` settings.
|
||||
|
||||
## Setting the authentication policy
|
||||
|
||||
The default authentication policy may be set globally, using the `DEFAULT_AUTHENTICATION_CLASSES` setting. For example.
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
'DEFAULT_AUTHENTICATION_CLASSES': (
|
||||
'rest_framework.authentication.UserBasicAuthentication',
|
||||
'rest_framework.authentication.SessionAuthentication',
|
||||
)
|
||||
}
|
||||
|
||||
You can also set the authentication policy on a per-view basis, using the `APIView` class based views.
|
||||
|
||||
class ExampleView(APIView):
|
||||
authentication_classes = (SessionAuthentication, UserBasicAuthentication)
|
||||
permission_classes = (IsAuthenticated,)
|
||||
|
||||
def get(self, request, format=None):
|
||||
content = {
|
||||
'user': unicode(request.user), # `django.contrib.auth.User` instance.
|
||||
'auth': unicode(request.auth), # None
|
||||
}
|
||||
return Response(content)
|
||||
|
||||
Or, if you're using the `@api_view` decorator with function based views.
|
||||
|
||||
@api_view(['GET'])
|
||||
@authentication_classes((SessionAuthentication, UserBasicAuthentication))
|
||||
@permissions_classes((IsAuthenticated,))
|
||||
def example_view(request, format=None):
|
||||
content = {
|
||||
'user': unicode(request.user), # `django.contrib.auth.User` instance.
|
||||
'auth': unicode(request.auth), # None
|
||||
}
|
||||
return Response(content)
|
||||
|
||||
# API Reference
|
||||
|
||||
## BasicAuthentication
|
||||
|
||||
This policy uses [HTTP Basic Authentication][basicauth], signed against a user's username and password. Basic authentication is generally only appropriate for testing.
|
||||
|
||||
If successfully authenticated, `BasicAuthentication` provides the following credentials.
|
||||
|
||||
* `request.user` will be a `django.contrib.auth.models.User` instance.
|
||||
* `request.auth` will be `None`.
|
||||
|
||||
**Note:** If you use `BasicAuthentication` in production you must ensure that your API is only available over `https` only. You should also ensure that your API clients will always re-request the username and password at login, and will never store those details to persistent storage.
|
||||
|
||||
## TokenAuthentication
|
||||
|
||||
This policy uses a simple token-based HTTP Authentication scheme. Token authentication is appropriate for client-server setups, such as native desktop and mobile clients.
|
||||
|
||||
To use the `TokenAuthentication` policy, include `rest_framework.authtoken` in your `INSTALLED_APPS` setting.
|
||||
|
||||
You'll also need to create tokens for your users.
|
||||
|
||||
from rest_framework.authtoken.models import Token
|
||||
|
||||
token = Token.objects.create(user=...)
|
||||
print token.key
|
||||
|
||||
For clients to authenticate, the token key should be included in the `Authorization` HTTP header. The key should be prefixed by the string literal "Token", with whitespace separating the two strings. For example:
|
||||
|
||||
Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b
|
||||
|
||||
If successfully authenticated, `TokenAuthentication` provides the following credentials.
|
||||
|
||||
* `request.user` will be a `django.contrib.auth.models.User` instance.
|
||||
* `request.auth` will be a `rest_framework.tokenauth.models.BasicToken` instance.
|
||||
|
||||
**Note:** If you use `TokenAuthentication` in production you must ensure that your API is only available over `https` only.
|
||||
|
||||
## OAuthAuthentication
|
||||
|
||||
This policy uses the [OAuth 2.0][oauth] protocol to authenticate requests. OAuth is appropriate for server-server setups, such as when you want to allow a third-party service to access your API on a user's behalf.
|
||||
|
||||
If successfully authenticated, `OAuthAuthentication` provides the following credentials.
|
||||
|
||||
* `request.user` will be a `django.contrib.auth.models.User` instance.
|
||||
* `request.auth` will be a `rest_framework.models.OAuthToken` instance.
|
||||
|
||||
## SessionAuthentication
|
||||
|
||||
This policy uses Django's default session backend for authentication. Session authentication is appropriate for AJAX clients that are running in the same session context as your website.
|
||||
|
||||
If successfully authenticated, `SessionAuthentication` provides the following credentials.
|
||||
|
||||
* `request.user` will be a `django.contrib.auth.models.User` instance.
|
||||
* `request.auth` will be `None`.
|
||||
|
||||
# Custom authentication
|
||||
|
||||
To implement a custom authentication policy, subclass `BaseAuthentication` and override the `.authenticate(self, request)` method. The method should return a two-tuple of `(user, auth)` if authentication succeeds, or `None` otherwise.
|
||||
|
||||
[cite]: http://jacobian.org/writing/rest-worst-practices/
|
||||
[basicauth]: http://tools.ietf.org/html/rfc2617
|
||||
[oauth]: http://oauth.net/2/
|
||||
[permission]: permissions.md
|
||||
[throttling]: throttling.md
|
66
docs/api-guide/content-negotiation.md
Normal file
66
docs/api-guide/content-negotiation.md
Normal file
|
@ -0,0 +1,66 @@
|
|||
<a class="github" href="negotiation.py"></a>
|
||||
|
||||
# Content negotiation
|
||||
|
||||
> HTTP has provisions for several mechanisms for "content negotiation" - the process of selecting the best representation for a given response when there are multiple representations available.
|
||||
>
|
||||
> — [RFC 2616][cite], Fielding et al.
|
||||
|
||||
[cite]: http://www.w3.org/Protocols/rfc2616/rfc2616-sec12.html
|
||||
|
||||
Content negotiation is the process of selecting one of multiple possible representations to return to a client, based on client or server preferences.
|
||||
|
||||
## Determining the accepted renderer
|
||||
|
||||
REST framework uses a simple style of content negotiation to determine which media type should be returned to a client, based on the available renderers, the priorities of each of those renderers, and the client's `Accept:` header. The style used is partly client-driven, and partly server-driven.
|
||||
|
||||
1. More specific media types are given preference to less specific media types.
|
||||
2. If multiple media types have the same specificity, then preference is given to based on the ordering of the renderers configured for the given view.
|
||||
|
||||
For example, given the following `Accept` header:
|
||||
|
||||
application/json; indent=4, application/json, application/yaml, text/html, */*
|
||||
|
||||
The priorities for each of the given media types would be:
|
||||
|
||||
* `application/json; indent=4`
|
||||
* `application/json`, `application/yaml` and `text/html`
|
||||
* `*/*`
|
||||
|
||||
If the requested view was only configured with renderers for `YAML` and `HTML`, then REST framework would select whichever renderer was listed first in the `renderer_classes` list or `DEFAULT_RENDERER_CLASSES` setting.
|
||||
|
||||
For more information on the `HTTP Accept` header, see [RFC 2616][accept-header]
|
||||
|
||||
---
|
||||
|
||||
**Note**: "q" values are not taken into account by REST framework when determining preference. The use of "q" values negatively impacts caching, and in the author's opinion they are an unnecessary and overcomplicated approach to content negotiation.
|
||||
|
||||
This is a valid approach as the HTTP spec deliberately underspecifies how a server should weight server-based preferences against client-based preferences.
|
||||
|
||||
---
|
||||
|
||||
# Custom content negotiation
|
||||
|
||||
It's unlikely that you'll want to provide a custom content negotiation scheme for REST framework, but you can do so if needed. To implement a custom content negotiation scheme override `BaseContentNegotiation`.
|
||||
|
||||
REST framework's content negotiation classes handle selection of both the appropriate parser for the request, and the appropriate renderer for the response, so you should implement both the `.select_parser(request, parsers)` and `.select_renderer(request, renderers, format_suffix)` methods.
|
||||
|
||||
## Example
|
||||
|
||||
The following is a custom content negotiation class which ignores the client
|
||||
request when selecting the appropriate parser or renderer.
|
||||
|
||||
class IgnoreClientContentNegotiation(BaseContentNegotiation):
|
||||
def select_parser(self, request, parsers):
|
||||
"""
|
||||
Select the first parser in the `.parser_classes` list.
|
||||
"""
|
||||
return parsers[0]
|
||||
|
||||
def select_renderer(self, request, renderers, format_suffix):
|
||||
"""
|
||||
Select the first renderer in the `.renderer_classes` list.
|
||||
"""
|
||||
return renderers[0]
|
||||
|
||||
[accept-header]: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
|
88
docs/api-guide/exceptions.md
Normal file
88
docs/api-guide/exceptions.md
Normal file
|
@ -0,0 +1,88 @@
|
|||
<a class="github" href="exceptions.py"></a>
|
||||
|
||||
# Exceptions
|
||||
|
||||
> Exceptions… allow error handling to be organized cleanly in a central or high-level place within the program structure.
|
||||
>
|
||||
> — Doug Hellmann, [Python Exception Handling Techniques][cite]
|
||||
|
||||
## Exception handling in REST framework views
|
||||
|
||||
REST framework's views handle various exceptions, and deal with returning appropriate error responses.
|
||||
|
||||
The handled exceptions are:
|
||||
|
||||
* Subclasses of `APIException` raised inside REST framework.
|
||||
* Django's `Http404` exception.
|
||||
* Django's `PermissionDenied` exception.
|
||||
|
||||
In each case, REST framework will return a response with an appropriate status code and content-type. The body of the response will include any additional details regarding the nature of the error.
|
||||
|
||||
By default all error responses will include a key `details` in the body of the response, but other keys may also be included.
|
||||
|
||||
For example, the following request:
|
||||
|
||||
DELETE http://api.example.com/foo/bar HTTP/1.1
|
||||
Accept: application/json
|
||||
|
||||
Might receive an error response indicating that the `DELETE` method is not allowed on that resource:
|
||||
|
||||
HTTP/1.1 405 Method Not Allowed
|
||||
Content-Type: application/json; charset=utf-8
|
||||
Content-Length: 42
|
||||
|
||||
{"detail": "Method 'DELETE' not allowed."}
|
||||
|
||||
---
|
||||
|
||||
# API Reference
|
||||
|
||||
## APIException
|
||||
|
||||
**Signature:** `APIException(detail=None)`
|
||||
|
||||
The **base class** for all exceptions raised inside REST framework.
|
||||
|
||||
To provide a custom exception, subclass `APIException` and set the `.status_code` and `.detail` properties on the class.
|
||||
|
||||
## ParseError
|
||||
|
||||
**Signature:** `ParseError(detail=None)`
|
||||
|
||||
Raised if the request contains malformed data when accessing `request.DATA` or `request.FILES`.
|
||||
|
||||
By default this exception results in a response with the HTTP status code "400 Bad Request".
|
||||
|
||||
## PermissionDenied
|
||||
|
||||
**Signature:** `PermissionDenied(detail=None)`
|
||||
|
||||
Raised when an incoming request fails the permission checks.
|
||||
|
||||
By default this exception results in a response with the HTTP status code "403 Forbidden".
|
||||
|
||||
## MethodNotAllowed
|
||||
|
||||
**Signature:** `MethodNotAllowed(method, detail=None)`
|
||||
|
||||
Raised when an incoming request occurs that does not map to a handler method on the view.
|
||||
|
||||
By default this exception results in a response with the HTTP status code "405 Method Not Allowed".
|
||||
|
||||
## UnsupportedMediaType
|
||||
|
||||
**Signature:** `UnsupportedMediaType(media_type, detail=None)`
|
||||
|
||||
Raised if there are no parsers that can handle the content type of the request data when accessing `request.DATA` or `request.FILES`.
|
||||
|
||||
By default this exception results in a response with the HTTP status code "415 Unsupported Media Type".
|
||||
|
||||
## Throttled
|
||||
|
||||
**Signature:** `Throttled(wait=None, detail=None)`
|
||||
|
||||
Raised when an incoming request fails the throttling checks.
|
||||
|
||||
By default this exception results in a response with the HTTP status code "429 Too Many Requests".
|
||||
|
||||
[cite]: http://www.doughellmann.com/articles/how-tos/python-exception-handling/index.html
|
278
docs/api-guide/fields.md
Normal file
278
docs/api-guide/fields.md
Normal file
|
@ -0,0 +1,278 @@
|
|||
<a class="github" href="fields.py"></a>
|
||||
|
||||
# Serializer fields
|
||||
|
||||
> Flat is better than nested.
|
||||
>
|
||||
> — [The Zen of Python][cite]
|
||||
|
||||
Serializer fields handle converting between primative values and internal datatypes. They also deal with validating input values, as well as retrieving and setting the values from their parent objects.
|
||||
|
||||
---
|
||||
|
||||
**Note:** The serializer fields are declared in fields.py, but by convention you should import them using `from rest_framework import serializers` and refer to fields as `serializers.<FieldName>`.
|
||||
|
||||
---
|
||||
|
||||
## Core arguments
|
||||
|
||||
Each serializer field class constructor takes at least these arguments. Some Field classes take additional, field-specific arguments, but the following should always be accepted:
|
||||
|
||||
### `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 `Field(source='get_absolute_url')`, or may use dotted notation to traverse attributes, such as `Field(source='user.email')`.
|
||||
|
||||
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. (See the implementation of the `PaginationSerializer` class for an example.)
|
||||
|
||||
Defaults to the name of the field.
|
||||
|
||||
### `read_only`
|
||||
|
||||
Set this to `True` to ensure that the field is used when serializing a representation, but is not used when updating an instance dureing deserialization.
|
||||
|
||||
Defaults to `False`
|
||||
|
||||
### `required`
|
||||
|
||||
Normally an error will be raised if a field is not supplied during deserialization.
|
||||
Set to false if this field is not required to be present during deserialization.
|
||||
|
||||
Defaults to `True`.
|
||||
|
||||
### `default`
|
||||
|
||||
If set, this gives the default value that will be used for the field if none is supplied. If not set the default behaviour is to not populate the attribute at all.
|
||||
|
||||
### `validators`
|
||||
|
||||
A list of Django validators that should be used to validate deserialized values.
|
||||
|
||||
### `error_messages`
|
||||
|
||||
A dictionary of error codes to error messages.
|
||||
|
||||
### `widget`
|
||||
|
||||
Used only if rendering the field to HTML.
|
||||
This argument sets the widget that should be used to render the field.
|
||||
|
||||
|
||||
---
|
||||
|
||||
# Generic Fields
|
||||
|
||||
These generic fields are used for representing arbitrary model fields or the output of model methods.
|
||||
|
||||
## Field
|
||||
|
||||
A generic, **read-only** field. You can use this field for any attribute that does not need to support write operations.
|
||||
|
||||
For example, using the following model.
|
||||
|
||||
class Account(models.Model):
|
||||
owner = models.ForeignKey('auth.user')
|
||||
name = models.CharField(max_length=100)
|
||||
created = models.DateTimeField(auto_now_add=True)
|
||||
payment_expiry = models.DateTimeField()
|
||||
|
||||
def has_expired(self):
|
||||
now = datetime.datetime.now()
|
||||
return now > self.payment_expiry
|
||||
|
||||
A serializer definition that looked like this:
|
||||
|
||||
class AccountSerializer(serializers.HyperlinkedModelSerializer):
|
||||
expired = Field(source='has_expired')
|
||||
|
||||
class Meta:
|
||||
fields = ('url', 'owner', 'name', 'expired')
|
||||
|
||||
Would produce output similar to:
|
||||
|
||||
{
|
||||
'url': 'http://example.com/api/accounts/3/',
|
||||
'owner': 'http://example.com/api/users/12/',
|
||||
'name': 'FooCorp business account',
|
||||
'expired': True
|
||||
}
|
||||
|
||||
By default, the `Field` class will perform a basic translation of the source value into primative datatypes, falling back to unicode representations of complex datatypes when necessary.
|
||||
|
||||
You can customize this behaviour by overriding the `.to_native(self, value)` method.
|
||||
|
||||
## WritableField
|
||||
|
||||
A field that supports both read and write operations. By itself `WriteableField` does not perform any translation of input values into a given type. You won't typically use this field directly, but you may want to override it and implement the `.to_native(self, value)` and `.from_native(self, value)` methods.
|
||||
|
||||
## ModelField
|
||||
|
||||
A generic field that can be tied to any arbitrary model field. The `ModelField` class delegates the task of serialization/deserialization to it's associated model field. This field can be used to create serializer fields for custom model fields, without having to create a new custom serializer field.
|
||||
|
||||
**Signature:** `ModelField(model_field=<Django ModelField class>)`
|
||||
|
||||
---
|
||||
|
||||
# Typed Fields
|
||||
|
||||
These fields represent basic datatypes, and support both reading and writing values.
|
||||
|
||||
## BooleanField
|
||||
|
||||
A Boolean representation.
|
||||
|
||||
Corresponds to `django.db.models.fields.BooleanField`.
|
||||
|
||||
## CharField
|
||||
|
||||
A text representation, optionally validates the text to be shorter than `max_length` and longer than `min_length`.
|
||||
|
||||
Corresponds to `django.db.models.fields.CharField`
|
||||
or `django.db.models.fields.TextField`.
|
||||
|
||||
**Signature:** `CharField(max_length=None, min_length=None)`
|
||||
|
||||
## ChoiceField
|
||||
|
||||
A field that can accept a value out of a limited set of choices.
|
||||
|
||||
## EmailField
|
||||
|
||||
A text representation, validates the text to be a valid e-mail address.
|
||||
|
||||
Corresponds to `django.db.models.fields.EmailField`
|
||||
|
||||
## DateField
|
||||
|
||||
A date representation.
|
||||
|
||||
Corresponds to `django.db.models.fields.DateField`
|
||||
|
||||
## DateTimeField
|
||||
|
||||
A date and time representation.
|
||||
|
||||
Corresponds to `django.db.models.fields.DateTimeField`
|
||||
|
||||
## IntegerField
|
||||
|
||||
An integer representation.
|
||||
|
||||
Corresponds to `django.db.models.fields.IntegerField`, `django.db.models.fields.SmallIntegerField`, `django.db.models.fields.PositiveIntegerField` and `django.db.models.fields.PositiveSmallIntegerField`
|
||||
|
||||
## FloatField
|
||||
|
||||
A floating point representation.
|
||||
|
||||
Corresponds to `django.db.models.fields.FloatField`.
|
||||
|
||||
---
|
||||
|
||||
# Relational Fields
|
||||
|
||||
Relational fields are used to represent model relationships. They can be applied to `ForeignKey`, `ManyToManyField` and `OneToOneField` relationships, as well as to reverse relationships, and custom relationships such as `GenericForeignKey`.
|
||||
|
||||
## RelatedField
|
||||
|
||||
This field can be applied to any of the following:
|
||||
|
||||
* A `ForeignKey` field.
|
||||
* A `OneToOneField` field.
|
||||
* A reverse OneToOne relationship
|
||||
* Any other "to-one" relationship.
|
||||
|
||||
By default `RelatedField` will represent the target of the field using it's `__unicode__` method.
|
||||
|
||||
You can customise this behaviour by subclassing `ManyRelatedField`, and overriding the `.to_native(self, value)` method.
|
||||
|
||||
## ManyRelatedField
|
||||
|
||||
This field can be applied to any of the following:
|
||||
|
||||
* A `ManyToManyField` field.
|
||||
* A reverse ManyToMany relationship.
|
||||
* A reverse ForeignKey relationship
|
||||
* Any other "to-many" relationship.
|
||||
|
||||
By default `ManyRelatedField` will represent the targets of the field using their `__unicode__` method.
|
||||
|
||||
For example, given the following models:
|
||||
|
||||
class TaggedItem(models.Model):
|
||||
"""
|
||||
Tags arbitrary model instances using a generic relation.
|
||||
|
||||
See: https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/
|
||||
"""
|
||||
tag = models.SlugField()
|
||||
content_type = models.ForeignKey(ContentType)
|
||||
object_id = models.PositiveIntegerField()
|
||||
content_object = GenericForeignKey('content_type', 'object_id')
|
||||
|
||||
def __unicode__(self):
|
||||
return self.tag
|
||||
|
||||
|
||||
class Bookmark(models.Model):
|
||||
"""
|
||||
A bookmark consists of a URL, and 0 or more descriptive tags.
|
||||
"""
|
||||
url = models.URLField()
|
||||
tags = GenericRelation(TaggedItem)
|
||||
|
||||
And a model serializer defined like this:
|
||||
|
||||
class BookmarkSerializer(serializers.ModelSerializer):
|
||||
tags = serializers.ManyRelatedField(source='tags')
|
||||
|
||||
class Meta:
|
||||
model = Bookmark
|
||||
exclude = ('id',)
|
||||
|
||||
Then an example output format for a Bookmark instance would be:
|
||||
|
||||
{
|
||||
'tags': [u'django', u'python'],
|
||||
'url': u'https://www.djangoproject.com/'
|
||||
}
|
||||
|
||||
## PrimaryKeyRelatedField
|
||||
|
||||
This field can be applied to any "to-one" relationship, such as a `ForeignKey` field.
|
||||
|
||||
`PrimaryKeyRelatedField` will represent the target of the field using it's primary key.
|
||||
|
||||
Be default, `PrimaryKeyRelatedField` is read-write, although you can change this behaviour using the `read_only` flag.
|
||||
|
||||
## ManyPrimaryKeyRelatedField
|
||||
|
||||
This field can be applied to any "to-many" relationship, such as a `ManyToManyField` field, or a reverse `ForeignKey` relationship.
|
||||
|
||||
`PrimaryKeyRelatedField` will represent the targets of the field using their primary key.
|
||||
|
||||
Be default, `ManyPrimaryKeyRelatedField` is read-write, although you can change this behaviour using the `read_only` flag.
|
||||
|
||||
## HyperlinkedRelatedField
|
||||
|
||||
This field can be applied to any "to-one" relationship, such as a `ForeignKey` field.
|
||||
|
||||
`HyperlinkedRelatedField` will represent the target of the field using a hyperlink. You must include a named URL pattern in your URL conf, with a name like `'{model-name}-detail'` that corresponds to the target of the hyperlink.
|
||||
|
||||
Be default, `HyperlinkedRelatedField` is read-write, although you can change this behaviour using the `read_only` flag.
|
||||
|
||||
## ManyHyperlinkedRelatedField
|
||||
|
||||
This field can be applied to any "to-many" relationship, such as a `ManyToManyField` field, or a reverse `ForeignKey` relationship.
|
||||
|
||||
`ManyHyperlinkedRelatedField` will represent the targets of the field using hyperlinks. You must include a named URL pattern in your URL conf, with a name like `'{model-name}-detail'` that corresponds to the target of the hyperlink.
|
||||
|
||||
Be default, `ManyHyperlinkedRelatedField` is read-write, although you can change this behaviour using the `read_only` flag.
|
||||
|
||||
## HyperLinkedIdentityField
|
||||
|
||||
This field can be applied as an identity relationship, such as the `'url'` field on a HyperlinkedModelSerializer.
|
||||
|
||||
You must include a named URL pattern in your URL conf, with a name like `'{model-name}-detail'` that corresponds to the model.
|
||||
|
||||
This field is always read-only.
|
||||
|
||||
[cite]: http://www.python.org/dev/peps/pep-0020/
|
61
docs/api-guide/format-suffixes.md
Normal file
61
docs/api-guide/format-suffixes.md
Normal file
|
@ -0,0 +1,61 @@
|
|||
<a class="github" href="urlpatterns.py"></a>
|
||||
|
||||
# Format suffixes
|
||||
|
||||
> Section 6.2.1 does not say that content negotiation should be
|
||||
used all the time.
|
||||
>
|
||||
> — Roy Fielding, [REST discuss mailing list][cite]
|
||||
|
||||
A common pattern for Web APIs is to use filename extensions on URLs to provide an endpoint for a given media type. For example, 'http://example.com/api/users.json' to serve a JSON representation.
|
||||
|
||||
Adding format-suffix patterns to each individual entry in the URLconf for your API is error-prone and non-DRY, so REST framework provides a shortcut to adding these patterns to your URLConf.
|
||||
|
||||
## format_suffix_patterns
|
||||
|
||||
**Signature**: format_suffix_patterns(urlpatterns, suffix_required=False, allowed=None)
|
||||
|
||||
Returns a URL pattern list which includes format suffix patterns appended to each of the URL patterns provided.
|
||||
|
||||
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.
|
||||
|
||||
Example:
|
||||
|
||||
from rest_framework.urlpatterns import format_suffix_patterns
|
||||
|
||||
urlpatterns = patterns('blog.views',
|
||||
url(r'^/$', 'api_root'),
|
||||
url(r'^comment/$', 'comment_root'),
|
||||
url(r'^comment/(?P<pk>[0-9]+)/$', 'comment_instance')
|
||||
)
|
||||
|
||||
urlpatterns = format_suffix_patterns(urlpatterns, allowed=['json', 'html'])
|
||||
|
||||
When using `format_suffix_patterns`, you must make sure to add the `'format'` keyword argument to the corresponding views. For example.
|
||||
|
||||
@api_view(('GET',))
|
||||
def api_root(request, format=None):
|
||||
# do stuff...
|
||||
|
||||
The name of the kwarg used may be modified by using the `FORMAT_SUFFIX_KWARG` setting.
|
||||
|
||||
Also note that `format_suffix_patterns` does not support descending into `include` URL patterns.
|
||||
|
||||
---
|
||||
|
||||
## Accept headers vs. format suffixes
|
||||
|
||||
There seems to be a view among some of the Web community that filename extensions are not a RESTful pattern, and that `HTTP Accept` headers should always be used instead.
|
||||
|
||||
It is actually a misconception. For example, take the following quote from Roy Fielding discussing the relative merits of query parameter media-type indicators vs. file extension media-type indicators:
|
||||
|
||||
“That's why I always prefer extensions. Neither choice has anything to do with REST.” — Roy Fielding, [REST discuss mailing list][cite2]
|
||||
|
||||
The quote does not mention Accept headers, but it does make it clear that format suffixes should be considered an acceptable pattern.
|
||||
|
||||
[cite]: http://tech.groups.yahoo.com/group/rest-discuss/message/5857
|
||||
[cite2]: http://tech.groups.yahoo.com/group/rest-discuss/message/14844
|
187
docs/api-guide/generic-views.md
Normal file
187
docs/api-guide/generic-views.md
Normal file
|
@ -0,0 +1,187 @@
|
|||
<a class="github" href="mixins.py"></a>
|
||||
<a class="github" href="generics.py"></a>
|
||||
|
||||
# Generic views
|
||||
|
||||
> Django’s generic views... were developed as a shortcut for common usage patterns... They take certain common idioms and patterns found in view development and abstract them so that you can quickly write common views of data without having to repeat yourself.
|
||||
>
|
||||
> — [Django Documentation][cite]
|
||||
|
||||
One of the key benefits of class based views is the way they allow you to compose bits of reusable behaviour. REST framework takes advantage of this by providing a number of pre-built views that provide for commonly used patterns.
|
||||
|
||||
The generic views provided by REST framework allow you to quickly build API views that map closely to your database models.
|
||||
|
||||
If the generic views don't suit the needs of your API, you can drop down to using the regular `APIView` class, or reuse the mixins and base classes used by the generic views to compose your own set of reusable generic views.
|
||||
|
||||
## Examples
|
||||
|
||||
Typically when using the generic views, you'll override the view, and set several class attributes.
|
||||
|
||||
class UserList(generics.ListCreateAPIView):
|
||||
model = User
|
||||
serializer_class = UserSerializer
|
||||
permission_classes = (IsAdminUser,)
|
||||
paginate_by = 100
|
||||
|
||||
For more complex cases you might also want to override various methods on the view class. For example.
|
||||
|
||||
class UserList(generics.ListCreateAPIView):
|
||||
model = User
|
||||
serializer_class = UserSerializer
|
||||
permission_classes = (IsAdminUser,)
|
||||
|
||||
def get_paginate_by(self, queryset):
|
||||
"""
|
||||
Use smaller pagination for HTML representations.
|
||||
"""
|
||||
page_size_param = self.request.QUERY_PARAMS.get('page_size')
|
||||
if page_size_param:
|
||||
return int(page_size_param)
|
||||
return 100
|
||||
|
||||
For very simple cases you might want to pass through any class attributes using the `.as_view()` method. For example, your URLconf might include something the following entry.
|
||||
|
||||
url(r'^/users/', ListCreateAPIView.as_view(model=User) name='user-list')
|
||||
|
||||
---
|
||||
|
||||
# API Reference
|
||||
|
||||
The following classes are the concrete generic views. If you're using generic views this is normally the level you'll be working at unless you need heavily customized behavior.
|
||||
|
||||
## CreateAPIView
|
||||
|
||||
Used for **create-only** endpoints.
|
||||
|
||||
Provides `post` method handlers.
|
||||
|
||||
Extends: [GenericAPIView], [CreateModelMixin]
|
||||
|
||||
## ListAPIView
|
||||
|
||||
Used for **read-only** endpoints to represent a **collection of model instances**.
|
||||
|
||||
Provides a `get` method handler.
|
||||
|
||||
Extends: [MultipleObjectAPIView], [ListModelMixin]
|
||||
|
||||
## RetrieveAPIView
|
||||
|
||||
Used for **read-only** endpoints to represent a **single model instance**.
|
||||
|
||||
Provides a `get` method handler.
|
||||
|
||||
Extends: [SingleObjectAPIView], [RetrieveModelMixin]
|
||||
|
||||
## DestroyAPIView
|
||||
|
||||
Used for **delete-only** endpoints for a **single model instance**.
|
||||
|
||||
Provides a `delete` method handler.
|
||||
|
||||
Extends: [SingleObjectAPIView], [DestroyModelMixin]
|
||||
|
||||
## UpdateAPIView
|
||||
|
||||
Used for **update-only** endpoints for a **single model instance**.
|
||||
|
||||
Provides a `put` method handler.
|
||||
|
||||
Extends: [SingleObjectAPIView], [UpdateModelMixin]
|
||||
|
||||
## ListCreateAPIView
|
||||
|
||||
Used for **read-write** endpoints to represent a **collection of model instances**.
|
||||
|
||||
Provides `get` and `post` method handlers.
|
||||
|
||||
Extends: [MultipleObjectAPIView], [ListModelMixin], [CreateModelMixin]
|
||||
|
||||
## RetrieveDestroyAPIView
|
||||
|
||||
Used for **read or delete** endpoints to represent a **single model instance**.
|
||||
|
||||
Provides `get` and `delete` method handlers.
|
||||
|
||||
Extends: [SingleObjectAPIView], [RetrieveModelMixin], [DestroyModelMixin]
|
||||
|
||||
## RetrieveUpdateDestroyAPIView
|
||||
|
||||
Used for **read-write-delete** endpoints to represent a **single model instance**.
|
||||
|
||||
Provides `get`, `put` and `delete` method handlers.
|
||||
|
||||
Extends: [SingleObjectAPIView], [RetrieveModelMixin], [UpdateModelMixin], [DestroyModelMixin]
|
||||
|
||||
---
|
||||
|
||||
# Base views
|
||||
|
||||
Each of the generic views provided is built by combining one of the base views below, with one or more mixin classes.
|
||||
|
||||
## GenericAPIView
|
||||
|
||||
Extends REST framework's `APIView` class, adding support for serialization of model instances and model querysets.
|
||||
|
||||
## MultipleObjectAPIView
|
||||
|
||||
Provides a base view for acting on a single object, by combining REST framework's `APIView`, and Django's [MultipleObjectMixin].
|
||||
|
||||
**See also:** ccbv.co.uk documentation for [MultipleObjectMixin][multiple-object-mixin-classy].
|
||||
|
||||
## SingleObjectAPIView
|
||||
|
||||
Provides a base view for acting on a single object, by combining REST framework's `APIView`, and Django's [SingleObjectMixin].
|
||||
|
||||
**See also:** ccbv.co.uk documentation for [SingleObjectMixin][single-object-mixin-classy].
|
||||
|
||||
---
|
||||
|
||||
# Mixins
|
||||
|
||||
The mixin classes provide the actions that are used to provide the basic view behaviour. Note that the mixin classes provide action methods rather than defining the handler methods such as `.get()` and `.post()` directly. This allows for more flexible composition of behaviour.
|
||||
|
||||
## ListModelMixin
|
||||
|
||||
Provides a `.list(request, *args, **kwargs)` method, that implements listing a queryset.
|
||||
|
||||
Should be mixed in with [MultipleObjectAPIView].
|
||||
|
||||
## CreateModelMixin
|
||||
|
||||
Provides a `.create(request, *args, **kwargs)` method, that implements creating and saving a new model instance.
|
||||
|
||||
Should be mixed in with any [GenericAPIView].
|
||||
|
||||
## RetrieveModelMixin
|
||||
|
||||
Provides a `.retrieve(request, *args, **kwargs)` method, that implements returning an existing model instance in a response.
|
||||
|
||||
Should be mixed in with [SingleObjectAPIView].
|
||||
|
||||
## UpdateModelMixin
|
||||
|
||||
Provides a `.update(request, *args, **kwargs)` method, that implements updating and saving an existing model instance.
|
||||
|
||||
Should be mixed in with [SingleObjectAPIView].
|
||||
|
||||
## DestroyModelMixin
|
||||
|
||||
Provides a `.destroy(request, *args, **kwargs)` method, that implements deletion of an existing model instance.
|
||||
|
||||
Should be mixed in with [SingleObjectAPIView].
|
||||
|
||||
[cite]: https://docs.djangoproject.com/en/dev/ref/class-based-views/#base-vs-generic-views
|
||||
[MultipleObjectMixin]: https://docs.djangoproject.com/en/dev/ref/class-based-views/mixins-multiple-object/
|
||||
[SingleObjectMixin]: https://docs.djangoproject.com/en/dev/ref/class-based-views/mixins-single-object/
|
||||
[multiple-object-mixin-classy]: http://ccbv.co.uk/projects/Django/1.4/django.views.generic.list/MultipleObjectMixin/
|
||||
[single-object-mixin-classy]: http://ccbv.co.uk/projects/Django/1.4/django.views.generic.detail/SingleObjectMixin/
|
||||
|
||||
[GenericAPIView]: #genericapiview
|
||||
[SingleObjectAPIView]: #singleobjectapiview
|
||||
[MultipleObjectAPIView]: #multipleobjectapiview
|
||||
[ListModelMixin]: #listmodelmixin
|
||||
[CreateModelMixin]: #createmodelmixin
|
||||
[RetrieveModelMixin]: #retrievemodelmixin
|
||||
[UpdateModelMixin]: #updatemodelmixin
|
||||
[DestroyModelMixin]: #destroymodelmixin
|
125
docs/api-guide/pagination.md
Normal file
125
docs/api-guide/pagination.md
Normal file
|
@ -0,0 +1,125 @@
|
|||
<a class="github" href="pagination.py"></a>
|
||||
|
||||
# Pagination
|
||||
|
||||
> Django provides a few classes that help you manage paginated data – that is, data that’s split across several pages, with “Previous/Next” links.
|
||||
>
|
||||
> — [Django documentation][cite]
|
||||
|
||||
REST framework includes a `PaginationSerializer` class that makes it easy to return paginated data in a way that can then be rendered to arbitrary media types.
|
||||
|
||||
## Paginating basic data
|
||||
|
||||
Let's start by taking a look at an example from the Django documentation.
|
||||
|
||||
from django.core.paginator import Paginator
|
||||
objects = ['john', 'paul', 'george', 'ringo']
|
||||
paginator = Paginator(objects, 2)
|
||||
page = paginator.page(1)
|
||||
page.object_list
|
||||
# ['john', 'paul']
|
||||
|
||||
At this point we've got a page object. If we wanted to return this page object as a JSON response, we'd need to provide the client with context such as next and previous links, so that it would be able to page through the remaining results.
|
||||
|
||||
from rest_framework.pagination import PaginationSerializer
|
||||
serializer = PaginationSerializer(instance=page)
|
||||
serializer.data
|
||||
# {'count': 4, 'next': '?page=2', 'previous': None, 'results': [u'john', u'paul']}
|
||||
|
||||
The `context` argument of the `PaginationSerializer` class may optionally include the request. If the request is included in the context then the next and previous links returned by the serializer will use absolute URLs instead of relative URLs.
|
||||
|
||||
request = RequestFactory().get('/foobar')
|
||||
serializer = PaginationSerializer(instance=page, context={'request': request})
|
||||
serializer.data
|
||||
# {'count': 4, 'next': 'http://testserver/foobar?page=2', 'previous': None, 'results': [u'john', u'paul']}
|
||||
|
||||
We could now return that data in a `Response` object, and it would be rendered into the correct media type.
|
||||
|
||||
## Paginating QuerySets
|
||||
|
||||
Our first example worked because we were using primative objects. If we wanted to paginate a queryset or other complex data, we'd need to specify a serializer to use to serialize the result set itself with.
|
||||
|
||||
We can do this using the `object_serializer_class` attribute on the inner `Meta` class of the pagination serializer. For example.
|
||||
|
||||
class UserSerializer(serializers.ModelSerializer):
|
||||
"""
|
||||
Serializes user querysets.
|
||||
"""
|
||||
class Meta:
|
||||
model = User
|
||||
fields = ('username', 'email')
|
||||
|
||||
class PaginatedUserSerializer(pagination.PaginationSerializer):
|
||||
"""
|
||||
Serializes page objects of user querysets.
|
||||
"""
|
||||
class Meta:
|
||||
object_serializer_class = UserSerializer
|
||||
|
||||
We could now use our pagination serializer in a view like this.
|
||||
|
||||
@api_view('GET')
|
||||
def user_list(request):
|
||||
queryset = User.objects.all()
|
||||
paginator = Paginator(queryset, 20)
|
||||
|
||||
page = request.QUERY_PARAMS.get('page')
|
||||
try:
|
||||
users = paginator.page(page)
|
||||
except PageNotAnInteger:
|
||||
# If page is not an integer, deliver first page.
|
||||
users = paginator.page(1)
|
||||
except EmptyPage:
|
||||
# If page is out of range (e.g. 9999), deliver last page of results.
|
||||
users = paginator.page(paginator.num_pages)
|
||||
|
||||
serializer_context = {'request': request}
|
||||
serializer = PaginatedUserSerializer(instance=users,
|
||||
context=serializer_context)
|
||||
return Response(serializer.data)
|
||||
|
||||
## Pagination in the generic views
|
||||
|
||||
The generic class based views `ListAPIView` and `ListCreateAPIView` provide pagination of the returned querysets by default. You can customise this behaviour by altering the pagination style, by modifying the default number of results, or by turning pagination off completely.
|
||||
|
||||
The default pagination style may be set globally, using the `PAGINATION_SERIALIZER` and `PAGINATE_BY` settings. For example.
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
'PAGINATION_SERIALIZER': (
|
||||
'example_app.pagination.CustomPaginationSerializer',
|
||||
),
|
||||
'PAGINATE_BY': 10
|
||||
}
|
||||
|
||||
You can also set the pagination style on a per-view basis, using the `ListAPIView` generic class-based view.
|
||||
|
||||
class PaginatedListView(ListAPIView):
|
||||
model = ExampleModel
|
||||
pagination_serializer_class = CustomPaginationSerializer
|
||||
paginate_by = 10
|
||||
|
||||
For more complex requirements such as serialization that differs depending on the requested media type you can override the `.get_paginate_by()` and `.get_pagination_serializer_class()` methods.
|
||||
|
||||
---
|
||||
|
||||
# Custom pagination serializers
|
||||
|
||||
To create a custom pagination serializer class you should override `pagination.BasePaginationSerializer` and set the fields that you want the serializer to return.
|
||||
|
||||
You can also override the name used for the object list field, by setting the `results_field` attribute, which defaults to `'results'`.
|
||||
|
||||
## Example
|
||||
|
||||
For example, to nest a pair of links labelled 'prev' and 'next', and set the name for the results field to 'objects', you might use something like this.
|
||||
|
||||
class LinksSerializer(serializers.Serializer):
|
||||
next = pagination.NextURLField(source='*')
|
||||
prev = pagination.PreviousURLField(source='*')
|
||||
|
||||
class CustomPaginationSerializer(pagination.BasePaginationSerializer):
|
||||
links = LinksSerializer(source='*') # Takes the page object as the source
|
||||
total_results = serializers.Field(source='paginator.count')
|
||||
|
||||
results_field = 'objects'
|
||||
|
||||
[cite]: https://docs.djangoproject.com/en/dev/topics/pagination/
|
161
docs/api-guide/parsers.md
Normal file
161
docs/api-guide/parsers.md
Normal file
|
@ -0,0 +1,161 @@
|
|||
<a class="github" href="parsers.py"></a>
|
||||
|
||||
# Parsers
|
||||
|
||||
> Machine interacting web services tend to use more
|
||||
structured formats for sending data than form-encoded, since they're
|
||||
sending more complex data than simple forms
|
||||
>
|
||||
> — Malcom Tredinnick, [Django developers group][cite]
|
||||
|
||||
REST framework includes a number of built in Parser classes, that allow you to accept requests with various media types. There is also support for defining your own custom parsers, which gives you the flexibility to design the media types that your API accepts.
|
||||
|
||||
## How the parser is determined
|
||||
|
||||
The set of valid parsers for a view is always defined as a list of classes. When either `request.DATA` or `request.FILES` is accessed, REST framework will examine the `Content-Type` header on the incoming request, and determine which parser to use to parse the request content.
|
||||
|
||||
## Setting the parsers
|
||||
|
||||
The default set of parsers may be set globally, using the `DEFAULT_PARSER_CLASSES` setting. For example, the following settings would allow requests with `YAML` content.
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
'DEFAULT_PARSER_CLASSES': (
|
||||
'rest_framework.parsers.YAMLParser',
|
||||
)
|
||||
}
|
||||
|
||||
You can also set the renderers used for an individual view, using the `APIView` class based views.
|
||||
|
||||
class ExampleView(APIView):
|
||||
"""
|
||||
A view that can accept POST requests with YAML content.
|
||||
"""
|
||||
parser_classes = (YAMLParser,)
|
||||
|
||||
def post(self, request, format=None):
|
||||
return Response({'received data': request.DATA})
|
||||
|
||||
Or, if you're using the `@api_view` decorator with function based views.
|
||||
|
||||
@api_view(['POST'])
|
||||
@parser_classes((YAMLParser,))
|
||||
def example_view(request, format=None):
|
||||
"""
|
||||
A view that can accept POST requests with YAML content.
|
||||
"""
|
||||
return Response({'received data': request.DATA})
|
||||
|
||||
---
|
||||
|
||||
# API Reference
|
||||
|
||||
## JSONParser
|
||||
|
||||
Parses `JSON` request content.
|
||||
|
||||
**.media_type**: `application/json`
|
||||
|
||||
## YAMLParser
|
||||
|
||||
Parses `YAML` request content.
|
||||
|
||||
**.media_type**: `application/yaml`
|
||||
|
||||
## XMLParser
|
||||
|
||||
Parses REST framework's default style of `XML` request content.
|
||||
|
||||
Note that the `XML` markup language is typically used as the base language for more strictly defined domain-specific languages, such as `RSS`, `Atom`, and `XHTML`.
|
||||
|
||||
If you are considering using `XML` for your API, you may want to consider implementing a custom renderer and parser for your specific requirements, and using an existing domain-specific media-type, or creating your own custom XML-based media-type.
|
||||
|
||||
**.media_type**: `application/xml`
|
||||
|
||||
## FormParser
|
||||
|
||||
Parses HTML form content. `request.DATA` will be populated with a `QueryDict` of data, `request.FILES` will be populated with an empty `QueryDict` of data.
|
||||
|
||||
You will typically want to use both `FormParser` and `MultiPartParser` together in order to fully support HTML form data.
|
||||
|
||||
**.media_type**: `application/x-www-form-urlencoded`
|
||||
|
||||
## MultiPartParser
|
||||
|
||||
Parses multipart HTML form content, which supports file uploads. Both `request.DATA` and `request.FILES` will be populated with a `QueryDict`.
|
||||
|
||||
You will typically want to use both `FormParser` and `MultiPartParser` together in order to fully support HTML form data.
|
||||
|
||||
**.media_type**: `multipart/form-data`
|
||||
|
||||
---
|
||||
|
||||
# Custom parsers
|
||||
|
||||
To implement a custom parser, you should override `BaseParser`, set the `.media_type` property, and implement the `.parse(self, stream, media_type, parser_context)` method.
|
||||
|
||||
The method should return the data that will be used to populate the `request.DATA` property.
|
||||
|
||||
The arguments passed to `.parse()` are:
|
||||
|
||||
### stream
|
||||
|
||||
A stream-like object representing the body of the request.
|
||||
|
||||
### media_type
|
||||
|
||||
Optional. If provided, this is the media type of the incoming request content.
|
||||
|
||||
Depending on the request's `Content-Type:` header, this may be more specific than the renderer's `media_type` attribute, and may include media type parameters. For example `"text/plain; charset=utf-8"`.
|
||||
|
||||
### parser_context
|
||||
|
||||
Optional. If supplied, this argument will be a dictionary containing any additional context that may be required to parse the request content.
|
||||
|
||||
By default this will include the following keys: `view`, `request`, `args`, `kwargs`.
|
||||
|
||||
## Example
|
||||
|
||||
The following is an example plaintext parser that will populate the `request.DATA` property with a string representing the body of the request.
|
||||
|
||||
class PlainTextParser(BaseParser):
|
||||
"""
|
||||
Plain text parser.
|
||||
"""
|
||||
|
||||
media_type = 'text/plain'
|
||||
|
||||
def parse(self, stream, media_type=None, parser_context=None):
|
||||
"""
|
||||
Simply return a string representing the body of the request.
|
||||
"""
|
||||
return stream.read()
|
||||
|
||||
## Uploading file content
|
||||
|
||||
If your custom parser needs to support file uploads, you may return a `DataAndFiles` object from the `.parse()` method. `DataAndFiles` should be instantiated with two arguments. The first argument will be used to populate the `request.DATA` property, and the second argument will be used to populate the `request.FILES` property.
|
||||
|
||||
For example:
|
||||
|
||||
class SimpleFileUploadParser(BaseParser):
|
||||
"""
|
||||
A naive raw file upload parser.
|
||||
"""
|
||||
|
||||
def parse(self, stream, media_type=None, parser_context=None):
|
||||
content = stream.read()
|
||||
name = 'example.dat'
|
||||
content_type = 'application/octet-stream'
|
||||
size = len(content)
|
||||
charset = 'utf-8'
|
||||
|
||||
# Write a temporary file based on the request content
|
||||
temp = tempfile.NamedTemporaryFile(delete=False)
|
||||
temp.write(content)
|
||||
uploaded = UploadedFile(temp, name, content_type, size, charset)
|
||||
|
||||
# Return the uploaded file
|
||||
data = {}
|
||||
files = {name: uploaded}
|
||||
return DataAndFiles(data, files)
|
||||
|
||||
[cite]: https://groups.google.com/d/topic/django-developers/dxI4qVzrBY4/discussion
|
118
docs/api-guide/permissions.md
Normal file
118
docs/api-guide/permissions.md
Normal file
|
@ -0,0 +1,118 @@
|
|||
<a class="github" href="permissions.py"></a>
|
||||
|
||||
# Permissions
|
||||
|
||||
> Authentication or identification by itself is not usually sufficient to gain access to information or code. For that, the entity requesting access must have authorization.
|
||||
>
|
||||
> — [Apple Developer Documentation][cite]
|
||||
|
||||
Together with [authentication] and [throttling], permissions determine whether a request should be granted or denied access.
|
||||
|
||||
Permission checks are always run at the very start of the view, before any other code is allowed to proceed. Permission checks will typically use the authentication information in the `request.user` and `request.auth` properties to determine if the incoming request should be permitted.
|
||||
|
||||
## How permissions are determined
|
||||
|
||||
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` exception will be raised, and the main body of the view will not run.
|
||||
|
||||
## Object level permissions
|
||||
|
||||
REST framework permissions also support object-level permissioning. Object level permissions are used to determine if a user should be allowed to act on a particular object, which will typically be a model instance.
|
||||
|
||||
Object level permissions are run by REST framework's generic views when `.get_object()` is called. As with view level permissions, an `exceptions.PermissionDenied` exception will be raised if the user is not allowed to act on the given object.
|
||||
|
||||
## Setting the permission policy
|
||||
|
||||
The default permission policy may be set globally, using the `DEFAULT_PERMISSION_CLASSES` setting. For example.
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
'DEFAULT_PERMISSION_CLASSES': (
|
||||
'rest_framework.permissions.IsAuthenticated',
|
||||
)
|
||||
}
|
||||
|
||||
If not specified, this setting defaults to allowing unrestricted access:
|
||||
|
||||
'DEFAULT_PERMISSION_CLASSES': (
|
||||
'rest_framework.permissions.AllowAny',
|
||||
)
|
||||
|
||||
You can also set the authentication policy on a per-view basis, using the `APIView` class based views.
|
||||
|
||||
class ExampleView(APIView):
|
||||
permission_classes = (IsAuthenticated,)
|
||||
|
||||
def get(self, request, format=None):
|
||||
content = {
|
||||
'status': 'request was permitted'
|
||||
}
|
||||
return Response(content)
|
||||
|
||||
Or, if you're using the `@api_view` decorator with function based views.
|
||||
|
||||
@api_view('GET')
|
||||
@permission_classes(IsAuthenticated)
|
||||
def example_view(request, format=None):
|
||||
content = {
|
||||
'status': 'request was permitted'
|
||||
}
|
||||
return Response(content)
|
||||
|
||||
---
|
||||
|
||||
# API Reference
|
||||
|
||||
## AllowAny
|
||||
|
||||
The `AllowAny` permission class will allow unrestricted access, **regardless of if the request was authenticated or unauthenticated**.
|
||||
|
||||
This permission is not strictly required, since you can achieve the same result by using an empty list or tuple for the permissions setting, but you may find it useful to specify this class because it makes the intention explicit.
|
||||
|
||||
## IsAuthenticated
|
||||
|
||||
The `IsAuthenticated` permission class will deny permission to any unauthenticated user, and allow permission otherwise.
|
||||
|
||||
This permission is suitable if you want your API to only be accessible to registered users.
|
||||
|
||||
## IsAdminUser
|
||||
|
||||
The `IsAdminUser` permission class will deny permission to any user, unless `user.is_staff` is `True` in which case permission will be allowed.
|
||||
|
||||
This permission is suitable is you want your API to only be accessible to a subset of trusted administrators.
|
||||
|
||||
## IsAuthenticatedOrReadOnly
|
||||
|
||||
The `IsAuthenticatedOrReadOnly` will allow authenticated users to perform any request. Requests for unauthorised users will only be permitted if the request method is one of the "safe" methods; `GET`, `HEAD` or `OPTIONS`.
|
||||
|
||||
This permission is suitable if you want to your API to allow read permissions to anonymous users, and only allow write permissions to authenticated users.
|
||||
|
||||
## DjangoModelPermissions
|
||||
|
||||
This permission class ties into Django's standard `django.contrib.auth` [model permissions][contribauth]. When applied to a view that has a `.model` property, authorization will only be granted if the user has the relevant model permissions assigned.
|
||||
|
||||
* `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.
|
||||
|
||||
To use custom model permissions, override `DjangoModelPermissions` and set the `.perms_map` property. Refer to the source code for details.
|
||||
|
||||
The `DjangoModelPermissions` class also supports object-level permissions. Third-party authorization backends such as [django-guardian][guardian] that provide object-level permissions should work just fine with `DjangoModelPermissions` without any custom configuration required.
|
||||
|
||||
---
|
||||
|
||||
# Custom permissions
|
||||
|
||||
To implement a custom permission, override `BasePermission` and implement the `.has_permission(self, request, view, obj=None)` method.
|
||||
|
||||
The method should return `True` if the request should be granted access, and `False` otherwise.
|
||||
|
||||
|
||||
[cite]: https://developer.apple.com/library/mac/#documentation/security/Conceptual/AuthenticationAndAuthorizationGuide/Authorization/Authorization.html
|
||||
[authentication]: authentication.md
|
||||
[throttling]: throttling.md
|
||||
[contribauth]: https://docs.djangoproject.com/en/1.0/topics/auth/#permissions
|
||||
[guardian]: https://github.com/lukaszb/django-guardian
|
267
docs/api-guide/renderers.md
Normal file
267
docs/api-guide/renderers.md
Normal file
|
@ -0,0 +1,267 @@
|
|||
<a class="github" href="renderers.py"></a>
|
||||
|
||||
# Renderers
|
||||
|
||||
> Before a TemplateResponse instance can be returned to the client, it must be rendered. The rendering process takes the intermediate representation of template and context, and turns it into the final byte stream that can be served to the client.
|
||||
>
|
||||
> — [Django documentation][cite]
|
||||
|
||||
REST framework includes a number of built in Renderer classes, that allow you to return responses with various media types. There is also support for defining your own custom renderers, which gives you the flexibility to design your own media types.
|
||||
|
||||
## How the renderer is determined
|
||||
|
||||
The set of valid renderers for a view is always defined as a list of classes. When a view is entered REST framework will perform content negotiation on the incoming request, and determine the most appropriate renderer to satisfy the request.
|
||||
|
||||
The basic process of content negotiation involves examining the request's `Accept` header, to determine which media types it expects in the response. Optionally, format suffixes on the URL may be used to explicitly request a particular representation. For example the URL `http://example.com/api/users_count.json` might be an endpoint that always returns JSON data.
|
||||
|
||||
For more information see the documentation on [content negotation][conneg].
|
||||
|
||||
## Setting the renderers
|
||||
|
||||
The default set of renderers may be set globally, using the `DEFAULT_RENDERER_CLASSES` setting. For example, the following settings would use `YAML` as the main media type and also include the self describing API.
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
'DEFAULT_RENDERER_CLASSES': (
|
||||
'rest_framework.renderers.YAMLRenderer',
|
||||
'rest_framework.renderers.BrowsableAPIRenderer',
|
||||
)
|
||||
}
|
||||
|
||||
You can also set the renderers used for an individual view, using the `APIView` class based views.
|
||||
|
||||
class UserCountView(APIView):
|
||||
"""
|
||||
A view that returns the count of active users, in JSON or JSONp.
|
||||
"""
|
||||
renderer_classes = (JSONRenderer, JSONPRenderer)
|
||||
|
||||
def get(self, request, format=None):
|
||||
user_count = User.objects.filter(active=True).count()
|
||||
content = {'user_count': user_count}
|
||||
return Response(content)
|
||||
|
||||
Or, if you're using the `@api_view` decorator with function based views.
|
||||
|
||||
@api_view(['GET'])
|
||||
@renderer_classes((JSONRenderer, JSONPRenderer))
|
||||
def user_count_view(request, format=None):
|
||||
"""
|
||||
A view that returns the count of active users, in JSON or JSONp.
|
||||
"""
|
||||
user_count = User.objects.filter(active=True).count()
|
||||
content = {'user_count': user_count}
|
||||
return Response(content)
|
||||
|
||||
## Ordering of renderer classes
|
||||
|
||||
It's important when specifying the renderer classes for your API to think about what priority you want to assign to each media type. If a client underspecifies the representations it can accept, such as sending an `Accept: */*` header, or not including an `Accept` header at all, then REST framework will select the first renderer in the list to use for the response.
|
||||
|
||||
For example if your API serves JSON responses and the HTML browseable API, you might want to make `JSONRenderer` your default renderer, in order to send `JSON` responses to clients that do not specify an `Accept` header.
|
||||
|
||||
If your API includes views that can serve both regular webpages and API responses depending on the request, then you might consider making `TemplateHTMLRenderer` your default renderer, in order to play nicely with older browsers that send [broken accept headers][browser-accept-headers].
|
||||
|
||||
---
|
||||
|
||||
# API Reference
|
||||
|
||||
## JSONRenderer
|
||||
|
||||
Renders the request data into `JSON`.
|
||||
|
||||
The client may additionally include an `'indent'` media type parameter, in which case the returned `JSON` will be indented. For example `Accept: application/json; indent=4`.
|
||||
|
||||
**.media_type**: `application/json`
|
||||
|
||||
**.format**: `'.json'`
|
||||
|
||||
## JSONPRenderer
|
||||
|
||||
Renders the request data into `JSONP`. The `JSONP` media type provides a mechanism of allowing cross-domain AJAX requests, by wrapping a `JSON` response in a javascript callback.
|
||||
|
||||
The javascript callback function must be set by the client including a `callback` URL query parameter. For example `http://example.com/api/users?callback=jsonpCallback`. If the callback function is not explicitly set by the client it will default to `'callback'`.
|
||||
|
||||
**Note**: If you require cross-domain AJAX requests, you may also want to consider using [CORS] as an alternative to `JSONP`.
|
||||
|
||||
**.media_type**: `application/javascript`
|
||||
|
||||
**.format**: `'.jsonp'`
|
||||
|
||||
## YAMLRenderer
|
||||
|
||||
Renders the request data into `YAML`.
|
||||
|
||||
**.media_type**: `application/yaml`
|
||||
|
||||
**.format**: `'.yaml'`
|
||||
|
||||
## XMLRenderer
|
||||
|
||||
Renders REST framework's default style of `XML` response content.
|
||||
|
||||
Note that the `XML` markup language is used typically used as the base language for more strictly defined domain-specific languages, such as `RSS`, `Atom`, and `XHTML`.
|
||||
|
||||
If you are considering using `XML` for your API, you may want to consider implementing a custom renderer and parser for your specific requirements, and using an existing domain-specific media-type, or creating your own custom XML-based media-type.
|
||||
|
||||
**.media_type**: `application/xml`
|
||||
|
||||
**.format**: `'.xml'`
|
||||
|
||||
## TemplateHTMLRenderer
|
||||
|
||||
Renders data to HTML, using Django's standard template rendering.
|
||||
Unlike other renderers, the data passed to the `Response` does not need to be serialized. Also, unlike other renderers, you may want to include a `template_name` argument when creating the `Response`.
|
||||
|
||||
The TemplateHTMLRenderer will create a `RequestContext`, using the `response.data` as the context dict, and determine a template name to use to render the context.
|
||||
|
||||
The template name is determined by (in order of preference):
|
||||
|
||||
1. An explicit `.template_name` attribute set on the response.
|
||||
2. An explicit `.template_name` attribute set on this class.
|
||||
3. The return result of calling `view.get_template_names()`.
|
||||
|
||||
An example of a view that uses `TemplateHTMLRenderer`:
|
||||
|
||||
class UserInstance(generics.RetrieveUserAPIView):
|
||||
"""
|
||||
A view that returns a templated HTML representations of a given user.
|
||||
"""
|
||||
model = Users
|
||||
renderer_classes = (TemplateHTMLRenderer,)
|
||||
|
||||
def get(self, request, *args, **kwargs)
|
||||
self.object = self.get_object()
|
||||
return Response({'user': self.object}, template_name='user_detail.html')
|
||||
|
||||
You can use `TemplateHTMLRenderer` either to return regular HTML pages using REST framework, or to return both HTML and API responses from a single endpoint.
|
||||
|
||||
If you're building websites that use `TemplateHTMLRenderer` along with other renderer classes, you should consider listing `TemplateHTMLRenderer` as the first class in the `renderer_classes` list, so that it will be prioritised first even for browsers that send poorly formed `ACCEPT:` headers.
|
||||
|
||||
**.media_type**: `text/html`
|
||||
|
||||
**.format**: `'.html'`
|
||||
|
||||
See also: `StaticHTMLRenderer`
|
||||
|
||||
## StaticHTMLRenderer
|
||||
|
||||
A simple renderer that simply returns pre-rendered HTML. Unlike other renderers, the data passed to the response object should be a string representing the content to be returned.
|
||||
|
||||
An example of a view that uses `TemplateHTMLRenderer`:
|
||||
|
||||
@api_view(('GET',))
|
||||
@renderer_classes((StaticHTMLRenderer,))
|
||||
def simple_html_view(request):
|
||||
data = '<html><body><h1>Hello, world</h1></body></html>'
|
||||
return Response(data)
|
||||
|
||||
You can use `TemplateHTMLRenderer` either to return regular HTML pages using REST framework, or to return both HTML and API responses from a single endpoint.
|
||||
|
||||
**.media_type**: `text/html`
|
||||
|
||||
**.format**: `'.html'`
|
||||
|
||||
See also: `TemplateHTMLRenderer`
|
||||
|
||||
## BrowsableAPIRenderer
|
||||
|
||||
Renders data into HTML for the Browseable API. This renderer will determine which other renderer would have been given highest priority, and use that to display an API style response within the HTML page.
|
||||
|
||||
**.media_type**: `text/html`
|
||||
|
||||
**.format**: `'.api'`
|
||||
|
||||
---
|
||||
|
||||
# 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.
|
||||
|
||||
The arguments passed to the `.render()` method are:
|
||||
|
||||
### `data`
|
||||
|
||||
The request data, as set by the `Response()` instantiation.
|
||||
|
||||
### `media_type=None`
|
||||
|
||||
Optional. If provided, this is the accepted media type, as determined by the content negotiation stage.
|
||||
|
||||
Depending on the client's `Accept:` header, this may be more specific than the renderer's `media_type` attribute, and may include media type parameters. For example `"application/json; nested=true"`.
|
||||
|
||||
### `renderer_context=None`
|
||||
|
||||
Optional. If provided, this is a dictionary of contextual information provided by the view.
|
||||
|
||||
By default this will include the following keys: `view`, `request`, `response`, `args`, `kwargs`.
|
||||
|
||||
## Example
|
||||
|
||||
The following is an example plaintext renderer that will return a response with the `data` parameter as the content of the response.
|
||||
|
||||
from django.utils.encoding import smart_unicode
|
||||
from rest_framework import renderers
|
||||
|
||||
|
||||
class PlainText(renderers.BaseRenderer):
|
||||
media_type = 'text/plain'
|
||||
format = 'txt'
|
||||
|
||||
def render(self, data, media_type=None, renderer_context=None):
|
||||
if isinstance(data, basestring):
|
||||
return data
|
||||
return smart_unicode(data)
|
||||
|
||||
---
|
||||
|
||||
# Advanced renderer usage
|
||||
|
||||
You can do some pretty flexible things using REST framework's renderers. Some examples...
|
||||
|
||||
* Provide either flat or nested representations from the same endpoint, depending on the requested media type.
|
||||
* Serve both regular HTML webpages, and JSON based API responses from the same endpoints.
|
||||
* 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
|
||||
|
||||
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.
|
||||
|
||||
For example:
|
||||
|
||||
@api_view(('GET',))
|
||||
@renderer_classes((TemplateHTMLRenderer, JSONRenderer))
|
||||
def list_users(request):
|
||||
"""
|
||||
A view that can return JSON or HTML representations
|
||||
of the users in the system.
|
||||
"""
|
||||
queryset = Users.objects.filter(active=True)
|
||||
|
||||
if request.accepted_renderer.format == 'html':
|
||||
# TemplateHTMLRenderer takes a context dict,
|
||||
# and additionally requires a 'template_name'.
|
||||
# It does not require serialization.
|
||||
data = {'users': queryset}
|
||||
return Response(data, template_name='list_users.html')
|
||||
|
||||
# JSONRenderer requires serialized data as normal.
|
||||
serializer = UserSerializer(instance=queryset)
|
||||
data = serializer.data
|
||||
return Response(data)
|
||||
|
||||
## Designing your media types
|
||||
|
||||
For the purposes of many Web APIs, simple `JSON` responses with hyperlinked relations may be sufficient. If you want to fully embrace RESTful design and [HATEOAS] you'll need to consider the design and usage of your media types in more detail.
|
||||
|
||||
In [the words of Roy Fielding][quote], "A REST API should spend almost all of its descriptive effort in defining the media type(s) used for representing resources and driving application state, or in defining extended relation names and/or hypertext-enabled mark-up for existing standard media types.".
|
||||
|
||||
For good examples of custom media types, see GitHub's use of a custom [application/vnd.github+json] media type, and Mike Amundsen's IANA approved [application/vnd.collection+json] JSON-based hypermedia.
|
||||
|
||||
[cite]: https://docs.djangoproject.com/en/dev/ref/template-response/#the-rendering-process
|
||||
[conneg]: content-negotiation.md
|
||||
[browser-accept-headers]: http://www.gethifi.com/blog/browser-rest-http-accept-headers
|
||||
[CORS]: http://en.wikipedia.org/wiki/Cross-origin_resource_sharing
|
||||
[HATEOAS]: http://timelessrepo.com/haters-gonna-hateoas
|
||||
[quote]: http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven
|
||||
[application/vnd.github+json]: http://developer.github.com/v3/media/
|
||||
[application/vnd.collection+json]: http://www.amundsen.com/media-types/collection/
|
128
docs/api-guide/requests.md
Normal file
128
docs/api-guide/requests.md
Normal file
|
@ -0,0 +1,128 @@
|
|||
<a class="github" href="request.py"></a>
|
||||
|
||||
# Requests
|
||||
|
||||
> If you're doing REST-based web service stuff ... you should ignore request.POST.
|
||||
>
|
||||
> — Malcom Tredinnick, [Django developers group][cite]
|
||||
|
||||
REST framework's `Request` class extends the standard `HttpRequest`, adding support for REST framework's flexible request parsing and request authentication.
|
||||
|
||||
---
|
||||
|
||||
# Request parsing
|
||||
|
||||
REST framework's Request objects provide flexible request parsing that allows you to treat requests with JSON data or other media types in the same way that you would normally deal with form data.
|
||||
|
||||
## .DATA
|
||||
|
||||
`request.DATA` returns the parsed content of the request body. This is similar to the standard `request.POST` attribute except that:
|
||||
|
||||
* It supports parsing the content of HTTP methods other than `POST`, meaning that you can access the content of `PUT` and `PATCH` requests.
|
||||
* It supports REST framework's flexible request parsing, rather than just supporting form data. For example you can handle incoming JSON data in the same way that you handle incoming form data.
|
||||
|
||||
For more details see the [parsers documentation].
|
||||
|
||||
## .FILES
|
||||
|
||||
`request.FILES` returns any uploaded files that may be present in the content of the request body. This is the same as the standard `HttpRequest` behavior, except that the same flexible request parsing is used for `request.DATA`.
|
||||
|
||||
For more details see the [parsers documentation].
|
||||
|
||||
## .QUERY_PARAMS
|
||||
|
||||
`request.QUERY_PARAMS` is a more correctly named synonym for `request.GET`.
|
||||
|
||||
For clarity inside your code, we recommend using `request.QUERY_PARAMS` instead of the usual `request.GET`, as *any* HTTP method type may include query parameters.
|
||||
|
||||
## .parsers
|
||||
|
||||
The `APIView` class or `@api_view` decorator will ensure that this property is automatically set to a list of `Parser` instances, based on the `parser_classes` set on the view or based on the `DEFAULT_PARSER_CLASSES` setting.
|
||||
|
||||
You won't typically need to access this property.
|
||||
|
||||
---
|
||||
|
||||
**Note:** If a client sends malformed content, then accessing `request.DATA` or `request.FILES` may raise a `ParseError`. By default REST framework's `APIView` class or `@api_view` decorator will catch the error and return a `400 Bad Request` response.
|
||||
|
||||
If a client sends a request with a content-type that cannot be parsed then a `UnsupportedMediaType` exception will be raised, which by default will be caught and return a `415 Unsupported Media Type` response.
|
||||
|
||||
---
|
||||
|
||||
# Authentication
|
||||
|
||||
REST framework provides flexible, per-request authentication, that gives you the ability to:
|
||||
|
||||
* Use different authentication policies for different parts of your API.
|
||||
* Support the use of multiple authentication policies.
|
||||
* Provide both user and token information associated with the incoming request.
|
||||
|
||||
## .user
|
||||
|
||||
`request.user` typically returns an instance of `django.contrib.auth.models.User`, although the behavior depends on the authentication policy being used.
|
||||
|
||||
If the request is unauthenticated the default value of `request.user` is an instance of `django.contrib.auth.models.AnonymousUser`.
|
||||
|
||||
For more details see the [authentication documentation].
|
||||
|
||||
## .auth
|
||||
|
||||
`request.auth` returns any additional authentication context. The exact behavior of `request.auth` depends on the authentication policy being used, but it may typically be an instance of the token that the request was authenticated against.
|
||||
|
||||
If the request is unauthenticated, or if no additional context is present, the default value of `request.auth` is `None`.
|
||||
|
||||
For more details see the [authentication documentation].
|
||||
|
||||
## .authenticators
|
||||
|
||||
The `APIView` class or `@api_view` decorator will ensure that this property is automatically set to a list of `Authentication` instances, based on the `authentication_classes` set on the view or based on the `DEFAULT_AUTHENTICATORS` setting.
|
||||
|
||||
You won't typically need to access this property.
|
||||
|
||||
---
|
||||
|
||||
# Browser enhancements
|
||||
|
||||
REST framework supports a few browser enhancements such as browser-based `PUT` and `DELETE` forms.
|
||||
|
||||
## .method
|
||||
|
||||
`request.method` returns the **uppercased** string representation of the request's HTTP method.
|
||||
|
||||
Browser-based `PUT` and `DELETE` forms are transparently supported.
|
||||
|
||||
For more information see the [browser enhancements documentation].
|
||||
|
||||
## .content_type
|
||||
|
||||
`request.content_type`, returns a string object representing the media type of the HTTP request's body, or an empty string if no media type was provided.
|
||||
|
||||
You won't typically need to directly access the request's content type, as you'll normally rely on REST framework's default request parsing behavior.
|
||||
|
||||
If you do need to access the content type of the request you should use the `.content_type` property in preference to using `request.META.get('HTTP_CONTENT_TYPE')`, as it provides transparent support for browser-based non-form content.
|
||||
|
||||
For more information see the [browser enhancements documentation].
|
||||
|
||||
## .stream
|
||||
|
||||
`request.stream` returns a stream representing the content of the request body.
|
||||
|
||||
You won't typically need to directly access the request's content, as you'll normally rely on REST framework's default request parsing behavior.
|
||||
|
||||
If you do need to access the raw content directly, you should use the `.stream` property in preference to using `request.content`, as it provides transparent support for browser-based non-form content.
|
||||
|
||||
For more information see the [browser enhancements documentation].
|
||||
|
||||
---
|
||||
|
||||
# Standard HttpRequest attributes
|
||||
|
||||
As REST framework's `Request` extends Django's `HttpRequest`, all the other standard attributes and methods are also available. For example the `request.META` dictionary is available as normal.
|
||||
|
||||
Note that due to implementation reasons the `Request` class does not inherit from `HttpRequest` class, but instead extends the class using composition.
|
||||
|
||||
|
||||
[cite]: https://groups.google.com/d/topic/django-developers/dxI4qVzrBY4/discussion
|
||||
[parsers documentation]: parsers.md
|
||||
[authentication documentation]: authentication.md
|
||||
[browser enhancements documentation]: ../topics/browser-enhancements.md
|
94
docs/api-guide/responses.md
Normal file
94
docs/api-guide/responses.md
Normal file
|
@ -0,0 +1,94 @@
|
|||
<a class="github" href="response.py"></a>
|
||||
|
||||
# Responses
|
||||
|
||||
> Unlike basic HttpResponse objects, TemplateResponse objects retain the details of the context that was provided by the view to compute the response. The final output of the response is not computed until it is needed, later in the response process.
|
||||
>
|
||||
> — [Django documentation][cite]
|
||||
|
||||
REST framework supports HTTP content negotiation by providing a `Response` class which allows you to return content that can be rendered into multiple content types, depending on the client request.
|
||||
|
||||
The `Response` class subclasses Django's `SimpleTemplateResponse`. `Response` objects are initialised with data, which should consist of native python primatives. REST framework then uses standard HTTP content negotiation to determine how it should render the final response content.
|
||||
|
||||
There's no requirement for you to use the `Response` class, you can also return regular `HttpResponse` objects from your views if you want, but it provides a nicer interface for returning Web API responses.
|
||||
|
||||
Unless you want to heavily customize REST framework for some reason, you should always use an `APIView` class or `@api_view` function for views that return `Response` objects. Doing so ensures that the view can perform content negotiation and select the appropriate renderer for the response, before it is returned from the view.
|
||||
|
||||
---
|
||||
|
||||
# Creating responses
|
||||
|
||||
## Response()
|
||||
|
||||
**Signature:** `Response(data, status=None, template_name=None, headers=None)`
|
||||
|
||||
Unlike regular `HttpResponse` objects, you do not instantiate `Response` objects with rendered content. Instead you pass in unrendered data, which may consist of any python primatives.
|
||||
|
||||
The renderers used by the `Response` class cannot natively handle complex datatypes such as Django model instances, so you need to serialize the data into primative datatypes before creating the `Response` object.
|
||||
|
||||
You can use REST framework's `Serializer` classes to perform this data serialization, or use your own custom serialization.
|
||||
|
||||
Arguments:
|
||||
|
||||
* `data`: The serialized data for the response.
|
||||
* `status`: A status code for the response. Defaults to 200. See also [status codes][statuscodes].
|
||||
* `template_name`: A template name to use if `HTMLRenderer` is selected.
|
||||
* `headers`: A dictionary of HTTP headers to use in the response.
|
||||
|
||||
---
|
||||
|
||||
# Attributes
|
||||
|
||||
## .data
|
||||
|
||||
The unrendered content of a `Request` object.
|
||||
|
||||
## .status_code
|
||||
|
||||
The numeric status code of the HTTP response.
|
||||
|
||||
## .content
|
||||
|
||||
The rendered content of the response. The `.render()` method must have been called before `.content` can be accessed.
|
||||
|
||||
## .template_name
|
||||
|
||||
The `template_name`, if supplied. Only required if `HTMLRenderer` or some other custom template renderer is the accepted renderer for the reponse.
|
||||
|
||||
## .accepted_renderer
|
||||
|
||||
The renderer instance that will be used to render the response.
|
||||
|
||||
Set automatically by the `APIView` or `@api_view` immediately before the response is returned from the view.
|
||||
|
||||
## .accepted_media_type
|
||||
|
||||
The media type that was selected by the content negotiation stage.
|
||||
|
||||
Set automatically by the `APIView` or `@api_view` immediately before the response is returned from the view.
|
||||
|
||||
## .renderer_context
|
||||
|
||||
A dictionary of additional context information that will be passed to the renderer's `.render()` method.
|
||||
|
||||
Set automatically by the `APIView` or `@api_view` immediately before the response is returned from the view.
|
||||
|
||||
---
|
||||
|
||||
# Standard HttpResponse attributes
|
||||
|
||||
The `Response` class extends `SimpleTemplateResponse`, and all the usual attributes and methods are also available on the response. For example you can set headers on the response in the standard way:
|
||||
|
||||
response = Response()
|
||||
response['Cache-Control'] = 'no-cache'
|
||||
|
||||
## .render()
|
||||
|
||||
**Signature:** `.render()`
|
||||
|
||||
As with any other `TemplateResponse`, this method is called to render the serialized data of the response into the final response content. When `.render()` is called, the response content will be set to the result of calling the `.render(data, accepted_media_type, renderer_context)` method on the `accepted_renderer` instance.
|
||||
|
||||
You won't typically need to call `.render()` yourself, as it's handled by Django's standard response cycle.
|
||||
|
||||
[cite]: https://docs.djangoproject.com/en/dev/ref/template-response/
|
||||
[statuscodes]: status-codes.md
|
55
docs/api-guide/reverse.md
Normal file
55
docs/api-guide/reverse.md
Normal file
|
@ -0,0 +1,55 @@
|
|||
<a class="github" href="reverse.py"></a>
|
||||
|
||||
# Returning URLs
|
||||
|
||||
> The central feature that distinguishes the REST architectural style from other network-based styles is its emphasis on a uniform interface between components.
|
||||
>
|
||||
> — Roy Fielding, [Architectural Styles and the Design of Network-based Software Architectures][cite]
|
||||
|
||||
As a rule, it's probably better practice to return absolute URIs from your Web APIs, such as `http://example.com/foobar`, rather than returning relative URIs, such as `/foobar`.
|
||||
|
||||
The advantages of doing so are:
|
||||
|
||||
* It's more explicit.
|
||||
* It leaves less work for your API clients.
|
||||
* There's no ambiguity about the meaning of the string when it's found in representations such as JSON that do not have a native URI type.
|
||||
* It makes it easy to do things like markup HTML representations with hyperlinks.
|
||||
|
||||
REST framework provides two utility functions to make it more simple to return absolute URIs from your Web API.
|
||||
|
||||
There's no requirement for you to use them, but if you do then the self-describing API will be able to automatically hyperlink it's output for you, which makes browsing the API much easier.
|
||||
|
||||
## reverse
|
||||
|
||||
**Signature:** `reverse(viewname, *args, **kwargs)`
|
||||
|
||||
Has the same behavior as [`django.core.urlresolvers.reverse`][reverse], except that it returns a fully qualified URL, using the request to determine the host and port.
|
||||
|
||||
You should **include the request as a keyword argument** to the function, for example:
|
||||
|
||||
import datetime
|
||||
from rest_framework.reverse import reverse
|
||||
from rest_framework.views import APIView
|
||||
|
||||
class APIRootView(APIView):
|
||||
def get(self, request):
|
||||
year = datetime.datetime.now().year
|
||||
data = {
|
||||
...
|
||||
'year-summary-url': reverse('year-summary', args=[year], request=request)
|
||||
}
|
||||
return Response(data)
|
||||
|
||||
## reverse_lazy
|
||||
|
||||
**Signature:** `reverse_lazy(viewname, *args, **kwargs)`
|
||||
|
||||
Has the same behavior as [`django.core.urlresolvers.reverse_lazy`][reverse-lazy], except that it returns a fully qualified URL, using the request to determine the host and port.
|
||||
|
||||
As with the `reverse` function, you should **include the request as a keyword argument** to the function, for example:
|
||||
|
||||
api_root = reverse_lazy('api-root', request=request)
|
||||
|
||||
[cite]: http://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm#sec_5_1_5
|
||||
[reverse]: https://docs.djangoproject.com/en/dev/topics/http/urls/#reverse
|
||||
[reverse-lazy]: https://docs.djangoproject.com/en/dev/topics/http/urls/#reverse-lazy
|
276
docs/api-guide/serializers.md
Normal file
276
docs/api-guide/serializers.md
Normal file
|
@ -0,0 +1,276 @@
|
|||
<a class="github" href="serializers.py"></a>
|
||||
|
||||
# Serializers
|
||||
|
||||
> Expanding the usefulness of the serializers is something that we would
|
||||
like to address. However, it's not a trivial problem, and it
|
||||
will take some serious design work. Any offers to help out in this
|
||||
area would be gratefully accepted.
|
||||
>
|
||||
> — Russell Keith-Magee, [Django users group][cite]
|
||||
|
||||
Serializers allow complex data such as querysets and model instances to be converted to native python datatypes that can then be easily rendered into `JSON`, `XML` or other content types. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.
|
||||
|
||||
REST framework's serializers work very similarly to Django's `Form` and `ModelForm` classes. It provides a `Serializer` class which gives you a powerful, generic way to control the output of your responses, as well as a `ModelSerializer` class which provides a useful shortcut for creating serializers that deal with model instances and querysets.
|
||||
|
||||
## Declaring Serializers
|
||||
|
||||
Let's start by creating a simple object we can use for example purposes:
|
||||
|
||||
class Comment(object):
|
||||
def __init__(self, email, content, created=None):
|
||||
self.email = email
|
||||
self.content = content
|
||||
self.created = created or datetime.datetime.now()
|
||||
|
||||
comment = Comment(email='leila@example.com', content='foo bar')
|
||||
|
||||
We'll declare a serializer that we can use to serialize and deserialize `Comment` objects.
|
||||
Declaring a serializer looks very similar to declaring a form:
|
||||
|
||||
class CommentSerializer(serializers.Serializer):
|
||||
email = serializers.EmailField()
|
||||
content = serializers.CharField(max_length=200)
|
||||
created = serializers.DateTimeField()
|
||||
|
||||
def restore_object(self, attrs, instance=None):
|
||||
if instance:
|
||||
instance.title = attrs['title']
|
||||
instance.content = attrs['content']
|
||||
instance.created = attrs['created']
|
||||
return instance
|
||||
return Comment(**attrs)
|
||||
|
||||
The first part of serializer class defines the fields that get serialized/deserialized. The `restore_object` method defines how fully fledged instances get created when deserializing data. The `restore_object` method is optional, and is only required if we want our serializer to support deserialization.
|
||||
|
||||
## Serializing objects
|
||||
|
||||
We can now use `CommentSerializer` to serialize a comment, or list of comments. Again, using the `Serializer` class looks a lot like using a `Form` class.
|
||||
|
||||
serializer = CommentSerializer(instance=comment)
|
||||
serializer.data
|
||||
# {'email': u'leila@example.com', 'content': u'foo bar', 'created': datetime.datetime(2012, 8, 22, 16, 20, 9, 822774)}
|
||||
|
||||
At this point we've translated the model instance into python native datatypes. To finalise the serialization process we render the data into `json`.
|
||||
|
||||
stream = JSONRenderer().render(data)
|
||||
stream
|
||||
# '{"email": "leila@example.com", "content": "foo bar", "created": "2012-08-22T16:20:09.822"}'
|
||||
|
||||
## Deserializing objects
|
||||
|
||||
Deserialization is similar. First we parse a stream into python native datatypes...
|
||||
|
||||
data = JSONParser().parse(stream)
|
||||
|
||||
...then we restore those native datatypes into a fully populated object instance.
|
||||
|
||||
serializer = CommentSerializer(data)
|
||||
serializer.is_valid()
|
||||
# True
|
||||
serializer.object
|
||||
# <Comment object at 0x10633b2d0>
|
||||
>>> serializer.deserialize('json', stream)
|
||||
|
||||
## Validation
|
||||
|
||||
When deserializing data, you always need to call `is_valid()` before attempting to access the deserialized object. If any validation errors occur, the `.errors` and `.non_field_errors` properties will contain the resulting error messages.
|
||||
|
||||
### Field-level validation
|
||||
|
||||
You can specify custom field-level validation by adding `validate_<fieldname>()` methods to your `Serializer` subclass. These are analagous to `clean_<fieldname>` methods on Django forms, but accept slightly different arguments. They take a dictionary of deserialized attributes as a first argument, and the field name in that dictionary as a second argument (which will be either the name of the field or the value of the `source` argument to the field, if one was provided). Your `validate_<fieldname>` methods should either just return the attrs dictionary or raise a `ValidationError`. For example:
|
||||
|
||||
from rest_framework import serializers
|
||||
|
||||
class BlogPostSerializer(serializers.Serializer):
|
||||
title = serializers.CharField(max_length=100)
|
||||
content = serializers.CharField()
|
||||
|
||||
def validate_title(self, attrs, source):
|
||||
"""
|
||||
Check that the blog post is about Django
|
||||
"""
|
||||
value = attrs[source]
|
||||
if "Django" not in value:
|
||||
raise serializers.ValidationError("Blog post is not about Django")
|
||||
return attrs
|
||||
|
||||
### Final cross-field validation
|
||||
|
||||
To do any other validation that requires access to multiple fields, add a method called `validate` to your `Serializer` subclass. This method takes a single argument, which is the `attrs` dictionary. It should raise a `ValidationError` if necessary, or just return `attrs`.
|
||||
|
||||
## Dealing with nested objects
|
||||
|
||||
The previous example is fine for dealing with objects that only have simple datatypes, but sometimes we also need to be able to represent more complex objects,
|
||||
where some of the attributes of an object might not be simple datatypes such as strings, dates or integers.
|
||||
|
||||
The `Serializer` class is itself a type of `Field`, and can be used to represent relationships where one object type is nested inside another.
|
||||
|
||||
class UserSerializer(serializers.Serializer):
|
||||
email = serializers.Field()
|
||||
username = serializers.Field()
|
||||
|
||||
class CommentSerializer(serializers.Serializer):
|
||||
user = UserSerializer()
|
||||
title = serializers.Field()
|
||||
content = serializers.Field()
|
||||
created = serializers.Field()
|
||||
|
||||
---
|
||||
|
||||
**Note**: Nested serializers are only suitable for read-only representations, as there are cases where they would have ambiguous or non-obvious behavior if used when updating instances. For read-write representations you should always use a flat representation, by using one of the `RelatedField` subclasses.
|
||||
|
||||
---
|
||||
|
||||
|
||||
## Creating custom fields
|
||||
|
||||
If you want to create a custom field, you'll probably want to override either one or both of the `.to_native()` and `.from_native()` methods. These two methods are used to convert between the intial datatype, and a primative, serializable datatype. Primative datatypes may be any of a number, string, date/time/datetime or None. They may also be any list or dictionary like object that only contains other primative objects.
|
||||
|
||||
The `.to_native()` method is called to convert the initial datatype into a primative, serializable datatype. The `from_native()` method is called to restore a primative datatype into it's initial representation.
|
||||
|
||||
Let's look at an example of serializing a class that represents an RGB color value:
|
||||
|
||||
class Color(object):
|
||||
"""
|
||||
A color represented in the RGB colorspace.
|
||||
"""
|
||||
def __init__(self, red, green, blue):
|
||||
assert(red >= 0 and green >= 0 and blue >= 0)
|
||||
assert(red < 256 and green < 256 and blue < 256)
|
||||
self.red, self.green, self.blue = red, green, blue
|
||||
|
||||
class ColourField(serializers.WritableField):
|
||||
"""
|
||||
Color objects are serialized into "rgb(#, #, #)" notation.
|
||||
"""
|
||||
def to_native(self, obj):
|
||||
return "rgb(%d, %d, %d)" % (obj.red, obj.green, obj.blue)
|
||||
|
||||
def from_native(self, data):
|
||||
data = data.strip('rgb(').rstrip(')')
|
||||
red, green, blue = [int(col) for col in data.split(',')]
|
||||
return Color(red, green, blue)
|
||||
|
||||
|
||||
By default field values are treated as mapping to an attribute on the object. If you need to customize how the field value is accessed and set you need to override `.field_to_native()` and/or `.field_from_native()`.
|
||||
|
||||
As an example, let's create a field that can be used represent the class name of the object being serialized:
|
||||
|
||||
class ClassNameField(serializers.WritableField):
|
||||
def field_to_native(self, obj, field_name):
|
||||
"""
|
||||
Serialize the object's class name, not an attribute of the object.
|
||||
"""
|
||||
return obj.__class__.__name__
|
||||
|
||||
def field_from_native(self, data, field_name, into):
|
||||
"""
|
||||
We don't want to set anything when we revert this field.
|
||||
"""
|
||||
pass
|
||||
|
||||
---
|
||||
|
||||
# ModelSerializers
|
||||
|
||||
Often you'll want serializer classes that map closely to model definitions.
|
||||
The `ModelSerializer` class lets you automatically create a Serializer class with fields that corrospond to the Model fields.
|
||||
|
||||
class AccountSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = Account
|
||||
|
||||
**[TODO: Explain model field to serializer field mapping in more detail]**
|
||||
|
||||
## Specifying fields explicitly
|
||||
|
||||
You can add extra fields to a `ModelSerializer` or override the default fields by declaring fields on the class, just as you would for a `Serializer` class.
|
||||
|
||||
class AccountSerializer(serializers.ModelSerializer):
|
||||
url = CharField(source='get_absolute_url', read_only=True)
|
||||
group = NaturalKeyField()
|
||||
|
||||
class Meta:
|
||||
model = Account
|
||||
|
||||
Extra fields can correspond to any property or callable on the model.
|
||||
|
||||
## Relational fields
|
||||
|
||||
When serializing model instances, there are a number of different ways you might choose to represent relationships. The default representation is to use the primary keys of the related instances.
|
||||
|
||||
Alternative representations include serializing using natural keys, serializing complete nested representations, or serializing using a custom representation, such as a URL that uniquely identifies the model instances.
|
||||
|
||||
The `PrimaryKeyRelatedField` and `HyperlinkedRelatedField` fields provide alternative flat representations.
|
||||
|
||||
The `ModelSerializer` class can itself be used as a field, in order to serialize relationships using nested representations.
|
||||
|
||||
The `RelatedField` class may be subclassed to create a custom representation of a relationship. The subclass should override `.to_native()`, and optionally `.from_native()` if deserialization is supported.
|
||||
|
||||
All the relational fields may be used for any relationship or reverse relationship on a model.
|
||||
|
||||
## Specifying which fields should be included
|
||||
|
||||
If you only want a subset of the default fields to be used in a model serializer, you can do so using `fields` or `exclude` options, just as you would with a `ModelForm`.
|
||||
|
||||
For example:
|
||||
|
||||
class AccountSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = Account
|
||||
exclude = ('id',)
|
||||
|
||||
## Specifiying nested serialization
|
||||
|
||||
The default `ModelSerializer` uses primary keys for relationships, but you can also easily generate nested representations using the `depth` option:
|
||||
|
||||
class AccountSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = Account
|
||||
exclude = ('id',)
|
||||
depth = 1
|
||||
|
||||
The `depth` option should be set to an integer value that indicates the depth of relationships that should be traversed before reverting to a flat representation.
|
||||
|
||||
## Customising the default fields
|
||||
|
||||
You can create customized subclasses of `ModelSerializer` that use a different set of default fields for the representation, by overriding various `get_<field_type>_field` methods.
|
||||
|
||||
Each of these methods may either return a field or serializer instance, or `None`.
|
||||
|
||||
### get_pk_field
|
||||
|
||||
**Signature**: `.get_pk_field(self, model_field)`
|
||||
|
||||
Returns the field instance that should be used to represent the pk field.
|
||||
|
||||
### get_nested_field
|
||||
|
||||
**Signature**: `.get_nested_field(self, model_field)`
|
||||
|
||||
Returns the field instance that should be used to represent a related field when `depth` is specified as being non-zero.
|
||||
|
||||
### get_related_field
|
||||
|
||||
**Signature**: `.get_related_field(self, model_field, to_many=False)`
|
||||
|
||||
Returns the field instance that should be used to represent a related field when `depth` is not specified, or when nested representations are being used and the depth reaches zero.
|
||||
|
||||
### get_field
|
||||
|
||||
**Signature**: `.get_field(self, model_field)`
|
||||
|
||||
Returns the field instance that should be used for non-relational, non-pk fields.
|
||||
|
||||
### Example:
|
||||
|
||||
The following custom model serializer could be used as a base class for model serializers that should always exclude the pk by default.
|
||||
|
||||
class NoPKModelSerializer(serializers.ModelSerializer):
|
||||
def get_pk_field(self, model_field):
|
||||
return None
|
||||
|
||||
|
||||
|
||||
[cite]: https://groups.google.com/d/topic/django-users/sVFaOfQi4wY/discussion
|
153
docs/api-guide/settings.md
Normal file
153
docs/api-guide/settings.md
Normal file
|
@ -0,0 +1,153 @@
|
|||
<a class="github" href="settings.py"></a>
|
||||
|
||||
# Settings
|
||||
|
||||
> Namespaces are one honking great idea - let's do more of those!
|
||||
>
|
||||
> — [The Zen of Python][cite]
|
||||
|
||||
Configuration for REST framework is all namespaced inside a single Django setting, named `REST_FRAMEWORK`.
|
||||
|
||||
For example your project's `settings.py` file might include something like this:
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
'DEFAULT_RENDERER_CLASSES': (
|
||||
'rest_framework.renderers.YAMLRenderer',
|
||||
)
|
||||
'DEFAULT_PARSER_CLASSES': (
|
||||
'rest_framework.parsers.YAMLParser',
|
||||
)
|
||||
}
|
||||
|
||||
## Accessing settings
|
||||
|
||||
If you need to access the values of REST framework's API settings in your project,
|
||||
you should use the `api_settings` object. For example.
|
||||
|
||||
from rest_framework.settings import api_settings
|
||||
|
||||
print api_settings.DEFAULT_AUTHENTICATION_CLASSES
|
||||
|
||||
The `api_settings` object will check for any user-defined settings, and otherwise fallback to the default values. Any setting that uses string import paths to refer to a class will automatically import and return the referenced class, instead of the string literal.
|
||||
|
||||
---
|
||||
|
||||
# API Reference
|
||||
|
||||
## DEFAULT_RENDERER_CLASSES
|
||||
|
||||
A list or tuple of renderer classes, that determines the default set of renderers that may be used when returning a `Response` object.
|
||||
|
||||
Default:
|
||||
|
||||
(
|
||||
'rest_framework.renderers.JSONRenderer',
|
||||
'rest_framework.renderers.BrowsableAPIRenderer',
|
||||
'rest_framework.renderers.TemplateHTMLRenderer'
|
||||
)
|
||||
|
||||
## DEFAULT_PARSER_CLASSES
|
||||
|
||||
A list or tuple of parser classes, that determines the default set of parsers used when accessing the `request.DATA` property.
|
||||
|
||||
Default:
|
||||
|
||||
(
|
||||
'rest_framework.parsers.JSONParser',
|
||||
'rest_framework.parsers.FormParser'
|
||||
)
|
||||
|
||||
## DEFAULT_AUTHENTICATION_CLASSES
|
||||
|
||||
A list or tuple of authentication classes, that determines the default set of authenticators used when accessing the `request.user` or `request.auth` properties.
|
||||
|
||||
Default:
|
||||
|
||||
(
|
||||
'rest_framework.authentication.SessionAuthentication',
|
||||
'rest_framework.authentication.UserBasicAuthentication'
|
||||
)
|
||||
|
||||
## DEFAULT_PERMISSION_CLASSES
|
||||
|
||||
A list or tuple of permission classes, that determines the default set of permissions checked at the start of a view.
|
||||
|
||||
Default:
|
||||
|
||||
(
|
||||
'rest_framework.permissions.AllowAny',
|
||||
)
|
||||
|
||||
## DEFAULT_THROTTLE_CLASSES
|
||||
|
||||
A list or tuple of throttle classes, that determines the default set of throttles checked at the start of a view.
|
||||
|
||||
Default: `()`
|
||||
|
||||
## DEFAULT_MODEL_SERIALIZER_CLASS
|
||||
|
||||
**TODO**
|
||||
|
||||
Default: `rest_framework.serializers.ModelSerializer`
|
||||
|
||||
## DEFAULT_PAGINATION_SERIALIZER_CLASS
|
||||
|
||||
**TODO**
|
||||
|
||||
Default: `rest_framework.pagination.PaginationSerializer`
|
||||
|
||||
## FORMAT_SUFFIX_KWARG
|
||||
|
||||
**TODO**
|
||||
|
||||
Default: `'format'`
|
||||
|
||||
## UNAUTHENTICATED_USER
|
||||
|
||||
The class that should be used to initialize `request.user` for unauthenticated requests.
|
||||
|
||||
Default: `django.contrib.auth.models.AnonymousUser`
|
||||
|
||||
## UNAUTHENTICATED_TOKEN
|
||||
|
||||
The class that should be used to initialize `request.auth` for unauthenticated requests.
|
||||
|
||||
Default: `None`
|
||||
|
||||
## FORM_METHOD_OVERRIDE
|
||||
|
||||
The name of a form field that may be used to override the HTTP method of the form.
|
||||
|
||||
If the value of this setting is `None` then form method overloading will be disabled.
|
||||
|
||||
Default: `'_method'`
|
||||
|
||||
## FORM_CONTENT_OVERRIDE
|
||||
|
||||
The name of a form field that may be used to override the content of the form payload. Must be used together with `FORM_CONTENTTYPE_OVERRIDE`.
|
||||
|
||||
If either setting is `None` then form content overloading will be disabled.
|
||||
|
||||
Default: `'_content'`
|
||||
|
||||
## FORM_CONTENTTYPE_OVERRIDE
|
||||
|
||||
The name of a form field that may be used to override the content type of the form payload. Must be used together with `FORM_CONTENT_OVERRIDE`.
|
||||
|
||||
If either setting is `None` then form content overloading will be disabled.
|
||||
|
||||
Default: `'_content_type'`
|
||||
|
||||
## URL_ACCEPT_OVERRIDE
|
||||
|
||||
The name of a URL parameter that may be used to override the HTTP `Accept` header.
|
||||
|
||||
If the value of this setting is `None` then URL accept overloading will be disabled.
|
||||
|
||||
Default: `'accept'`
|
||||
|
||||
## URL_FORMAT_OVERRIDE
|
||||
|
||||
Default: `'format'`
|
||||
|
||||
[cite]: http://www.python.org/dev/peps/pep-0020/
|
95
docs/api-guide/status-codes.md
Normal file
95
docs/api-guide/status-codes.md
Normal file
|
@ -0,0 +1,95 @@
|
|||
<a class="github" href="status.py"></a>
|
||||
|
||||
# Status Codes
|
||||
|
||||
> 418 I'm a teapot - Any attempt to brew coffee with a teapot should result in the error code "418 I'm a teapot". The resulting entity body MAY be short and stout.
|
||||
>
|
||||
> — [RFC 2324][rfc2324], Hyper Text Coffee Pot Control Protocol
|
||||
|
||||
Using bare status codes in your responses isn't recommended. REST framework includes a set of named constants that you can use to make more code more obvious and readable.
|
||||
|
||||
from rest_framework import status
|
||||
|
||||
def empty_view(self):
|
||||
content = {'please move along': 'nothing to see here'}
|
||||
return Response(content, status=status.HTTP_404_NOT_FOUND)
|
||||
|
||||
The full set of HTTP status codes included in the `status` module is listed below.
|
||||
|
||||
For more information on proper usage of HTTP status codes see [RFC 2616][rfc2616]
|
||||
and [RFC 6585][rfc6585].
|
||||
|
||||
## Informational - 1xx
|
||||
|
||||
This class of status code indicates a provisional response. There are no 1xx status codes used in REST framework by default.
|
||||
|
||||
HTTP_100_CONTINUE
|
||||
HTTP_101_SWITCHING_PROTOCOLS
|
||||
|
||||
## Successful - 2xx
|
||||
|
||||
This class of status code indicates that the client's request was successfully received, understood, and accepted.
|
||||
|
||||
HTTP_200_OK
|
||||
HTTP_201_CREATED
|
||||
HTTP_202_ACCEPTED
|
||||
HTTP_203_NON_AUTHORITATIVE_INFORMATION
|
||||
HTTP_204_NO_CONTENT
|
||||
HTTP_205_RESET_CONTENT
|
||||
HTTP_206_PARTIAL_CONTENT
|
||||
|
||||
## Redirection - 3xx
|
||||
|
||||
This class of status code indicates that further action needs to be taken by the user agent in order to fulfill the request.
|
||||
|
||||
HTTP_300_MULTIPLE_CHOICES
|
||||
HTTP_301_MOVED_PERMANENTLY
|
||||
HTTP_302_FOUND
|
||||
HTTP_303_SEE_OTHER
|
||||
HTTP_304_NOT_MODIFIED
|
||||
HTTP_305_USE_PROXY
|
||||
HTTP_306_RESERVED
|
||||
HTTP_307_TEMPORARY_REDIRECT
|
||||
|
||||
## Client Error - 4xx
|
||||
|
||||
The 4xx class of status code is intended for cases in which the client seems to have erred. Except when responding to a HEAD request, the server SHOULD include an entity containing an explanation of the error situation, and whether it is a temporary or permanent condition.
|
||||
|
||||
HTTP_400_BAD_REQUEST
|
||||
HTTP_401_UNAUTHORIZED
|
||||
HTTP_402_PAYMENT_REQUIRED
|
||||
HTTP_403_FORBIDDEN
|
||||
HTTP_404_NOT_FOUND
|
||||
HTTP_405_METHOD_NOT_ALLOWED
|
||||
HTTP_406_NOT_ACCEPTABLE
|
||||
HTTP_407_PROXY_AUTHENTICATION_REQUIRED
|
||||
HTTP_408_REQUEST_TIMEOUT
|
||||
HTTP_409_CONFLICT
|
||||
HTTP_410_GONE
|
||||
HTTP_411_LENGTH_REQUIRED
|
||||
HTTP_412_PRECONDITION_FAILED
|
||||
HTTP_413_REQUEST_ENTITY_TOO_LARGE
|
||||
HTTP_414_REQUEST_URI_TOO_LONG
|
||||
HTTP_415_UNSUPPORTED_MEDIA_TYPE
|
||||
HTTP_416_REQUESTED_RANGE_NOT_SATISFIABLE
|
||||
HTTP_417_EXPECTATION_FAILED
|
||||
HTTP_428_PRECONDITION_REQUIRED
|
||||
HTTP_429_TOO_MANY_REQUESTS
|
||||
HTTP_431_REQUEST_HEADER_FIELDS_TOO_LARGE
|
||||
|
||||
## Server Error - 5xx
|
||||
|
||||
Response status codes beginning with the digit "5" indicate cases in which the server is aware that it has erred or is incapable of performing the request. Except when responding to a HEAD request, the server SHOULD include an entity containing an explanation of the error situation, and whether it is a temporary or permanent condition.
|
||||
|
||||
HTTP_500_INTERNAL_SERVER_ERROR
|
||||
HTTP_501_NOT_IMPLEMENTED
|
||||
HTTP_502_BAD_GATEWAY
|
||||
HTTP_503_SERVICE_UNAVAILABLE
|
||||
HTTP_504_GATEWAY_TIMEOUT
|
||||
HTTP_505_HTTP_VERSION_NOT_SUPPORTED
|
||||
HTTP_511_NETWORD_AUTHENTICATION_REQUIRED
|
||||
|
||||
|
||||
[rfc2324]: http://www.ietf.org/rfc/rfc2324.txt
|
||||
[rfc2616]: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
|
||||
[rfc6585]: http://tools.ietf.org/html/rfc6585
|
157
docs/api-guide/throttling.md
Normal file
157
docs/api-guide/throttling.md
Normal file
|
@ -0,0 +1,157 @@
|
|||
<a class="github" href="throttling.py"></a>
|
||||
|
||||
# Throttling
|
||||
|
||||
> HTTP/1.1 420 Enhance Your Calm
|
||||
>
|
||||
> [Twitter API rate limiting response][cite]
|
||||
|
||||
[cite]: https://dev.twitter.com/docs/error-codes-responses
|
||||
|
||||
Throttling is similar to [permissions], in that it determines if a request should be authorized. Throttles indicate a temporary state, and are used to control the rate of requests that clients can make to an API.
|
||||
|
||||
As with permissions, multiple throttles may be used. Your API might have a restrictive throttle for unauthenticated requests, and a less restrictive throttle for authenticated requests.
|
||||
|
||||
Another scenario where you might want to use multiple throttles would be if you need to impose different constraints on different parts of the API, due to some services being particularly resource-intensive.
|
||||
|
||||
Multiple throttles can also be used if you want to impose both burst throttling rates, and sustained throttling rates. For example, you might want to limit a user to a maximum of 60 requests per minute, and 1000 requests per day.
|
||||
|
||||
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.
|
||||
|
||||
## How throttling is determined
|
||||
|
||||
As with permissions and authentication, throttling in REST framework is always defined as a list of classes.
|
||||
|
||||
Before running the main body of the view each throttle in the list is checked.
|
||||
If any throttle check fails an `exceptions.Throttled` exception will be raised, and the main body of the view will not run.
|
||||
|
||||
## Setting the throttling policy
|
||||
|
||||
The default throttling policy may be set globally, using the `DEFAULT_THROTTLE_CLASSES` and `DEFAULT_THROTTLE_RATES` settings. For example.
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
'DEFAULT_THROTTLE_CLASSES': (
|
||||
'rest_framework.throttles.AnonThrottle',
|
||||
'rest_framework.throttles.UserThrottle'
|
||||
),
|
||||
'DEFAULT_THROTTLE_RATES': {
|
||||
'anon': '100/day',
|
||||
'user': '1000/day'
|
||||
}
|
||||
}
|
||||
|
||||
The rate descriptions used in `DEFAULT_THROTTLE_RATES` may include `second`, `minute`, `hour` or `day` as the throttle period.
|
||||
|
||||
You can also set the throttling policy on a per-view basis, using the `APIView` class based views.
|
||||
|
||||
class ExampleView(APIView):
|
||||
throttle_classes = (UserThrottle,)
|
||||
|
||||
def get(self, request, format=None):
|
||||
content = {
|
||||
'status': 'request was permitted'
|
||||
}
|
||||
return Response(content)
|
||||
|
||||
Or, if you're using the `@api_view` decorator with function based views.
|
||||
|
||||
@api_view('GET')
|
||||
@throttle_classes(UserThrottle)
|
||||
def example_view(request, format=None):
|
||||
content = {
|
||||
'status': 'request was permitted'
|
||||
}
|
||||
return Response(content)
|
||||
|
||||
---
|
||||
|
||||
# API Reference
|
||||
|
||||
## AnonRateThrottle
|
||||
|
||||
The `AnonThrottle` will only ever throttle unauthenticated users. The IP address of the incoming request is used to generate a unique key to throttle against.
|
||||
|
||||
The allowed request rate is determined from one of the following (in order of preference).
|
||||
|
||||
* The `rate` property on the class, which may be provided by overriding `AnonThrottle` and setting the property.
|
||||
* The `DEFAULT_THROTTLE_RATES['anon']` setting.
|
||||
|
||||
`AnonThrottle` is suitable if you want to restrict the rate of requests from unknown sources.
|
||||
|
||||
## UserRateThrottle
|
||||
|
||||
The `UserThrottle` will throttle users to a given rate of requests across the API. The user id is used to generate a unique key to throttle against. Unauthenticated requests will fall back to using the IP address of the incoming request to generate a unique key to throttle against.
|
||||
|
||||
The allowed request rate is determined from one of the following (in order of preference).
|
||||
|
||||
* The `rate` property on the class, which may be provided by overriding `UserThrottle` and setting the property.
|
||||
* The `DEFAULT_THROTTLE_RATES['user']` setting.
|
||||
|
||||
An API may have multiple `UserRateThrottles` in place at the same time. To do so, override `UserRateThrottle` and set a unique "scope" for each class.
|
||||
|
||||
For example, multiple user throttle rates could be implemented by using the following classes...
|
||||
|
||||
class BurstRateThrottle(UserRateThrottle):
|
||||
scope = 'burst'
|
||||
|
||||
class SustainedRateThrottle(UserRateThrottle):
|
||||
scope = 'sustained'
|
||||
|
||||
...and the following settings.
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
'DEFAULT_THROTTLE_CLASSES': (
|
||||
'example.throttles.BurstRateThrottle',
|
||||
'example.throttles.SustainedRateThrottle'
|
||||
),
|
||||
'DEFAULT_THROTTLE_RATES': {
|
||||
'burst': '60/min',
|
||||
'sustained': '1000/day'
|
||||
}
|
||||
}
|
||||
|
||||
`UserThrottle` is suitable if you want simple global rate restrictions per-user.
|
||||
|
||||
## ScopedRateThrottle
|
||||
|
||||
The `ScopedThrottle` class can be used to restrict access to specific parts of the API. This throttle will only be applied if the view that is being accessed includes a `.throttle_scope` property. The unique throttle key will then be formed by concatenating the "scope" of the request with the unique user id or IP address.
|
||||
|
||||
The allowed request rate is determined by the `DEFAULT_THROTTLE_RATES` setting using a key from the request "scope".
|
||||
|
||||
For example, given the following views...
|
||||
|
||||
class ContactListView(APIView):
|
||||
throttle_scope = 'contacts'
|
||||
...
|
||||
|
||||
class ContactDetailView(ApiView):
|
||||
throttle_scope = 'contacts'
|
||||
...
|
||||
|
||||
class UploadView(APIView):
|
||||
throttle_scope = 'uploads'
|
||||
...
|
||||
|
||||
...and the following settings.
|
||||
|
||||
REST_FRAMEWORK = {
|
||||
'DEFAULT_THROTTLE_CLASSES': (
|
||||
'rest_framework.throttles.ScopedRateThrottle'
|
||||
),
|
||||
'DEFAULT_THROTTLE_RATES': {
|
||||
'contacts': '1000/day',
|
||||
'uploads': '20/day'
|
||||
}
|
||||
}
|
||||
|
||||
User requests to either `ContactListView` or `ContactDetailView` would be restricted to a total of 1000 requests per-day. User requests to `UploadView` would be restricted to 20 requests per day.
|
||||
|
||||
---
|
||||
|
||||
# Custom throttles
|
||||
|
||||
To create a custom throttle, override `BaseThrottle` and implement `.allow_request(request, view)`. The method should return `True` if the request should be allowed, and `False` otherwise.
|
||||
|
||||
Optionally you may also override the `.wait()` method. If implemented, `.wait()` should return a recommended number of seconds to wait before attempting the next request, or `None`. The `.wait()` method will only be called if `.allow_request()` has previously returned `False`.
|
||||
|
||||
[permissions]: permissions.md
|
168
docs/api-guide/views.md
Normal file
168
docs/api-guide/views.md
Normal file
|
@ -0,0 +1,168 @@
|
|||
<a class="github" href="decorators.py"></a> <a class="github" href="views.py"></a>
|
||||
|
||||
# Class Based Views
|
||||
|
||||
> Django's class based views are a welcome departure from the old-style views.
|
||||
>
|
||||
> — [Reinout van Rees][cite]
|
||||
|
||||
REST framework provides an `APIView` class, which subclasses Django's `View` class.
|
||||
|
||||
`APIView` classes are different from regular `View` classes in the following ways:
|
||||
|
||||
* Requests passed to the handler methods will be REST framework's `Request` instances, not Django's `HttpRequest` instances.
|
||||
* Handler methods may return REST framework's `Response`, instead of Django's `HttpResponse`. The view will manage content negotiation and setting the correct renderer on the response.
|
||||
* Any `APIException` exceptions will be caught and mediated into appropriate responses.
|
||||
* Incoming requests will be authenticated and appropriate permission and/or throttle checks will be run before dispatching the request to the handler method.
|
||||
|
||||
Using the `APIView` class is pretty much the same as using a regular `View` class, as usual, the incoming request is dispatched to an appropriate handler method such as `.get()` or `.post()`. Additionally, a number of attributes may be set on the class that control various aspects of the API policy.
|
||||
|
||||
For example:
|
||||
|
||||
class ListUsers(APIView):
|
||||
"""
|
||||
View to list all users in the system.
|
||||
|
||||
* Requires token authentication.
|
||||
* Only admin users are able to access this view.
|
||||
"""
|
||||
authentication_classes = (authentication.TokenAuthentication,)
|
||||
permission_classes = (permissions.IsAdminUser,)
|
||||
|
||||
def get(self, request, format=None):
|
||||
"""
|
||||
Return a list of all users.
|
||||
"""
|
||||
usernames = [user.username for user in User.objects.all()]
|
||||
return Response(usernames)
|
||||
|
||||
## API policy attributes
|
||||
|
||||
The following attributes control the pluggable aspects of API views.
|
||||
|
||||
### .renderer_classes
|
||||
|
||||
### .parser_classes
|
||||
|
||||
### .authentication_classes
|
||||
|
||||
### .throttle_classes
|
||||
|
||||
### .permission_classes
|
||||
|
||||
### .content_negotiation_class
|
||||
|
||||
## API policy instantiation methods
|
||||
|
||||
The following methods are used by REST framework to instantiate the various pluggable API policies. You won't typically need to override these methods.
|
||||
|
||||
### .get_renderers(self)
|
||||
|
||||
### .get_parsers(self)
|
||||
|
||||
### .get_authenticators(self)
|
||||
|
||||
### .get_throttles(self)
|
||||
|
||||
### .get_permissions(self)
|
||||
|
||||
### .get_content_negotiator(self)
|
||||
|
||||
## API policy implementation methods
|
||||
|
||||
The following methods are called before dispatching to the handler method.
|
||||
|
||||
### .check_permissions(...)
|
||||
|
||||
### .check_throttles(...)
|
||||
|
||||
### .perform_content_negotiation(...)
|
||||
|
||||
## Dispatch methods
|
||||
|
||||
The following methods are called directly by the view's `.dispatch()` method.
|
||||
These perform any actions that need to occur before or after calling the handler methods such as `.get()`, `.post()`, `put()` and `.delete()`.
|
||||
|
||||
### .initial(self, request, \*args, **kwargs)
|
||||
|
||||
Performs any actions that need to occur before the handler method gets called.
|
||||
This method is used to enforce permissions and throttling, and perform content negotiation.
|
||||
|
||||
You won't typically need to override this method.
|
||||
|
||||
### .handle_exception(self, exc)
|
||||
|
||||
Any exception thrown by the handler method will be passed to this method, which either returns a `Response` instance, or re-raises the exception.
|
||||
|
||||
The default implementation handles any subclass of `rest_framework.exceptions.APIException`, as well as Django's `Http404` and `PermissionDenied` exceptions, and returns an appropriate error response.
|
||||
|
||||
If you need to customize the error responses your API returns you should subclass this method.
|
||||
|
||||
### .initialize_request(self, request, \*args, **kwargs)
|
||||
|
||||
Ensures that the request object that is passed to the handler method is an instance of `Request`, rather than the usual Django `HttpRequest`.
|
||||
|
||||
You won't typically need to override this method.
|
||||
|
||||
### .finalize_response(self, request, response, \*args, **kwargs)
|
||||
|
||||
Ensures that any `Response` object returned from the handler method will be rendered into the correct content type, as determined by the content negotation.
|
||||
|
||||
You won't typically need to override this method.
|
||||
|
||||
---
|
||||
|
||||
# Function Based Views
|
||||
|
||||
> Saying [that Class based views] is always the superior solution is a mistake.
|
||||
>
|
||||
> — [Nick Coghlan][cite2]
|
||||
|
||||
REST framework also allows you to work with regular function based views. It provides a set of simple decorators that wrap your function based views to ensure they receive an instance of `Request` (rather than the usual Django `HttpRequest`) and allows them to return a `Response` (instead of a Django `HttpResponse`), and allow you to configure how the request is processed.
|
||||
|
||||
## @api_view()
|
||||
|
||||
**Signature:** `@api_view(http_method_names)`
|
||||
|
||||
The core of this functionality is the `api_view` decorator, which takes a list of HTTP methods that your view should respond to. For example, this is how you would write a very simple view that just manually returns some data:
|
||||
|
||||
from rest_framework.decorators import api_view
|
||||
|
||||
@api_view(['GET'])
|
||||
def hello_world(request):
|
||||
return Response({"message": "Hello, world!"})
|
||||
|
||||
|
||||
This view will use the default renderers, parsers, authentication classes etc specified in the [settings](settings).
|
||||
|
||||
## API policy decorators
|
||||
|
||||
To override the default settings, REST framework provides a set of additional decorators which can be added to your views. These must come *after* (below) the `@api_view` decorator. For example, to create a view that uses a [throttle](throttling) to ensure it can only be called once per day by a particular user, use the `@throttle_classes` decorator, passing a list of throttle classes:
|
||||
|
||||
from rest_framework.decorators import api_view, throttle_classes
|
||||
from rest_framework.throttling import UserRateThrottle
|
||||
|
||||
class OncePerDayUserThrottle(UserRateThrottle):
|
||||
rate = '1/day'
|
||||
|
||||
@api_view(['GET'])
|
||||
@throttle_classes([OncePerDayUserThrottle])
|
||||
def view(request):
|
||||
return Response({"message": "Hello for today! See you tomorrow!"})
|
||||
|
||||
These decorators correspond to the attributes set on `APIView` subclasses, described above.
|
||||
|
||||
The available decorators are:
|
||||
|
||||
* `@renderer_classes(...)`
|
||||
* `@parser_classes(...)`
|
||||
* `@authentication_classes(...)`
|
||||
* `@throttle_classes(...)`
|
||||
* `@permission_classes(...)`
|
||||
|
||||
Each of these decorators takes a single argument which must be a list or tuple of classes.
|
||||
|
||||
[cite]: http://reinout.vanrees.org/weblog/2011/08/24/class-based-views-usage.html
|
||||
[cite2]: http://www.boredomandlaziness.org/2012/05/djangos-cbvs-are-not-mistake-but.html
|
||||
[settings]: api-guide/settings.md
|
||||
[throttling]: api-guide/throttling.md
|
|
@ -1,9 +0,0 @@
|
|||
import pytest
|
||||
import subprocess
|
||||
|
||||
def test_build_docs(tmpdir):
|
||||
doctrees = tmpdir.join("doctrees")
|
||||
htmldir = "html" #we want to keep the docs
|
||||
subprocess.check_call([
|
||||
"sphinx-build", "-q", "-bhtml",
|
||||
"-d", str(doctrees), ".", str(htmldir)])
|
228
docs/conf.py
228
docs/conf.py
|
@ -1,228 +0,0 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
#
|
||||
# Asset Platform documentation build configuration file, created by
|
||||
# sphinx-quickstart on Fri Nov 19 20:24:09 2010.
|
||||
#
|
||||
# This file is execfile()d with the current directory set to its containing dir.
|
||||
#
|
||||
# Note that not all possible configuration values are present in this
|
||||
# autogenerated file.
|
||||
#
|
||||
# All configuration values have a default; values that are commented out
|
||||
# serve to show the default.
|
||||
|
||||
import sys, os
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(__file__)), 'djangorestframework')) # for documenting the library
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(__file__)), 'examples')) # for importing settings
|
||||
import settings
|
||||
from django.core.management import setup_environ
|
||||
setup_environ(settings)
|
||||
|
||||
# If extensions (or modules to document with autodoc) are in another directory,
|
||||
# add these directories to sys.path here. If the directory is relative to the
|
||||
# documentation root, use os.path.abspath to make it absolute, like shown here.
|
||||
#sys.path.insert(0, os.path.abspath('.'))
|
||||
|
||||
# -- General configuration -----------------------------------------------------
|
||||
|
||||
# If your documentation needs a minimal Sphinx version, state it here.
|
||||
#needs_sphinx = '1.0'
|
||||
|
||||
# Add any Sphinx extension module names here, as strings. They can be extensions
|
||||
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
|
||||
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.viewcode']
|
||||
|
||||
# Add any paths that contain templates here, relative to this directory.
|
||||
templates_path = ['templates']
|
||||
|
||||
# The suffix of source filenames.
|
||||
source_suffix = '.rst'
|
||||
|
||||
# The encoding of source files.
|
||||
#source_encoding = 'utf-8-sig'
|
||||
|
||||
# The master toctree document.
|
||||
master_doc = 'index'
|
||||
|
||||
# General information about the project.
|
||||
project = u'django-rest-framework'
|
||||
copyright = u'2011, Tom Christie'
|
||||
|
||||
# The version info for the project you're documenting, acts as replacement for
|
||||
# |version| and |release|, also used in various other places throughout the
|
||||
# built documents.
|
||||
#
|
||||
# The short X.Y version.
|
||||
|
||||
import djangorestframework
|
||||
|
||||
version = djangorestframework.__version__
|
||||
|
||||
# The full version, including alpha/beta/rc tags.
|
||||
release = version
|
||||
|
||||
autodoc_member_order='bysource'
|
||||
|
||||
# The language for content autogenerated by Sphinx. Refer to documentation
|
||||
# for a list of supported languages.
|
||||
#language = None
|
||||
|
||||
# There are two options for replacing |today|: either, you set today to some
|
||||
# non-false value, then it is used:
|
||||
#today = ''
|
||||
# Else, today_fmt is used as the format for a strftime call.
|
||||
#today_fmt = '%B %d, %Y'
|
||||
|
||||
# List of patterns, relative to source directory, that match files and
|
||||
# directories to ignore when looking for source files.
|
||||
exclude_patterns = ['_build']
|
||||
|
||||
# The reST default role (used for this markup: `text`) to use for all documents.
|
||||
#default_role = None
|
||||
|
||||
# If true, '()' will be appended to :func: etc. cross-reference text.
|
||||
#add_function_parentheses = True
|
||||
|
||||
# If true, the current module name will be prepended to all description
|
||||
# unit titles (such as .. function::).
|
||||
#add_module_names = True
|
||||
|
||||
# If true, sectionauthor and moduleauthor directives will be shown in the
|
||||
# output. They are ignored by default.
|
||||
#show_authors = False
|
||||
|
||||
# The name of the Pygments (syntax highlighting) style to use.
|
||||
pygments_style = 'sphinx'
|
||||
|
||||
# A list of ignored prefixes for module index sorting.
|
||||
#modindex_common_prefix = []
|
||||
|
||||
|
||||
# -- Options for HTML output ---------------------------------------------------
|
||||
|
||||
# The theme to use for HTML and HTML Help pages. See the documentation for
|
||||
# a list of builtin themes.
|
||||
html_theme = 'sphinxdoc'
|
||||
|
||||
# Theme options are theme-specific and customize the look and feel of a theme
|
||||
# further. For a list of options available for each theme, see the
|
||||
# documentation.
|
||||
#html_theme_options = {}
|
||||
|
||||
# Add any paths that contain custom themes here, relative to this directory.
|
||||
#html_theme_path = []
|
||||
|
||||
# The name for this set of Sphinx documents. If None, it defaults to
|
||||
# "<project> v<release> documentation".
|
||||
html_title = "Django REST framework"
|
||||
|
||||
# A shorter title for the navigation bar. Default is the same as html_title.
|
||||
#html_short_title = None
|
||||
|
||||
# The name of an image file (relative to this directory) to place at the top
|
||||
# of the sidebar.
|
||||
#html_logo = None
|
||||
|
||||
# The name of an image file (within the static path) to use as favicon of the
|
||||
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
|
||||
# pixels large.
|
||||
#html_favicon = None
|
||||
|
||||
# Add any paths that contain custom static files (such as style sheets) here,
|
||||
# relative to this directory. They are copied after the builtin static files,
|
||||
# so a file named "default.css" will overwrite the builtin "default.css".
|
||||
html_static_path = []
|
||||
|
||||
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
|
||||
# using the given strftime format.
|
||||
#html_last_updated_fmt = '%b %d, %Y'
|
||||
|
||||
# If true, SmartyPants will be used to convert quotes and dashes to
|
||||
# typographically correct entities.
|
||||
#html_use_smartypants = True
|
||||
|
||||
# Custom sidebar templates, maps document names to template names.
|
||||
#html_sidebars = {}
|
||||
|
||||
# Additional templates that should be rendered to pages, maps page names to
|
||||
# template names.
|
||||
#html_additional_pages = {}
|
||||
|
||||
# If false, no module index is generated.
|
||||
#html_domain_indices = True
|
||||
|
||||
# If false, no index is generated.
|
||||
#html_use_index = True
|
||||
|
||||
# If true, the index is split into individual pages for each letter.
|
||||
#html_split_index = False
|
||||
|
||||
# If true, links to the reST sources are added to the pages.
|
||||
#html_show_sourcelink = True
|
||||
|
||||
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
|
||||
#html_show_sphinx = True
|
||||
|
||||
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
|
||||
#html_show_copyright = True
|
||||
|
||||
# If true, an OpenSearch description file will be output, and all pages will
|
||||
# contain a <link> tag referring to it. The value of this option must be the
|
||||
# base URL from which the finished HTML is served.
|
||||
#html_use_opensearch = ''
|
||||
|
||||
# This is the file name suffix for HTML files (e.g. ".xhtml").
|
||||
#html_file_suffix = None
|
||||
|
||||
# Output file base name for HTML help builder.
|
||||
#htmlhelp_basename = ''
|
||||
|
||||
|
||||
# -- Options for LaTeX output --------------------------------------------------
|
||||
|
||||
# The paper size ('letter' or 'a4').
|
||||
#latex_paper_size = 'letter'
|
||||
|
||||
# The font size ('10pt', '11pt' or '12pt').
|
||||
#latex_font_size = '10pt'
|
||||
|
||||
# Grouping the document tree into LaTeX files. List of tuples
|
||||
# (source start file, target name, title, author, documentclass [howto/manual]).
|
||||
#latex_documents = [
|
||||
# (),
|
||||
#]
|
||||
|
||||
# The name of an image file (relative to this directory) to place at the top of
|
||||
# the title page.
|
||||
#latex_logo = None
|
||||
|
||||
# For "manual" documents, if this is true, then toplevel headings are parts,
|
||||
# not chapters.
|
||||
#latex_use_parts = False
|
||||
|
||||
# If true, show page references after internal links.
|
||||
#latex_show_pagerefs = False
|
||||
|
||||
# If true, show URL addresses after external links.
|
||||
#latex_show_urls = False
|
||||
|
||||
# Additional stuff for the LaTeX preamble.
|
||||
#latex_preamble = ''
|
||||
|
||||
# Documents to append as an appendix to all manuals.
|
||||
#latex_appendices = []
|
||||
|
||||
# If false, no module index is generated.
|
||||
#latex_domain_indices = True
|
||||
|
||||
# -- Options for manual page output --------------------------------------------
|
||||
|
||||
# One entry per manual page. List of tuples
|
||||
# (source start file, name, description, authors, manual section).
|
||||
#man_pages = [
|
||||
# ()
|
||||
#]
|
||||
|
||||
linkcheck_timeout = 120 # seconds, set to extra large value for link_checks
|
|
@ -1,10 +0,0 @@
|
|||
Documentation
|
||||
=============
|
||||
|
||||
.. toctree::
|
||||
:maxdepth: 2
|
||||
|
||||
howto
|
||||
library
|
||||
examples
|
||||
|
1058
docs/css/bootstrap-responsive.css
vendored
Executable file
1058
docs/css/bootstrap-responsive.css
vendored
Executable file
File diff suppressed because it is too large
Load Diff
5774
docs/css/bootstrap.css
vendored
Executable file
5774
docs/css/bootstrap.css
vendored
Executable file
File diff suppressed because it is too large
Load Diff
268
docs/css/default.css
Normal file
268
docs/css/default.css
Normal file
|
@ -0,0 +1,268 @@
|
|||
/* Set the body padding-top when above 980px to push the content down from
|
||||
below the navbar, which is fixed at >980px screen widths. */
|
||||
pre {
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.dropdown .dropdown-menu {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.dropdown.open .dropdown-menu {
|
||||
display: block;
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.repo-link {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
/* Header link to GitHub */
|
||||
.repo-link {
|
||||
float: right;
|
||||
margin-right: 10px;
|
||||
margin-top: 9px;
|
||||
}
|
||||
|
||||
/* GitHub 'Star' badge */
|
||||
body.index-page #main-content iframe {
|
||||
float: right;
|
||||
margin-top: -12px;
|
||||
margin-right: -15px;
|
||||
}
|
||||
|
||||
/* Travis CI badge */
|
||||
body.index-page #main-content p:first-of-type {
|
||||
float: right;
|
||||
margin-right: 8px;
|
||||
margin-top: -14px;
|
||||
margin-bottom: 0px;
|
||||
}
|
||||
|
||||
/* Github source file badges */
|
||||
a.github {
|
||||
float: right;
|
||||
margin-top: -12px;
|
||||
margin-right: 12px;
|
||||
}
|
||||
|
||||
a.github:hover {
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
/* */
|
||||
body hr {
|
||||
border-top: 1px dotted #A30000;
|
||||
}
|
||||
|
||||
/* Force TOC text to not overrun */
|
||||
#table-of-contents {
|
||||
overflow: hidden;
|
||||
margin: 0 0 20px 0;
|
||||
}
|
||||
|
||||
/* Code blocks should scroll horizontally */
|
||||
pre {
|
||||
overflow: auto;
|
||||
word-wrap: normal;
|
||||
white-space: pre;
|
||||
}
|
||||
|
||||
/* Preserve the spacing of the navbar across different screen sizes. */
|
||||
.navbar-inner {
|
||||
/*padding: 5px 0;*/
|
||||
}
|
||||
|
||||
@media (max-width: 979px) {
|
||||
.navbar .brand {
|
||||
margin-left: 0;
|
||||
padding-left: 0;
|
||||
}
|
||||
.navbar-inner .container-fluid {
|
||||
padding-left: 15px;
|
||||
}
|
||||
}
|
||||
|
||||
.nav-list li.main {
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.nav-list a {
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
/* Set the table of contents to static so it flows back into the content when
|
||||
viewed on tablets and smaller. */
|
||||
@media (max-width: 767px) {
|
||||
#table-of-contents {
|
||||
position: static;
|
||||
}
|
||||
}
|
||||
|
||||
/* When the page is in two-column layout, give the main content some room
|
||||
to breath on the left. */
|
||||
@media (min-width: 768px) {
|
||||
#main-content {
|
||||
padding-left: 1em;
|
||||
}
|
||||
}
|
||||
|
||||
/* Cutesy quote styling */
|
||||
blockquote {
|
||||
font-family: Georgia, serif;
|
||||
font-size: 18px;
|
||||
font-style: italic;
|
||||
margin: 0.25em 0;
|
||||
padding: 0.25em 40px;
|
||||
line-height: 1.45;
|
||||
position: relative;
|
||||
color: #383838;
|
||||
border-left: none;
|
||||
}
|
||||
|
||||
blockquote:before {
|
||||
display: block;
|
||||
content: "\201C";
|
||||
font-size: 80px;
|
||||
position: absolute;
|
||||
left: -10px;
|
||||
top: -20px;
|
||||
color: #7a7a7a;
|
||||
}
|
||||
|
||||
blockquote p:last-child {
|
||||
color: #999999;
|
||||
font-size: 14px;
|
||||
display: block;
|
||||
margin-top: 5px;
|
||||
}
|
||||
|
||||
|
||||
/*=== dabapps bootstrap styles ====*/
|
||||
|
||||
html{
|
||||
width:100%;
|
||||
background: none;
|
||||
}
|
||||
|
||||
body, .navbar .navbar-inner .container-fluid{
|
||||
max-width: 1150px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
body{
|
||||
background: url("../img/grid.png") repeat-x;
|
||||
background-attachment: fixed;
|
||||
}
|
||||
|
||||
/* custom navigation styles */
|
||||
|
||||
.navbar .navbar-inner{
|
||||
background: #2C2C2C;
|
||||
color: white;
|
||||
border: none;
|
||||
border-top: 5px solid #A30000;
|
||||
}
|
||||
|
||||
.navbar .navbar-inner .nav li, .navbar .navbar-inner .nav li a, .navbar .navbar-inner .brand{
|
||||
color: white;
|
||||
}
|
||||
|
||||
.nav-list > .active > a, .navbar .navbar-inner .nav li a:hover {
|
||||
background:#212121;
|
||||
color:white;
|
||||
}
|
||||
|
||||
.navbar .navbar-inner .dropdown-menu li a, .navbar .navbar-inner .dropdown-menu li{
|
||||
color: #A30000;
|
||||
}
|
||||
.navbar .navbar-inner .dropdown-menu li a:hover{
|
||||
background: #eeeeee;
|
||||
color: #c20000;
|
||||
}
|
||||
|
||||
/* custom general page styles */
|
||||
.hero-unit h2, .hero-unit h1{
|
||||
color: #A30000;
|
||||
}
|
||||
|
||||
body a{
|
||||
color: #A30000;
|
||||
}
|
||||
|
||||
body a:hover{
|
||||
color: #c20000;
|
||||
}
|
||||
|
||||
/* subnavigation styles */
|
||||
|
||||
@media (min-width: 767px) {
|
||||
.sidebar-nav-fixed {
|
||||
position:fixed;
|
||||
width:19%;
|
||||
max-width: 240px;
|
||||
}
|
||||
|
||||
.navbar {
|
||||
position: fixed;
|
||||
}
|
||||
.navbar .navbar-inner .container-fluid{
|
||||
max-width: 1110px;
|
||||
}
|
||||
}
|
||||
|
||||
/* sticky footer and footer */
|
||||
html, body {
|
||||
height: 100%;
|
||||
}
|
||||
.wrapper {
|
||||
min-height: 100%;
|
||||
height: auto !important;
|
||||
height: 100%;
|
||||
margin: 0 auto -60px;
|
||||
}
|
||||
|
||||
.body-content{
|
||||
padding-top: 70px;
|
||||
padding-bottom: 70px;
|
||||
}
|
||||
|
||||
@media (max-width: 979px) {
|
||||
.navbar-fixed-top .navbar-inner {
|
||||
padding: 0px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 767px) {
|
||||
.body-content{
|
||||
padding-top: 0px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (min-width: 768px) {
|
||||
footer.span12 {
|
||||
width: 95%;
|
||||
}
|
||||
}
|
||||
|
||||
footer, .push {
|
||||
height: 60px; /* .push must be the same height as .footer */
|
||||
}
|
||||
|
||||
|
||||
footer p {
|
||||
text-align: center;
|
||||
color: gray;
|
||||
border-top: 1px solid #DDD;
|
||||
padding-top: 10px;
|
||||
}
|
||||
|
||||
footer a {
|
||||
color: gray;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
footer a:hover {
|
||||
color: gray;
|
||||
}
|
30
docs/css/prettify.css
Normal file
30
docs/css/prettify.css
Normal file
|
@ -0,0 +1,30 @@
|
|||
.com { color: #93a1a1; }
|
||||
.lit { color: #195f91; }
|
||||
.pun, .opn, .clo { color: #93a1a1; }
|
||||
.fun { color: #dc322f; }
|
||||
.str, .atv { color: #D14; }
|
||||
.kwd, .prettyprint .tag { color: #1e347b; }
|
||||
.typ, .atn, .dec, .var { color: teal; }
|
||||
.pln { color: #48484c; }
|
||||
|
||||
.prettyprint {
|
||||
padding: 8px;
|
||||
background-color: #f7f7f9;
|
||||
border: 1px solid #e1e1e8;
|
||||
}
|
||||
.prettyprint.linenums {
|
||||
-webkit-box-shadow: inset 40px 0 0 #fbfbfc, inset 41px 0 0 #ececf0;
|
||||
-moz-box-shadow: inset 40px 0 0 #fbfbfc, inset 41px 0 0 #ececf0;
|
||||
box-shadow: inset 40px 0 0 #fbfbfc, inset 41px 0 0 #ececf0;
|
||||
}
|
||||
|
||||
/* Specify class=linenums on a pre to get line numbering */
|
||||
ol.linenums {
|
||||
margin: 0 0 0 33px; /* IE indents via margin-left */
|
||||
}
|
||||
ol.linenums li {
|
||||
padding-left: 12px;
|
||||
color: #bebec5;
|
||||
line-height: 20px;
|
||||
text-shadow: 0 1px 0 #fff;
|
||||
}
|
|
@ -1,23 +0,0 @@
|
|||
Examples
|
||||
========
|
||||
|
||||
There are a few real world web API examples included with Django REST framework.
|
||||
|
||||
#. :doc:`examples/objectstore` - Using :class:`views.View` classes for APIs that do not map to models.
|
||||
#. :doc:`examples/pygments` - Using :class:`views.View` classes with forms for input validation.
|
||||
#. :doc:`examples/blogpost` - Using :class:`views.ModelView` classes for APIs that map directly to models.
|
||||
|
||||
All the examples are freely available for testing in the sandbox:
|
||||
|
||||
http://shielded-mountain-6732.herokuapp.com
|
||||
|
||||
(The :doc:`examples/sandbox` resource is also documented.)
|
||||
|
||||
Example Reference
|
||||
-----------------
|
||||
|
||||
.. toctree::
|
||||
:maxdepth: 1
|
||||
:glob:
|
||||
|
||||
examples/*
|
|
@ -1,37 +0,0 @@
|
|||
Blog Posts API
|
||||
==============
|
||||
|
||||
* http://shielded-mountain-6732.herokuapp.com/blog-post/
|
||||
|
||||
The models
|
||||
----------
|
||||
|
||||
In this example we're working from two related models:
|
||||
|
||||
``models.py``
|
||||
|
||||
.. include:: ../../examples/blogpost/models.py
|
||||
:literal:
|
||||
|
||||
Creating the resources
|
||||
----------------------
|
||||
|
||||
We need to create two resources that we map to our two existing models, in order to describe how the models should be serialized.
|
||||
Our resource descriptions will typically go into a module called something like 'resources.py'
|
||||
|
||||
``resources.py``
|
||||
|
||||
.. include:: ../../examples/blogpost/resources.py
|
||||
:literal:
|
||||
|
||||
Creating views for our resources
|
||||
--------------------------------
|
||||
|
||||
Once we've created the resources there's very little we need to do to create the API.
|
||||
For each resource we'll create a base view, and an instance view.
|
||||
The generic views :class:`.ListOrCreateModelView` and :class:`.InstanceModelView` provide default operations for listing, creating and updating our models via the API, and also automatically provide input validation using default ModelForms for each model.
|
||||
|
||||
``urls.py``
|
||||
|
||||
.. include:: ../../examples/blogpost/urls.py
|
||||
:literal:
|
|
@ -1,56 +0,0 @@
|
|||
Getting Started - Model Views
|
||||
-----------------------------
|
||||
|
||||
.. note::
|
||||
|
||||
A live sandbox instance of this API is available:
|
||||
|
||||
http://shielded-mountain-6732.herokuapp.com/model-resource-example/
|
||||
|
||||
You can browse the API using a web browser, or from the command line::
|
||||
|
||||
curl -X GET http://shielded-mountain-6732.herokuapp.com/resource-example/ -H 'Accept: text/plain'
|
||||
|
||||
Often you'll want parts of your API to directly map to existing django models. Django REST framework handles this nicely for you in a couple of ways:
|
||||
|
||||
#. It automatically provides suitable create/read/update/delete methods for your views.
|
||||
#. Input validation occurs automatically, by using appropriate `ModelForms <http://docs.djangoproject.com/en/dev/topics/forms/modelforms/>`_.
|
||||
|
||||
Here's the model we're working from in this example:
|
||||
|
||||
``models.py``
|
||||
|
||||
.. include:: ../../examples/modelresourceexample/models.py
|
||||
:literal:
|
||||
|
||||
To add an API for the model, first we need to create a Resource for the model.
|
||||
|
||||
``resources.py``
|
||||
|
||||
.. include:: ../../examples/modelresourceexample/resources.py
|
||||
:literal:
|
||||
|
||||
Then we simply map a couple of views to the Resource in our urlconf.
|
||||
|
||||
``urls.py``
|
||||
|
||||
.. include:: ../../examples/modelresourceexample/urls.py
|
||||
:literal:
|
||||
|
||||
And we're done. We've now got a fully browseable API, which supports multiple input and output media types, and has all the nice automatic field validation that Django gives us for free.
|
||||
|
||||
We can visit the API in our browser:
|
||||
|
||||
* http://shielded-mountain-6732.herokuapp.com/model-resource-example/
|
||||
|
||||
Or access it from the command line using curl:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
# Demonstrates API's input validation using form input
|
||||
bash: curl -X POST --data 'foo=true' http://shielded-mountain-6732.herokuapp.com/model-resource-example/
|
||||
{"detail": {"bar": ["This field is required."], "baz": ["This field is required."]}}
|
||||
|
||||
# Demonstrates API's input validation using JSON input
|
||||
bash: curl -X POST -H 'Content-Type: application/json' --data-binary '{"foo":true}' http://shielded-mountain-6732.herokuapp.com/model-resource-example/
|
||||
{"detail": {"bar": ["This field is required."], "baz": ["This field is required."]}}
|
|
@ -1,17 +0,0 @@
|
|||
Object Store API
|
||||
================
|
||||
|
||||
* http://shielded-mountain-6732.herokuapp.com/object-store/
|
||||
|
||||
This example shows an object store API that can be used to store arbitrary serializable content.
|
||||
|
||||
``urls.py``
|
||||
|
||||
.. include:: ../../examples/objectstore/urls.py
|
||||
:literal:
|
||||
|
||||
``views.py``
|
||||
|
||||
.. include:: ../../examples/objectstore/views.py
|
||||
:literal:
|
||||
|
|
@ -1,66 +0,0 @@
|
|||
Permissions
|
||||
===========
|
||||
|
||||
This example will show how you can protect your api by using authentication
|
||||
and how you can limit the amount of requests a user can do to a resource by setting
|
||||
a throttle to your view.
|
||||
|
||||
Authentication
|
||||
--------------
|
||||
|
||||
If you want to protect your api from unauthorized users, Django REST Framework
|
||||
offers you two default authentication methods:
|
||||
|
||||
* Basic Authentication
|
||||
* Django's session-based authentication
|
||||
|
||||
These authentication methods are by default enabled. But they are not used unless
|
||||
you specifically state that your view requires authentication.
|
||||
|
||||
To do this you just need to import the `Isauthenticated` class from the frameworks' `permissions` module.::
|
||||
|
||||
from djangorestframework.permissions import IsAuthenticated
|
||||
|
||||
Then you enable authentication by setting the right 'permission requirement' to the `permissions` class attribute of your View like
|
||||
the example View below.:
|
||||
|
||||
|
||||
.. literalinclude:: ../../examples/permissionsexample/views.py
|
||||
:pyobject: LoggedInExampleView
|
||||
|
||||
The `IsAuthenticated` permission will only let a user do a 'GET' if he is authenticated. Try it
|
||||
yourself on the live sandbox__
|
||||
|
||||
__ http://shielded-mountain-6732.herokuapp.com/permissions-example/loggedin
|
||||
|
||||
|
||||
Throttling
|
||||
----------
|
||||
|
||||
If you want to limit the amount of requests a client is allowed to do on
|
||||
a resource, then you can set a 'throttle' to achieve this.
|
||||
|
||||
For this to work you'll need to import the `PerUserThrottling` class from the `permissions`
|
||||
module.::
|
||||
|
||||
from djangorestframework.permissions import PerUserThrottling
|
||||
|
||||
In the example below we have limited the amount of requests one 'client' or 'user'
|
||||
may do on our view to 10 requests per minute.:
|
||||
|
||||
.. literalinclude:: ../../examples/permissionsexample/views.py
|
||||
:pyobject: ThrottlingExampleView
|
||||
|
||||
Try it yourself on the live sandbox__.
|
||||
|
||||
__ http://shielded-mountain-6732.herokuapp.com/permissions-example/throttling
|
||||
|
||||
Now if you want a view to require both aurhentication and throttling, you simply declare them
|
||||
both::
|
||||
|
||||
permissions = (PerUserThrottling, Isauthenticated)
|
||||
|
||||
To see what other throttles are available, have a look at the :mod:`permissions` module.
|
||||
|
||||
If you want to implement your own authentication method, then refer to the :mod:`authentication`
|
||||
module.
|
|
@ -1,89 +0,0 @@
|
|||
Code Highlighting API
|
||||
=====================
|
||||
|
||||
This example demonstrates creating a REST API using a :class:`.Resource` with some form validation on the input.
|
||||
We're going to provide a simple wrapper around the awesome `pygments <http://pygments.org/>`_ library, to create the Web API for a simple pastebin.
|
||||
|
||||
.. note::
|
||||
|
||||
A live sandbox instance of this API is available at http://shielded-mountain-6732.herokuapp.com/pygments/
|
||||
|
||||
You can browse the API using a web browser, or from the command line::
|
||||
|
||||
curl -X GET http://shielded-mountain-6732.herokuapp.com/pygments/ -H 'Accept: text/plain'
|
||||
|
||||
|
||||
URL configuration
|
||||
-----------------
|
||||
|
||||
We'll need two resources:
|
||||
|
||||
* A resource which represents the root of the API.
|
||||
* A resource which represents an instance of a highlighted snippet.
|
||||
|
||||
``urls.py``
|
||||
|
||||
.. include:: ../../examples/pygments_api/urls.py
|
||||
:literal:
|
||||
|
||||
Form validation
|
||||
---------------
|
||||
|
||||
We'll now add a form to specify what input fields are required when creating a new highlighted code snippet. This will include:
|
||||
|
||||
* The code text itself.
|
||||
* An optional title for the code.
|
||||
* A flag to determine if line numbers should be included.
|
||||
* Which programming language to interpret the code snippet as.
|
||||
* Which output style to use for the highlighting.
|
||||
|
||||
``forms.py``
|
||||
|
||||
.. include:: ../../examples/pygments_api/forms.py
|
||||
:literal:
|
||||
|
||||
Creating the resources
|
||||
----------------------
|
||||
|
||||
We'll need to define 3 resource handling methods on our resources.
|
||||
|
||||
* ``PygmentsRoot.get()`` method, which lists all the existing snippets.
|
||||
* ``PygmentsRoot.post()`` method, which creates new snippets.
|
||||
* ``PygmentsInstance.get()`` method, which returns existing snippets.
|
||||
|
||||
And set a number of attributes on our resources.
|
||||
|
||||
* Set the ``allowed_methods`` and ``anon_allowed_methods`` attributes on both resources allowing for full unauthenticated access.
|
||||
* Set the ``form`` attribute on the ``PygmentsRoot`` resource, to give us input validation when we create snippets.
|
||||
* Set the ``emitters`` attribute on the ``PygmentsInstance`` resource, so that
|
||||
|
||||
``views.py``
|
||||
|
||||
.. include:: ../../examples/pygments_api/views.py
|
||||
:literal:
|
||||
|
||||
Completed
|
||||
---------
|
||||
|
||||
And we're done. We now have an API that is:
|
||||
|
||||
* **Browseable.** The API supports media types for both programmatic and human access, and can be accessed either via a browser or from the command line.
|
||||
* **Self describing.** The API serves as it's own documentation.
|
||||
* **Well connected.** The API can be accessed fully by traversal from the initial URL. Clients never need to construct URLs themselves.
|
||||
|
||||
Our API also supports multiple media types for both input and output, and applies sensible input validation in all cases.
|
||||
|
||||
For example if we make a POST request using form input:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
bash: curl -X POST --data 'code=print "hello, world!"' --data 'style=foobar' -H 'X-Requested-With: XMLHttpRequest' http://shielded-mountain-6732.herokuapp.com/pygments/
|
||||
{"detail": {"style": ["Select a valid choice. foobar is not one of the available choices."], "lexer": ["This field is required."]}}
|
||||
|
||||
Or if we make the same request using JSON:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
bash: curl -X POST --data-binary '{"code":"print \"hello, world!\"", "style":"foobar"}' -H 'Content-Type: application/json' -H 'X-Requested-With: XMLHttpRequest' http://shielded-mountain-6732.herokuapp.com/pygments/
|
||||
{"detail": {"style": ["Select a valid choice. foobar is not one of the available choices."], "lexer": ["This field is required."]}}
|
||||
|
|
@ -1,12 +0,0 @@
|
|||
Sandbox Root API
|
||||
================
|
||||
|
||||
The Resource
|
||||
------------
|
||||
|
||||
The root level resource of the Django REST framework examples is a simple read only resource:
|
||||
|
||||
``view.py``
|
||||
|
||||
.. include:: ../../examples/sandbox/views.py
|
||||
:literal:
|
|
@ -1,56 +0,0 @@
|
|||
Getting Started - Views
|
||||
-----------------------
|
||||
|
||||
.. note::
|
||||
|
||||
A live sandbox instance of this API is available:
|
||||
|
||||
http://shielded-mountain-6732.herokuapp.com/resource-example/
|
||||
|
||||
You can browse the API using a web browser, or from the command line::
|
||||
|
||||
curl -X GET http://shielded-mountain-6732.herokuapp.com/resource-example/ -H 'Accept: text/plain'
|
||||
|
||||
We're going to start off with a simple example, that demonstrates a few things:
|
||||
|
||||
#. Creating views.
|
||||
#. Linking views.
|
||||
#. Writing method handlers on views.
|
||||
#. Adding form validation to views.
|
||||
|
||||
First we'll define two views in our urlconf.
|
||||
|
||||
``urls.py``
|
||||
|
||||
.. include:: ../../examples/resourceexample/urls.py
|
||||
:literal:
|
||||
|
||||
Now we'll add a form that we'll use for input validation. This is completely optional, but it's often useful.
|
||||
|
||||
``forms.py``
|
||||
|
||||
.. include:: ../../examples/resourceexample/forms.py
|
||||
:literal:
|
||||
|
||||
Now we'll write our views. The first is a read only view that links to three instances of the second. The second view just has some stub handler methods to help us see that our example is working.
|
||||
|
||||
``views.py``
|
||||
|
||||
.. include:: ../../examples/resourceexample/views.py
|
||||
:literal:
|
||||
|
||||
That's us done. Our API now provides both programmatic access using JSON and XML, as well a nice browseable HTML view, so we can now access it both from the browser:
|
||||
|
||||
* http://shielded-mountain-6732.herokuapp.com/resource-example/
|
||||
|
||||
And from the command line:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
# Demonstrates API's input validation using form input
|
||||
bash: curl -X POST --data 'foo=true' http://shielded-mountain-6732.herokuapp.com/resource-example/1/
|
||||
{"detail": {"bar": ["This field is required."], "baz": ["This field is required."]}}
|
||||
|
||||
# Demonstrates API's input validation using JSON input
|
||||
bash: curl -X POST -H 'Content-Type: application/json' --data-binary '{"foo":true}' http://shielded-mountain-6732.herokuapp.com/resource-example/1/
|
||||
{"detail": {"bar": ["This field is required."], "baz": ["This field is required."]}}
|
|
@ -1,8 +0,0 @@
|
|||
How Tos, FAQs & Notes
|
||||
=====================
|
||||
|
||||
.. toctree::
|
||||
:maxdepth: 1
|
||||
:glob:
|
||||
|
||||
howto/*
|
|
@ -1,35 +0,0 @@
|
|||
Alternative frameworks & Why Django REST framework
|
||||
==================================================
|
||||
|
||||
Alternative frameworks
|
||||
----------------------
|
||||
|
||||
There are a number of alternative REST frameworks for Django:
|
||||
|
||||
* `django-piston <https://bitbucket.org/jespern/django-piston/wiki/Home>`_ is very mature, and has a large community behind it. This project was originally based on piston code in parts.
|
||||
* `django-tastypie <https://github.com/toastdriven/django-tastypie>`_ is also very good, and has a very active and helpful developer community and maintainers.
|
||||
* Other interesting projects include `dagny <https://github.com/zacharyvoase/dagny>`_ and `dj-webmachine <http://benoitc.github.com/dj-webmachine/>`_
|
||||
|
||||
|
||||
Why use Django REST framework?
|
||||
------------------------------
|
||||
|
||||
The big benefits of using Django REST framework come down to:
|
||||
|
||||
1. It's based on Django's class based views, which makes it simple, modular, and future-proof.
|
||||
2. It stays as close as possible to Django idioms and language throughout.
|
||||
3. The browse-able API makes working with the APIs extremely quick and easy.
|
||||
|
||||
|
||||
Why was this project created?
|
||||
-----------------------------
|
||||
|
||||
For me the browse-able API is the most important aspect of Django REST framework.
|
||||
|
||||
I wanted to show that Web APIs could easily be made Web browse-able,
|
||||
and demonstrate how much better browse-able Web APIs are to work with.
|
||||
|
||||
Being able to navigate and use a Web API directly in the browser is a huge win over only having command line and programmatic
|
||||
access to the API. It enables the API to be properly self-describing, and it makes it much much quicker and easier to work with.
|
||||
There's no fundamental reason why the Web APIs we're creating shouldn't be able to render to HTML as well as JSON/XML/whatever,
|
||||
and I really think that more Web API frameworks *in whatever language* ought to be taking a similar approach.
|
|
@ -1,30 +0,0 @@
|
|||
Using Django REST framework Mixin classes
|
||||
=========================================
|
||||
|
||||
This example demonstrates creating a REST API **without** using Django REST framework's :class:`.Resource` or :class:`.ModelResource`, but instead using Django's :class:`View` class, and adding the :class:`ResponseMixin` class to provide full HTTP Accept header content negotiation,
|
||||
a browseable Web API, and much of the other goodness that Django REST framework gives you for free.
|
||||
|
||||
.. note::
|
||||
|
||||
A live sandbox instance of this API is available for testing:
|
||||
|
||||
* http://shielded-mountain-6732.herokuapp.com/mixin/
|
||||
|
||||
You can browse the API using a web browser, or from the command line::
|
||||
|
||||
curl -X GET http://shielded-mountain-6732.herokuapp.com/mixin/
|
||||
|
||||
|
||||
URL configuration
|
||||
-----------------
|
||||
|
||||
Everything we need for this example can go straight into the URL conf...
|
||||
|
||||
``urls.py``
|
||||
|
||||
.. include:: ../../examples/mixin/urls.py
|
||||
:literal:
|
||||
|
||||
That's it. Auto-magically our API now supports multiple output formats, specified either by using
|
||||
standard HTTP Accept header content negotiation, or by using the `&_accept=application/json` style parameter overrides.
|
||||
We even get a nice HTML view which can be used to self-document our API.
|
|
@ -1,50 +0,0 @@
|
|||
Returning URIs from your Web APIs
|
||||
=================================
|
||||
|
||||
As a rule, it's probably better practice to return absolute URIs from you web
|
||||
APIs, e.g. "http://example.com/foobar", rather than returning relative URIs,
|
||||
e.g. "/foobar".
|
||||
|
||||
The advantages of doing so are:
|
||||
|
||||
* It's more explicit.
|
||||
* It leaves less work for your API clients.
|
||||
* There's no ambiguity about the meaning of the string when it's found in
|
||||
representations such as JSON that do not have a native URI type.
|
||||
* It allows us to easily do things like markup HTML representations
|
||||
with hyperlinks.
|
||||
|
||||
Django REST framework provides two utility functions to make it simpler to
|
||||
return absolute URIs from your Web API.
|
||||
|
||||
There's no requirement for you to use them, but if you do then the
|
||||
self-describing API will be able to automatically hyperlink its output for you,
|
||||
which makes browsing the API much easier.
|
||||
|
||||
reverse(viewname, ..., request=None)
|
||||
-------------------------------
|
||||
|
||||
The `reverse` function has the same behavior as
|
||||
`django.core.urlresolvers.reverse`_, except that it optionally takes a request
|
||||
keyword argument, which it uses to return a fully qualified URL.
|
||||
|
||||
from djangorestframework.reverse import reverse
|
||||
from djangorestframework.views import View
|
||||
|
||||
class MyView(View):
|
||||
def get(self, request):
|
||||
context = {
|
||||
'url': reverse('year-summary', args=[1945], request=request)
|
||||
}
|
||||
|
||||
return Response(context)
|
||||
|
||||
reverse_lazy(viewname, ..., request=None)
|
||||
------------------------------------
|
||||
|
||||
The `reverse_lazy` function has the same behavior as
|
||||
`django.core.urlresolvers.reverse_lazy`_, except that it optionally takes a
|
||||
request keyword argument, which it uses to return a fully qualified URL.
|
||||
|
||||
.. _django.core.urlresolvers.reverse: https://docs.djangoproject.com/en/dev/topics/http/urls/#reverse
|
||||
.. _django.core.urlresolvers.reverse_lazy: https://docs.djangoproject.com/en/dev/topics/http/urls/#reverse-lazy
|
|
@ -1,73 +0,0 @@
|
|||
.. _setup:
|
||||
|
||||
Setup
|
||||
=====
|
||||
|
||||
Templates
|
||||
---------
|
||||
|
||||
Django REST framework uses a few templates for the HTML and plain text
|
||||
documenting renderers. You'll need to ensure ``TEMPLATE_LOADERS`` setting
|
||||
contains ``'django.template.loaders.app_directories.Loader'``.
|
||||
This will already be the case by default.
|
||||
|
||||
You may customize the templates by creating a new template called
|
||||
``djangorestframework/api.html`` in your project, which should extend
|
||||
``djangorestframework/base.html`` and override the appropriate
|
||||
block tags. For example::
|
||||
|
||||
{% extends "djangorestframework/base.html" %}
|
||||
|
||||
{% block title %}My API{% endblock %}
|
||||
|
||||
{% block branding %}
|
||||
<h1 id="site-name">My API</h1>
|
||||
{% endblock %}
|
||||
|
||||
|
||||
Styling
|
||||
-------
|
||||
|
||||
Django REST framework requires `django.contrib.staticfiles`_ to serve it's css.
|
||||
If you're using Django 1.2 you'll need to use the seperate
|
||||
`django-staticfiles`_ package instead.
|
||||
|
||||
You can override the styling by creating a file in your top-level static
|
||||
directory named ``djangorestframework/css/style.css``
|
||||
|
||||
|
||||
Markdown
|
||||
--------
|
||||
|
||||
`Python markdown`_ is not required but comes recommended.
|
||||
|
||||
If markdown is installed your :class:`.Resource` descriptions can include
|
||||
`markdown formatting`_ which will be rendered by the self-documenting API.
|
||||
|
||||
YAML
|
||||
----
|
||||
|
||||
YAML support is optional, and requires `PyYAML`_.
|
||||
|
||||
|
||||
Login / Logout
|
||||
--------------
|
||||
|
||||
Django REST framework includes login and logout views that are needed if
|
||||
you're using the self-documenting API.
|
||||
|
||||
Make sure you include the following in your `urlconf`::
|
||||
|
||||
from django.conf.urls.defaults import patterns, url
|
||||
|
||||
urlpatterns = patterns('',
|
||||
...
|
||||
url(r'^restframework', include('djangorestframework.urls', namespace='djangorestframework'))
|
||||
)
|
||||
|
||||
.. _django.contrib.staticfiles: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/
|
||||
.. _django-staticfiles: http://pypi.python.org/pypi/django-staticfiles/
|
||||
.. _URLObject: http://pypi.python.org/pypi/URLObject/
|
||||
.. _Python markdown: http://www.freewisdom.org/projects/python-markdown/
|
||||
.. _markdown formatting: http://daringfireball.net/projects/markdown/syntax
|
||||
.. _PyYAML: http://pypi.python.org/pypi/PyYAML
|
|
@ -1,30 +0,0 @@
|
|||
Using CURL with django-rest-framework
|
||||
=====================================
|
||||
|
||||
`curl <http://curl.haxx.se/>`_ is a great command line tool for making requests to URLs.
|
||||
|
||||
There are a few things that can be helpful to remember when using CURL with django-rest-framework APIs.
|
||||
|
||||
#. Curl sends an ``Accept: */*`` header by default::
|
||||
|
||||
curl -X GET http://example.com/my-api/
|
||||
|
||||
#. Setting the ``Accept:`` header on a curl request can be useful::
|
||||
|
||||
curl -X GET -H 'Accept: application/json' http://example.com/my-api/
|
||||
|
||||
#. The text/plain representation is useful for browsing the API::
|
||||
|
||||
curl -X GET -H 'Accept: text/plain' http://example.com/my-api/
|
||||
|
||||
#. ``POST`` and ``PUT`` requests can contain form data (ie ``Content-Type: application/x-www-form-urlencoded``)::
|
||||
|
||||
curl -X PUT --data 'foo=bar' http://example.com/my-api/some-resource/
|
||||
|
||||
#. Or any other content type::
|
||||
|
||||
curl -X PUT -H 'Content-Type: application/json' --data-binary '{"foo":"bar"}' http://example.com/my-api/some-resource/
|
||||
|
||||
#. You can use basic authentication to send the username and password::
|
||||
|
||||
curl -X GET -H 'Accept: application/json' -u <user>:<password> http://example.com/my-api/
|
|
@ -1,39 +0,0 @@
|
|||
Using urllib2 with Django REST Framework
|
||||
========================================
|
||||
|
||||
Python's standard library comes with some nice modules
|
||||
you can use to test your api or even write a full client.
|
||||
|
||||
Using the 'GET' method
|
||||
----------------------
|
||||
|
||||
Here's an example which does a 'GET' on the `model-resource` example
|
||||
in the sandbox.::
|
||||
|
||||
>>> import urllib2
|
||||
>>> r = urllib2.urlopen('htpp://shielded-mountain-6732.herokuapp.com/model-resource-example')
|
||||
>>> r.getcode() # Check if the response was ok
|
||||
200
|
||||
>>> print r.read() # Examin the response itself
|
||||
[{"url": "http://shielded-mountain-6732.herokuapp.com/model-resource-example/1/", "baz": "sdf", "foo": true, "bar": 123}]
|
||||
|
||||
Using the 'POST' method
|
||||
-----------------------
|
||||
|
||||
And here's an example which does a 'POST' to create a new instance. First let's encode
|
||||
the data we want to POST. We'll use `urllib` for encoding and the `time` module
|
||||
to send the current time as as a string value for our POST.::
|
||||
|
||||
>>> import urllib, time
|
||||
>>> d = urllib.urlencode((('bar', 123), ('baz', time.asctime())))
|
||||
|
||||
Now use the `Request` class and specify the 'Content-type'::
|
||||
|
||||
>>> req = urllib2.Request('http://shielded-mountain-6732.herokuapp.com/model-resource-example/', data=d, headers={'Content-Type':'application/x-www-form-urlencoded'})
|
||||
>>> resp = urllib2.urlopen(req)
|
||||
>>> resp.getcode()
|
||||
201
|
||||
>>> resp.read()
|
||||
'{"url": "http://shielded-mountain-6732.herokuapp.com/model-resource-example/4/", "baz": "Fri Dec 30 18:22:52 2011", "foo": false, "bar": 123}'
|
||||
|
||||
That should get you started to write a client for your own api.
|
BIN
docs/img/favicon.ico
Normal file
BIN
docs/img/favicon.ico
Normal file
Binary file not shown.
After Width: | Height: | Size: 2.2 KiB |
BIN
docs/img/glyphicons-halflings-white.png
Normal file
BIN
docs/img/glyphicons-halflings-white.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 8.6 KiB |
BIN
docs/img/glyphicons-halflings.png
Normal file
BIN
docs/img/glyphicons-halflings.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 12 KiB |
BIN
docs/img/grid.png
Normal file
BIN
docs/img/grid.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 1.4 KiB |
BIN
docs/img/quickstart.png
Normal file
BIN
docs/img/quickstart.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 38 KiB |
208
docs/index.md
Normal file
208
docs/index.md
Normal file
|
@ -0,0 +1,208 @@
|
|||
<iframe src="http://ghbtns.com/github-btn.html?user=tomchristie&repo=django-rest-framework&type=watch&count=true" allowtransparency="true" frameborder="0" scrolling="0" width="110px" height="20px"></iframe>
|
||||
[![Travis build image][travis-build-image]][travis]
|
||||
|
||||
# Django REST framework
|
||||
|
||||
**A toolkit for building well-connected, self-describing Web APIs.**
|
||||
|
||||
---
|
||||
|
||||
**Note**: This documentation is for the 2.0 version of REST framework. If you are looking for earlier versions please see the [0.4.x branch][0.4] on GitHub.
|
||||
|
||||
---
|
||||
|
||||
Django REST framework is a lightweight library that makes it easy to build Web APIs. It is designed as a modular and easy to customize architecture, based on Django's class based views.
|
||||
|
||||
Web APIs built using REST framework are fully self-describing and web browseable - a huge useability win for your developers. It also supports a wide range of media types, authentication and permission policies out of the box.
|
||||
|
||||
If you are considering using REST framework for your API, we recommend reading the [REST framework 2 announcment][rest-framework-2-announcement] which gives a good overview of the framework and it's capabilities.
|
||||
|
||||
There is also a sandbox API you can use for testing purposes, [available here][sandbox].
|
||||
|
||||
**Below**: *Screenshot from the browseable API*
|
||||
|
||||
![Screenshot][image]
|
||||
|
||||
## Requirements
|
||||
|
||||
REST framework requires the following:
|
||||
|
||||
* Python (2.6, 2.7)
|
||||
* Django (1.3, 1.4, 1.5)
|
||||
|
||||
The following packages are optional:
|
||||
|
||||
* [Markdown][markdown] (2.1.0+) - Markdown support for the self describing API.
|
||||
* [PyYAML][yaml] (3.10+) - YAML content-type support.
|
||||
|
||||
## Installation
|
||||
|
||||
Install using `pip`, including any optional packages you want...
|
||||
|
||||
pip install djangorestframework
|
||||
pip install markdown # Recommended if using the browseable API.
|
||||
pip install pyyaml # Required for yaml content-type support.
|
||||
|
||||
...or clone the project from github.
|
||||
|
||||
git clone git@github.com:tomchristie/django-rest-framework.git
|
||||
cd django-rest-framework
|
||||
pip install -r requirements.txt
|
||||
pip install -r optionals.txt
|
||||
|
||||
Add `rest_framework` to your `INSTALLED_APPS`.
|
||||
|
||||
INSTALLED_APPS = (
|
||||
...
|
||||
'rest_framework',
|
||||
)
|
||||
|
||||
If you're intending to use the browseable API you'll want to add REST framework's login and logout views. Add the following to your root `urls.py` file.
|
||||
|
||||
urlpatterns = patterns('',
|
||||
...
|
||||
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
|
||||
)
|
||||
|
||||
Note that the URL path can be whatever you want, but you must include `rest_framework.urls` with the `rest_framework` namespace.
|
||||
|
||||
<!--
|
||||
## Quickstart
|
||||
|
||||
Can't wait to get started? The [quickstart guide][quickstart] is the fastest way to get up and running with REST framework.
|
||||
-->
|
||||
|
||||
## Tutorial
|
||||
|
||||
The tutorial will walk you through the building blocks that make up REST framework. It'll take a little while to get through, but it'll give you a comprehensive understanding of how everything fits together, and is highly recommended reading.
|
||||
|
||||
* [1 - Serialization][tut-1]
|
||||
* [2 - Requests & Responses][tut-2]
|
||||
* [3 - Class based views][tut-3]
|
||||
* [4 - Authentication & permissions][tut-4]
|
||||
* [5 - Relationships & hyperlinked APIs][tut-5]
|
||||
|
||||
## API Guide
|
||||
|
||||
The API guide is your complete reference manual to all the functionality provided by REST framework.
|
||||
|
||||
* [Requests][request]
|
||||
* [Responses][response]
|
||||
* [Views][views]
|
||||
* [Generic views][generic-views]
|
||||
* [Parsers][parsers]
|
||||
* [Renderers][renderers]
|
||||
* [Serializers][serializers]
|
||||
* [Serializer fields][fields]
|
||||
* [Authentication][authentication]
|
||||
* [Permissions][permissions]
|
||||
* [Throttling][throttling]
|
||||
* [Pagination][pagination]
|
||||
* [Content negotiation][contentnegotiation]
|
||||
* [Format suffixes][formatsuffixes]
|
||||
* [Returning URLs][reverse]
|
||||
* [Exceptions][exceptions]
|
||||
* [Status codes][status]
|
||||
* [Settings][settings]
|
||||
|
||||
## Topics
|
||||
|
||||
General guides to using REST framework.
|
||||
|
||||
* [Browser enhancements][browser-enhancements]
|
||||
* [The Browsable API][browsableapi]
|
||||
* [REST, Hypermedia & HATEOAS][rest-hypermedia-hateoas]
|
||||
* [2.0 Announcement][rest-framework-2-announcement]
|
||||
* [Release Notes][release-notes]
|
||||
* [Credits][credits]
|
||||
|
||||
## Development
|
||||
|
||||
If you want to work on REST framework itself, clone the repository, then...
|
||||
|
||||
Build the docs:
|
||||
|
||||
./mkdocs.py
|
||||
|
||||
Run the tests:
|
||||
|
||||
./rest_framework/runtests/runtests.py
|
||||
|
||||
## Support
|
||||
|
||||
For support please see the [REST framework discussion group][group], or try the `#restframework` channel on `irc.freenode.net`.
|
||||
|
||||
Paid support is also available from [DabApps], and can include work on REST framework core, or support with building your REST framework API. Please contact [Tom Christie][email] if you'd like to discuss commercial support options.
|
||||
|
||||
## License
|
||||
|
||||
Copyright (c) 2011-2012, Tom Christie
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
Redistributions in binary form must reproduce the above copyright notice, this
|
||||
list of conditions and the following disclaimer in the documentation and/or
|
||||
other materials provided with the distribution.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
[travis]: http://travis-ci.org/tomchristie/django-rest-framework?branch=restframework2
|
||||
[travis-build-image]: https://secure.travis-ci.org/tomchristie/django-rest-framework.png?branch=restframework2
|
||||
[urlobject]: https://github.com/zacharyvoase/urlobject
|
||||
[markdown]: http://pypi.python.org/pypi/Markdown/
|
||||
[yaml]: http://pypi.python.org/pypi/PyYAML
|
||||
[0.4]: https://github.com/tomchristie/django-rest-framework/tree/0.4.X
|
||||
[image]: img/quickstart.png
|
||||
[sandbox]: http://restframework.herokuapp.com/
|
||||
|
||||
[quickstart]: tutorial/quickstart.md
|
||||
[tut-1]: tutorial/1-serialization.md
|
||||
[tut-2]: tutorial/2-requests-and-responses.md
|
||||
[tut-3]: tutorial/3-class-based-views.md
|
||||
[tut-4]: tutorial/4-authentication-and-permissions.md
|
||||
[tut-5]: tutorial/5-relationships-and-hyperlinked-apis.md
|
||||
|
||||
[request]: api-guide/requests.md
|
||||
[response]: api-guide/responses.md
|
||||
[views]: api-guide/views.md
|
||||
[generic-views]: api-guide/generic-views.md
|
||||
[parsers]: api-guide/parsers.md
|
||||
[renderers]: api-guide/renderers.md
|
||||
[serializers]: api-guide/serializers.md
|
||||
[fields]: api-guide/fields.md
|
||||
[authentication]: api-guide/authentication.md
|
||||
[permissions]: api-guide/permissions.md
|
||||
[throttling]: api-guide/throttling.md
|
||||
[pagination]: api-guide/pagination.md
|
||||
[contentnegotiation]: api-guide/content-negotiation.md
|
||||
[formatsuffixes]: api-guide/format-suffixes.md
|
||||
[reverse]: api-guide/reverse.md
|
||||
[exceptions]: api-guide/exceptions.md
|
||||
[status]: api-guide/status-codes.md
|
||||
[settings]: api-guide/settings.md
|
||||
|
||||
[csrf]: topics/csrf.md
|
||||
[browser-enhancements]: topics/browser-enhancements.md
|
||||
[browsableapi]: topics/browsable-api.md
|
||||
[rest-hypermedia-hateoas]: topics/rest-hypermedia-hateoas.md
|
||||
[contributing]: topics/contributing.md
|
||||
[rest-framework-2-announcement]: topics/rest-framework-2-announcement.md
|
||||
[release-notes]: topics/release-notes.md
|
||||
[credits]: topics/credits.md
|
||||
|
||||
[group]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework
|
||||
[DabApps]: http://dabapps.com
|
||||
[email]: mailto:tom@tomchristie.com
|
|
@ -1,11 +0,0 @@
|
|||
.. meta::
|
||||
:description: A lightweight REST framework for Django.
|
||||
:keywords: django, python, REST, RESTful, API, interface, framework
|
||||
|
||||
|
||||
Django REST framework
|
||||
=====================
|
||||
|
||||
**The documentation has moved.**
|
||||
|
||||
**Please see:** `http://django-rest-framework.org <http://django-rest-framework.org>`_
|
7
docs/js/bootstrap-2.1.1-min.js
vendored
Executable file
7
docs/js/bootstrap-2.1.1-min.js
vendored
Executable file
File diff suppressed because one or more lines are too long
2
docs/js/jquery-1.8.1-min.js
vendored
Normal file
2
docs/js/jquery-1.8.1-min.js
vendored
Normal file
File diff suppressed because one or more lines are too long
28
docs/js/prettify-1.0.js
Normal file
28
docs/js/prettify-1.0.js
Normal file
|
@ -0,0 +1,28 @@
|
|||
var q=null;window.PR_SHOULD_USE_CONTINUATION=!0;
|
||||
(function(){function L(a){function m(a){var f=a.charCodeAt(0);if(f!==92)return f;var b=a.charAt(1);return(f=r[b])?f:"0"<=b&&b<="7"?parseInt(a.substring(1),8):b==="u"||b==="x"?parseInt(a.substring(2),16):a.charCodeAt(1)}function e(a){if(a<32)return(a<16?"\\x0":"\\x")+a.toString(16);a=String.fromCharCode(a);if(a==="\\"||a==="-"||a==="["||a==="]")a="\\"+a;return a}function h(a){for(var f=a.substring(1,a.length-1).match(/\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\[0-3][0-7]{0,2}|\\[0-7]{1,2}|\\[\S\s]|[^\\]/g),a=
|
||||
[],b=[],o=f[0]==="^",c=o?1:0,i=f.length;c<i;++c){var j=f[c];if(/\\[bdsw]/i.test(j))a.push(j);else{var j=m(j),d;c+2<i&&"-"===f[c+1]?(d=m(f[c+2]),c+=2):d=j;b.push([j,d]);d<65||j>122||(d<65||j>90||b.push([Math.max(65,j)|32,Math.min(d,90)|32]),d<97||j>122||b.push([Math.max(97,j)&-33,Math.min(d,122)&-33]))}}b.sort(function(a,f){return a[0]-f[0]||f[1]-a[1]});f=[];j=[NaN,NaN];for(c=0;c<b.length;++c)i=b[c],i[0]<=j[1]+1?j[1]=Math.max(j[1],i[1]):f.push(j=i);b=["["];o&&b.push("^");b.push.apply(b,a);for(c=0;c<
|
||||
f.length;++c)i=f[c],b.push(e(i[0])),i[1]>i[0]&&(i[1]+1>i[0]&&b.push("-"),b.push(e(i[1])));b.push("]");return b.join("")}function y(a){for(var f=a.source.match(/\[(?:[^\\\]]|\\[\S\s])*]|\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\\d+|\\[^\dux]|\(\?[!:=]|[()^]|[^()[\\^]+/g),b=f.length,d=[],c=0,i=0;c<b;++c){var j=f[c];j==="("?++i:"\\"===j.charAt(0)&&(j=+j.substring(1))&&j<=i&&(d[j]=-1)}for(c=1;c<d.length;++c)-1===d[c]&&(d[c]=++t);for(i=c=0;c<b;++c)j=f[c],j==="("?(++i,d[i]===void 0&&(f[c]="(?:")):"\\"===j.charAt(0)&&
|
||||
(j=+j.substring(1))&&j<=i&&(f[c]="\\"+d[i]);for(i=c=0;c<b;++c)"^"===f[c]&&"^"!==f[c+1]&&(f[c]="");if(a.ignoreCase&&s)for(c=0;c<b;++c)j=f[c],a=j.charAt(0),j.length>=2&&a==="["?f[c]=h(j):a!=="\\"&&(f[c]=j.replace(/[A-Za-z]/g,function(a){a=a.charCodeAt(0);return"["+String.fromCharCode(a&-33,a|32)+"]"}));return f.join("")}for(var t=0,s=!1,l=!1,p=0,d=a.length;p<d;++p){var g=a[p];if(g.ignoreCase)l=!0;else if(/[a-z]/i.test(g.source.replace(/\\u[\da-f]{4}|\\x[\da-f]{2}|\\[^UXux]/gi,""))){s=!0;l=!1;break}}for(var r=
|
||||
{b:8,t:9,n:10,v:11,f:12,r:13},n=[],p=0,d=a.length;p<d;++p){g=a[p];if(g.global||g.multiline)throw Error(""+g);n.push("(?:"+y(g)+")")}return RegExp(n.join("|"),l?"gi":"g")}function M(a){function m(a){switch(a.nodeType){case 1:if(e.test(a.className))break;for(var g=a.firstChild;g;g=g.nextSibling)m(g);g=a.nodeName;if("BR"===g||"LI"===g)h[s]="\n",t[s<<1]=y++,t[s++<<1|1]=a;break;case 3:case 4:g=a.nodeValue,g.length&&(g=p?g.replace(/\r\n?/g,"\n"):g.replace(/[\t\n\r ]+/g," "),h[s]=g,t[s<<1]=y,y+=g.length,
|
||||
t[s++<<1|1]=a)}}var e=/(?:^|\s)nocode(?:\s|$)/,h=[],y=0,t=[],s=0,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&&(l=document.defaultView.getComputedStyle(a,q).getPropertyValue("white-space"));var p=l&&"pre"===l.substring(0,3);m(a);return{a:h.join("").replace(/\n$/,""),c:t}}function B(a,m,e,h){m&&(a={a:m,d:a},e(a),h.push.apply(h,a.e))}function x(a,m){function e(a){for(var l=a.d,p=[l,"pln"],d=0,g=a.a.match(y)||[],r={},n=0,z=g.length;n<z;++n){var f=g[n],b=r[f],o=void 0,c;if(typeof b===
|
||||
"string")c=!1;else{var i=h[f.charAt(0)];if(i)o=f.match(i[1]),b=i[0];else{for(c=0;c<t;++c)if(i=m[c],o=f.match(i[1])){b=i[0];break}o||(b="pln")}if((c=b.length>=5&&"lang-"===b.substring(0,5))&&!(o&&typeof o[1]==="string"))c=!1,b="src";c||(r[f]=b)}i=d;d+=f.length;if(c){c=o[1];var j=f.indexOf(c),k=j+c.length;o[2]&&(k=f.length-o[2].length,j=k-c.length);b=b.substring(5);B(l+i,f.substring(0,j),e,p);B(l+i+j,c,C(b,c),p);B(l+i+k,f.substring(k),e,p)}else p.push(l+i,b)}a.e=p}var h={},y;(function(){for(var e=a.concat(m),
|
||||
l=[],p={},d=0,g=e.length;d<g;++d){var r=e[d],n=r[3];if(n)for(var k=n.length;--k>=0;)h[n.charAt(k)]=r;r=r[1];n=""+r;p.hasOwnProperty(n)||(l.push(r),p[n]=q)}l.push(/[\S\s]/);y=L(l)})();var t=m.length;return e}function u(a){var m=[],e=[];a.tripleQuotedStrings?m.push(["str",/^(?:'''(?:[^'\\]|\\[\S\s]|''?(?=[^']))*(?:'''|$)|"""(?:[^"\\]|\\[\S\s]|""?(?=[^"]))*(?:"""|$)|'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$))/,q,"'\""]):a.multiLineStrings?m.push(["str",/^(?:'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$)|`(?:[^\\`]|\\[\S\s])*(?:`|$))/,
|
||||
q,"'\"`"]):m.push(["str",/^(?:'(?:[^\n\r'\\]|\\.)*(?:'|$)|"(?:[^\n\r"\\]|\\.)*(?:"|$))/,q,"\"'"]);a.verbatimStrings&&e.push(["str",/^@"(?:[^"]|"")*(?:"|$)/,q]);var h=a.hashComments;h&&(a.cStyleComments?(h>1?m.push(["com",/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,q,"#"]):m.push(["com",/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\n\r]*)/,q,"#"]),e.push(["str",/^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)>/,q])):m.push(["com",/^#[^\n\r]*/,
|
||||
q,"#"]));a.cStyleComments&&(e.push(["com",/^\/\/[^\n\r]*/,q]),e.push(["com",/^\/\*[\S\s]*?(?:\*\/|$)/,q]));a.regexLiterals&&e.push(["lang-regex",/^(?:^^\.?|[!+-]|!=|!==|#|%|%=|&|&&|&&=|&=|\(|\*|\*=|\+=|,|-=|->|\/|\/=|:|::|;|<|<<|<<=|<=|=|==|===|>|>=|>>|>>=|>>>|>>>=|[?@[^]|\^=|\^\^|\^\^=|{|\||\|=|\|\||\|\|=|~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\s*(\/(?=[^*/])(?:[^/[\\]|\\[\S\s]|\[(?:[^\\\]]|\\[\S\s])*(?:]|$))+\/)/]);(h=a.types)&&e.push(["typ",h]);a=(""+a.keywords).replace(/^ | $/g,
|
||||
"");a.length&&e.push(["kwd",RegExp("^(?:"+a.replace(/[\s,]+/g,"|")+")\\b"),q]);m.push(["pln",/^\s+/,q," \r\n\t\xa0"]);e.push(["lit",/^@[$_a-z][\w$@]*/i,q],["typ",/^(?:[@_]?[A-Z]+[a-z][\w$@]*|\w+_t\b)/,q],["pln",/^[$_a-z][\w$@]*/i,q],["lit",/^(?:0x[\da-f]+|(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d\+)(?:e[+-]?\d+)?)[a-z]*/i,q,"0123456789"],["pln",/^\\[\S\s]?/,q],["pun",/^.[^\s\w"-$'./@\\`]*/,q]);return x(m,e)}function D(a,m){function e(a){switch(a.nodeType){case 1:if(k.test(a.className))break;if("BR"===a.nodeName)h(a),
|
||||
a.parentNode&&a.parentNode.removeChild(a);else for(a=a.firstChild;a;a=a.nextSibling)e(a);break;case 3:case 4:if(p){var b=a.nodeValue,d=b.match(t);if(d){var c=b.substring(0,d.index);a.nodeValue=c;(b=b.substring(d.index+d[0].length))&&a.parentNode.insertBefore(s.createTextNode(b),a.nextSibling);h(a);c||a.parentNode.removeChild(a)}}}}function h(a){function b(a,d){var e=d?a.cloneNode(!1):a,f=a.parentNode;if(f){var f=b(f,1),g=a.nextSibling;f.appendChild(e);for(var h=g;h;h=g)g=h.nextSibling,f.appendChild(h)}return e}
|
||||
for(;!a.nextSibling;)if(a=a.parentNode,!a)return;for(var a=b(a.nextSibling,0),e;(e=a.parentNode)&&e.nodeType===1;)a=e;d.push(a)}var k=/(?:^|\s)nocode(?:\s|$)/,t=/\r\n?|\n/,s=a.ownerDocument,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&&(l=s.defaultView.getComputedStyle(a,q).getPropertyValue("white-space"));var p=l&&"pre"===l.substring(0,3);for(l=s.createElement("LI");a.firstChild;)l.appendChild(a.firstChild);for(var d=[l],g=0;g<d.length;++g)e(d[g]);m===(m|0)&&d[0].setAttribute("value",
|
||||
m);var r=s.createElement("OL");r.className="linenums";for(var n=Math.max(0,m-1|0)||0,g=0,z=d.length;g<z;++g)l=d[g],l.className="L"+(g+n)%10,l.firstChild||l.appendChild(s.createTextNode("\xa0")),r.appendChild(l);a.appendChild(r)}function k(a,m){for(var e=m.length;--e>=0;){var h=m[e];A.hasOwnProperty(h)?window.console&&console.warn("cannot override language handler %s",h):A[h]=a}}function C(a,m){if(!a||!A.hasOwnProperty(a))a=/^\s*</.test(m)?"default-markup":"default-code";return A[a]}function E(a){var m=
|
||||
a.g;try{var e=M(a.h),h=e.a;a.a=h;a.c=e.c;a.d=0;C(m,h)(a);var k=/\bMSIE\b/.test(navigator.userAgent),m=/\n/g,t=a.a,s=t.length,e=0,l=a.c,p=l.length,h=0,d=a.e,g=d.length,a=0;d[g]=s;var r,n;for(n=r=0;n<g;)d[n]!==d[n+2]?(d[r++]=d[n++],d[r++]=d[n++]):n+=2;g=r;for(n=r=0;n<g;){for(var z=d[n],f=d[n+1],b=n+2;b+2<=g&&d[b+1]===f;)b+=2;d[r++]=z;d[r++]=f;n=b}for(d.length=r;h<p;){var o=l[h+2]||s,c=d[a+2]||s,b=Math.min(o,c),i=l[h+1],j;if(i.nodeType!==1&&(j=t.substring(e,b))){k&&(j=j.replace(m,"\r"));i.nodeValue=
|
||||
j;var u=i.ownerDocument,v=u.createElement("SPAN");v.className=d[a+1];var x=i.parentNode;x.replaceChild(v,i);v.appendChild(i);e<o&&(l[h+1]=i=u.createTextNode(t.substring(b,o)),x.insertBefore(i,v.nextSibling))}e=b;e>=o&&(h+=2);e>=c&&(a+=2)}}catch(w){"console"in window&&console.log(w&&w.stack?w.stack:w)}}var v=["break,continue,do,else,for,if,return,while"],w=[[v,"auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile"],
|
||||
"catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof"],F=[w,"alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where"],G=[w,"abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient"],
|
||||
H=[G,"as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var"],w=[w,"debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN"],I=[v,"and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None"],
|
||||
J=[v,"alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END"],v=[v,"case,done,elif,esac,eval,fi,function,in,local,set,then,until"],K=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/,N=/\S/,O=u({keywords:[F,H,w,"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END"+
|
||||
I,J,v],hashComments:!0,cStyleComments:!0,multiLineStrings:!0,regexLiterals:!0}),A={};k(O,["default-code"]);k(x([],[["pln",/^[^<?]+/],["dec",/^<!\w[^>]*(?:>|$)/],["com",/^<\!--[\S\s]*?(?:--\>|$)/],["lang-",/^<\?([\S\s]+?)(?:\?>|$)/],["lang-",/^<%([\S\s]+?)(?:%>|$)/],["pun",/^(?:<[%?]|[%?]>)/],["lang-",/^<xmp\b[^>]*>([\S\s]+?)<\/xmp\b[^>]*>/i],["lang-js",/^<script\b[^>]*>([\S\s]*?)(<\/script\b[^>]*>)/i],["lang-css",/^<style\b[^>]*>([\S\s]*?)(<\/style\b[^>]*>)/i],["lang-in.tag",/^(<\/?[a-z][^<>]*>)/i]]),
|
||||
["default-markup","htm","html","mxml","xhtml","xml","xsl"]);k(x([["pln",/^\s+/,q," \t\r\n"],["atv",/^(?:"[^"]*"?|'[^']*'?)/,q,"\"'"]],[["tag",/^^<\/?[a-z](?:[\w-.:]*\w)?|\/?>$/i],["atn",/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],["lang-uq.val",/^=\s*([^\s"'>]*(?:[^\s"'/>]|\/(?=\s)))/],["pun",/^[/<->]+/],["lang-js",/^on\w+\s*=\s*"([^"]+)"/i],["lang-js",/^on\w+\s*=\s*'([^']+)'/i],["lang-js",/^on\w+\s*=\s*([^\s"'>]+)/i],["lang-css",/^style\s*=\s*"([^"]+)"/i],["lang-css",/^style\s*=\s*'([^']+)'/i],["lang-css",
|
||||
/^style\s*=\s*([^\s"'>]+)/i]]),["in.tag"]);k(x([],[["atv",/^[\S\s]+/]]),["uq.val"]);k(u({keywords:F,hashComments:!0,cStyleComments:!0,types:K}),["c","cc","cpp","cxx","cyc","m"]);k(u({keywords:"null,true,false"}),["json"]);k(u({keywords:H,hashComments:!0,cStyleComments:!0,verbatimStrings:!0,types:K}),["cs"]);k(u({keywords:G,cStyleComments:!0}),["java"]);k(u({keywords:v,hashComments:!0,multiLineStrings:!0}),["bsh","csh","sh"]);k(u({keywords:I,hashComments:!0,multiLineStrings:!0,tripleQuotedStrings:!0}),
|
||||
["cv","py"]);k(u({keywords:"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END",hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),["perl","pl","pm"]);k(u({keywords:J,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),["rb"]);k(u({keywords:w,cStyleComments:!0,regexLiterals:!0}),["js"]);k(u({keywords:"all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,true,try,unless,until,when,while,yes",
|
||||
hashComments:3,cStyleComments:!0,multilineStrings:!0,tripleQuotedStrings:!0,regexLiterals:!0}),["coffee"]);k(x([],[["str",/^[\S\s]+/]]),["regex"]);window.prettyPrintOne=function(a,m,e){var h=document.createElement("PRE");h.innerHTML=a;e&&D(h,e);E({g:m,i:e,h:h});return h.innerHTML};window.prettyPrint=function(a){function m(){for(var e=window.PR_SHOULD_USE_CONTINUATION?l.now()+250:Infinity;p<h.length&&l.now()<e;p++){var n=h[p],k=n.className;if(k.indexOf("prettyprint")>=0){var k=k.match(g),f,b;if(b=
|
||||
!k){b=n;for(var o=void 0,c=b.firstChild;c;c=c.nextSibling)var i=c.nodeType,o=i===1?o?b:c:i===3?N.test(c.nodeValue)?b:o:o;b=(f=o===b?void 0:o)&&"CODE"===f.tagName}b&&(k=f.className.match(g));k&&(k=k[1]);b=!1;for(o=n.parentNode;o;o=o.parentNode)if((o.tagName==="pre"||o.tagName==="code"||o.tagName==="xmp")&&o.className&&o.className.indexOf("prettyprint")>=0){b=!0;break}b||((b=(b=n.className.match(/\blinenums\b(?::(\d+))?/))?b[1]&&b[1].length?+b[1]:!0:!1)&&D(n,b),d={g:k,h:n,i:b},E(d))}}p<h.length?setTimeout(m,
|
||||
250):a&&a()}for(var e=[document.getElementsByTagName("pre"),document.getElementsByTagName("code"),document.getElementsByTagName("xmp")],h=[],k=0;k<e.length;++k)for(var t=0,s=e[k].length;t<s;++t)h.push(e[k][t]);var e=q,l=Date;l.now||(l={now:function(){return+new Date}});var p=0,d,g=/\blang(?:uage)?-([\w.]+)(?!\S)/;m()};window.PR={createSimpleLexer:x,registerLangHandler:k,sourceDecorator:u,PR_ATTRIB_NAME:"atn",PR_ATTRIB_VALUE:"atv",PR_COMMENT:"com",PR_DECLARATION:"dec",PR_KEYWORD:"kwd",PR_LITERAL:"lit",
|
||||
PR_NOCODE:"nocode",PR_PLAIN:"pln",PR_PUNCTUATION:"pun",PR_SOURCE:"src",PR_STRING:"str",PR_TAG:"tag",PR_TYPE:"typ"}})();
|
|
@ -1,8 +0,0 @@
|
|||
Library
|
||||
=======
|
||||
|
||||
.. toctree::
|
||||
:maxdepth: 1
|
||||
:glob:
|
||||
|
||||
library/*
|
|
@ -1,5 +0,0 @@
|
|||
:mod:`authentication`
|
||||
=====================
|
||||
|
||||
.. automodule:: authentication
|
||||
:members:
|
|
@ -1,5 +0,0 @@
|
|||
:mod:`compat`
|
||||
=====================
|
||||
|
||||
.. automodule:: compat
|
||||
:members:
|
|
@ -1,5 +0,0 @@
|
|||
:mod:`mixins`
|
||||
=====================
|
||||
|
||||
.. automodule:: mixins
|
||||
:members:
|
|
@ -1,5 +0,0 @@
|
|||
:mod:`parsers`
|
||||
==============
|
||||
|
||||
.. automodule:: parsers
|
||||
:members:
|
|
@ -1,5 +0,0 @@
|
|||
:mod:`permissions`
|
||||
=====================
|
||||
|
||||
.. automodule:: permissions
|
||||
:members:
|
|
@ -1,10 +0,0 @@
|
|||
:mod:`renderers`
|
||||
================
|
||||
|
||||
The renderers module provides a set of renderers that can be plugged in to a :class:`.Resource`.
|
||||
A renderer is responsible for taking the output of a View and serializing it to a given media type.
|
||||
A :class:`.Resource` can have a number of renderers, allow the same content to be serialized in a number
|
||||
of different formats depending on the requesting client's preferences, as specified in the HTTP Request's Accept header.
|
||||
|
||||
.. automodule:: renderers
|
||||
:members:
|
|
@ -1,5 +0,0 @@
|
|||
:mod:`resource`
|
||||
===============
|
||||
|
||||
.. automodule:: resources
|
||||
:members:
|
|
@ -1,5 +0,0 @@
|
|||
:mod:`response`
|
||||
===============
|
||||
|
||||
.. automodule:: response
|
||||
:members:
|
|
@ -1,5 +0,0 @@
|
|||
:mod:`reverse`
|
||||
================
|
||||
|
||||
.. automodule:: reverse
|
||||
:members:
|
|
@ -1,5 +0,0 @@
|
|||
:mod:`serializer`
|
||||
=================
|
||||
|
||||
.. automodule:: serializer
|
||||
:members:
|
|
@ -1,5 +0,0 @@
|
|||
:mod:`status`
|
||||
===============
|
||||
|
||||
.. automodule:: status
|
||||
:members:
|
|
@ -1,5 +0,0 @@
|
|||
:mod:`views`
|
||||
=====================
|
||||
|
||||
.. automodule:: views
|
||||
:members:
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user