Flesh out resources/routers part of tutorial

This commit is contained in:
Tom Christie 2012-09-14 12:43:14 +01:00
parent 886f8b4751
commit eb761be9d0
3 changed files with 141 additions and 8 deletions

View File

@ -76,7 +76,7 @@ The allowed request rate is determined from one of the following (in order of pr
## 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. Unauthenticted requests will fall back to using the IP address of the incoming request is used to generate a unique key to throttle against.
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. Unauthenticted 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).
@ -106,7 +106,7 @@ For example, multiple user throttle rates could be implemented by using the foll
}
}
`UserThrottle` is suitable if you want a simple global rate restriction per-user.
`UserThrottle` is suitable if you want simple global rate restrictions per-user.
## ScopedRateThrottle
@ -124,7 +124,6 @@ For example, given the following views...
throttle_scope = 'contacts'
...
class UploadView(APIView):
throttle_scope = 'uploads'
...

107
docs/topics/changelog.md Normal file
View File

@ -0,0 +1,107 @@
# Release Notes
## 2.0.0
**TODO:** Explain REST framework 2.0
## 0.4.0
* Supports Django 1.5.
* Fixes issues with 'HEAD' method.
* Allow views to specify template used by TemplateRenderer
* More consistent error responses
* Some serializer fixes
* Fix internet explorer ajax behaviour
* Minor xml and yaml fixes
* Improve setup (eg use staticfiles, not the defunct ADMIN_MEDIA_PREFIX)
* Sensible absolute URL generation, not using hacky set_script_prefix
## 0.3.3
* Added DjangoModelPermissions class to support `django.contrib.auth` style permissions.
* Use `staticfiles` for css files.
- Easier to override. Won't conflict with customised admin styles (eg grappelli)
* Templates are now nicely namespaced.
- Allows easier overriding.
* Drop implied 'pk' filter if last arg in urlconf is unnamed.
- Too magical. Explict is better than implicit.
* Saner template variable autoescaping.
* Tider setup.py
* Updated for URLObject 2.0
* Bugfixes:
- Bug with PerUserThrottling when user contains unicode chars.
## 0.3.2
* Bugfixes:
* Fix 403 for POST and PUT from the UI with UserLoggedInAuthentication (#115)
* serialize_model method in serializer.py may cause wrong value (#73)
* Fix Error when clicking OPTIONS button (#146)
* And many other fixes
* Remove short status codes
- Zen of Python: "There should be one-- and preferably only one --obvious way to do it."
* get_name, get_description become methods on the view - makes them overridable.
* Improved model mixin API - Hooks for build_query, get_instance_data, get_model, get_queryset, get_ordering
## 0.3.1
* [not documented]
## 0.3.0
* JSONP Support
* Bugfixes, including support for latest markdown release
## 0.2.4
* Fix broken IsAdminUser permission.
* OPTIONS support.
* XMLParser.
* Drop mentions of Blog, BitBucket.
## 0.2.3
* Fix some throttling bugs.
* ``X-Throttle`` header on throttling.
* Support for nesting resources on related models.
## 0.2.2
* Throttling support complete.
## 0.2.1
* Couple of simple bugfixes over 0.2.0
## 0.2.0
* Big refactoring changes since 0.1.0, ask on the discussion group if anything isn't clear.
The public API has been massively cleaned up. Expect it to be fairly stable from here on in.
* ``Resource`` becomes decoupled into ``View`` and ``Resource``, your views should now inherit from ``View``, not ``Resource``.
* The handler functions on views ``.get() .put() .post()`` etc, no longer have the ``content`` and ``auth`` args.
Use ``self.CONTENT`` inside a view to access the deserialized, validated content.
Use ``self.user`` inside a view to access the authenticated user.
* ``allowed_methods`` and ``anon_allowed_methods`` are now defunct. if a method is defined, it's available.
The ``permissions`` attribute on a ``View`` is now used to provide generic permissions checking.
Use permission classes such as ``FullAnonAccess``, ``IsAuthenticated`` or ``IsUserOrIsAnonReadOnly`` to set the permissions.
* The ``authenticators`` class becomes ``authentication``. Class names change to ``Authentication``.
* The ``emitters`` class becomes ``renderers``. Class names change to ``Renderers``.
* ``ResponseException`` becomes ``ErrorResponse``.
* The mixin classes have been nicely refactored, the basic mixins are now ``RequestMixin``, ``ResponseMixin``, ``AuthMixin``, and ``ResourceMixin``
You can reuse these mixin classes individually without using the ``View`` class.
## 0.1.1
* Final build before pulling in all the refactoring changes for 0.2, in case anyone needs to hang on to 0.1.
## 0.1.0
* Initial release.

View File

@ -1,3 +1,7 @@
In REST framework Resources classes are just View classes that don't have any handler methods bound to them. This allows us to seperate out the behaviour of the classes from how that behaviour should be bound to a set of URLs.
For instance, given our serializers
serializers.py
class BlogPostSerializer(URLModelSerializer):
@ -8,21 +12,44 @@ serializers.py
class Meta:
model = Comment
We can re-write our 4 sets of views into something more compact...
resources.py
class BlogPostResource(ModelResource):
serializer_class = BlogPostSerializer
model = BlogPost
permissions = [AdminOrAnonReadonly()]
throttles = [AnonThrottle(rate='5/min')]
permissions_classes = (permissions.IsAuthenticatedOrReadOnly,)
throttle_classes = (throttles.UserRateThrottle,)
class CommentResource(ModelResource):
serializer_class = CommentSerializer
model = Comment
permissions = [AdminOrAnonReadonly()]
throttles = [AnonThrottle(rate='5/min')]
permissions_classes = (permissions.IsAuthenticatedOrReadOnly,)
throttle_classes = (throttles.UserRateThrottle,)
Now that we're using Resources rather than Views, we don't need to design the urlconf ourselves. The conventions for wiring up resources into views and urls are handled automatically. All we need to do is register the appropriate resources with a router, and let it do the rest. Here's our re-wired `urls.py` file.
The handler methods only get bound to the actions when we define the URLConf. Here's our urls.py:
comment_root = CommentResource.as_view(actions={
'get': 'list',
'post': 'create'
})
comment_instance = CommentInstance.as_view(actions={
'get': 'retrieve',
'put': 'update',
'delete': 'destroy'
})
... # And for blog post
urlpatterns = patterns('blogpost.views',
url(r'^$', comment_root),
url(r'^(?P<pk>[0-9]+)$', comment_instance)
... # And for blog post
)
## Using Routers
Right now that hasn't really saved us a lot of code. However, now that we're using Resources rather than Views, we actually don't need to design the urlconf ourselves. The conventions for wiring up resources into views and urls can be handled automatically, using `Router` classes. All we need to do is register the appropriate resources with a router, and let it do the rest. Here's our re-wired `urls.py` file.
from blog import resources
from djangorestframework.routers import DefaultRouter