| 1 |
### DRF-extensions |
| 2 |
|
| 3 |
DRF-extensions is a collection of custom extensions for [Django REST Framework](https://github.com/tomchristie/django-rest-framework). |
| 4 |
Source repository is available at [https://github.com/chibisov/drf-extensions](https://github.com/chibisov/drf-extensions). |
| 5 |
|
| 6 |
### Viewsets |
| 7 |
|
| 8 |
Extensions for [viewsets](https://www.django-rest-framework.org/api-guide/viewsets/). |
| 9 |
|
| 10 |
#### DetailSerializerMixin |
| 11 |
|
| 12 |
This mixin lets add custom serializer for detail view. Just add mixin and specify `serializer_detail_class` attribute: |
| 13 |
|
| 14 |
from django.contrib.auth.models import User |
| 15 |
from myapps.serializers import UserSerializer, UserDetailSerializer |
| 16 |
from rest_framework_extensions.mixins import DetailSerializerMixin |
| 17 |
|
| 18 |
class UserViewSet(DetailSerializerMixin, viewsets.ReadOnlyModelViewSet): |
| 19 |
serializer_class = UserSerializer |
| 20 |
serializer_detail_class = UserDetailSerializer |
| 21 |
queryset = User.objects.all() |
| 22 |
|
| 23 |
Sometimes you need to set custom QuerySet for detail view. For example, in detail view you want to show user groups and permissions for these groups. You can make it by specifying `queryset_detail` attribute: |
| 24 |
|
| 25 |
from django.contrib.auth.models import User |
| 26 |
from myapps.serializers import UserSerializer, UserDetailSerializer |
| 27 |
from rest_framework_extensions.mixins import DetailSerializerMixin |
| 28 |
|
| 29 |
class UserViewSet(DetailSerializerMixin, viewsets.ReadOnlyModelViewSet): |
| 30 |
serializer_class = UserSerializer |
| 31 |
serializer_detail_class = UserDetailSerializer |
| 32 |
queryset = User.objects.all() |
| 33 |
queryset_detail = queryset.prefetch_related('groups__permissions') |
| 34 |
|
| 35 |
If you use `DetailSerializerMixin` and don't specify `serializer_detail_class` attribute, then `serializer_class` will be used. |
| 36 |
|
| 37 |
If you use `DetailSerializerMixin` and don't specify `queryset_detail` attribute, then `queryset` will be used. |
| 38 |
|
| 39 |
|
| 40 |
#### PaginateByMaxMixin |
| 41 |
|
| 42 |
*New in DRF-extensions 0.2.2* |
| 43 |
|
| 44 |
This mixin allows to paginate results by [max\_paginate\_by](https://www.django-rest-framework.org/api-guide/pagination#pagination-in-the-generic-views) |
| 45 |
value. This approach is useful when clients want to take as much paginated data as possible, |
| 46 |
but don't want to bother about backend limitations. |
| 47 |
|
| 48 |
from myapps.serializers import UserSerializer |
| 49 |
from rest_framework_extensions.mixins import PaginateByMaxMixin |
| 50 |
|
| 51 |
class UserViewSet(PaginateByMaxMixin, |
| 52 |
viewsets.ReadOnlyModelViewSet): |
| 53 |
max_paginate_by = 100 |
| 54 |
serializer_class = UserSerializer |
| 55 |
|
| 56 |
And now you can send requests with `?page_size=max` argument: |
| 57 |
|
| 58 |
# Request |
| 59 |
GET /users/?page_size=max HTTP/1.1 |
| 60 |
Accept: application/json |
| 61 |
|
| 62 |
# Response |
| 63 |
HTTP/1.1 200 OK |
| 64 |
Content-Type: application/json; charset=UTF-8 |
| 65 |
|
| 66 |
{ |
| 67 |
count: 1000, |
| 68 |
next: "https://localhost:8000/v1/users/?page=2&page_size=max", |
| 69 |
previous: null, |
| 70 |
results: [ |
| 71 |
...100 items... |
| 72 |
] |
| 73 |
} |
| 74 |
|
| 75 |
This mixin could be used only with Django Rest Framework >= 2.3.8, because |
| 76 |
[max\_paginate\_by](https://www.django-rest-framework.org/community/release-notes/#382) |
| 77 |
was introduced in 2.3.8 version. |
| 78 |
|
| 79 |
|
| 80 |
#### Cache/ETAG mixins |
| 81 |
|
| 82 |
<!--**ReadOnlyCacheResponseAndETAGMixin**--> |
| 83 |
|
| 84 |
<!--This mixin combines `ReadOnlyETAGMixin` and `CacheResponseMixin`. It could be used with--> |
| 85 |
<!--[ReadOnlyModelViewSet](http://www.django-rest-framework.org/api-guide/viewsets.html#readonlymodelviewset) and helps--> |
| 86 |
<!--to process caching + etag calculation for `retrieve` and `list` methods:--> |
| 87 |
|
| 88 |
<!-- from myapps.serializers import UserSerializer--> |
| 89 |
<!-- from rest_framework_extensions.mixins import (--> |
| 90 |
<!-- ReadOnlyCacheResponseAndETAGMixin--> |
| 91 |
<!-- )--> |
| 92 |
|
| 93 |
<!-- class UserViewSet(ReadOnlyCacheResponseAndETAGMixin,--> |
| 94 |
<!-- viewsets.ReadOnlyModelViewSet):--> |
| 95 |
<!-- serializer_class = UserSerializer--> |
| 96 |
|
| 97 |
<!--**CacheResponseAndETAGMixin**--> |
| 98 |
|
| 99 |
<!--This mixin combines `ETAGMixin` and `CacheResponseMixin`. It could be used with--> |
| 100 |
<!--[ModelViewSet](https://www.django-rest-framework.org/api-guide/viewsets/#modelviewset) and helps--> |
| 101 |
<!--to process:--> |
| 102 |
|
| 103 |
<!--* Caching for `retrieve` and `list` methods--> |
| 104 |
<!--* Etag for `retrieve`, `list`, `update` and `destroy` methods--> |
| 105 |
|
| 106 |
<!--Usage:--> |
| 107 |
|
| 108 |
<!-- from myapps.serializers import UserSerializer--> |
| 109 |
<!-- from rest_framework_extensions.mixins import CacheResponseAndETAGMixin--> |
| 110 |
|
| 111 |
<!-- class UserViewSet(CacheResponseAndETAGMixin,--> |
| 112 |
<!-- viewsets.ModelViewSet):--> |
| 113 |
<!-- serializer_class = UserSerializer--> |
| 114 |
|
| 115 |
<!--Please, read more about [caching](#caching), [key construction](#key-constructor) and [conditional requests](#conditional-requests).--> |
| 116 |
The etag functionality is pending an overhaul has been temporarily removed since 0.4.0. |
| 117 |
|
| 118 |
ReadOnlyCacheResponseAndETAGMixin and CacheResponseAndETAGMixin are no longer available to use. |
| 119 |
|
| 120 |
See discussion in [Issue #177](https://github.com/chibisov/drf-extensions/issues/177) |
| 121 |
|
| 122 |
### Routers |
| 123 |
|
| 124 |
Extensions for [routers](https://www.django-rest-framework.org/api-guide/routers/). |
| 125 |
|
| 126 |
You will need to use custom `ExtendedDefaultRouter` or `ExtendedSimpleRouter` for routing if you want to take advantages of described extensions. For example you have standard implementation: |
| 127 |
|
| 128 |
from rest_framework.routers import DefaultRouter |
| 129 |
router = DefaultRouter() |
| 130 |
|
| 131 |
You should replace `DefaultRouter` with `ExtendedDefaultRouter`: |
| 132 |
|
| 133 |
from rest_framework_extensions.routers import ( |
| 134 |
ExtendedDefaultRouter as DefaultRouter |
| 135 |
) |
| 136 |
router = DefaultRouter() |
| 137 |
|
| 138 |
Or `SimpleRouter` with `ExtendedSimpleRouter`: |
| 139 |
|
| 140 |
from rest_framework_extensions.routers import ( |
| 141 |
ExtendedSimpleRouter as SimpleRouter |
| 142 |
) |
| 143 |
router = SimpleRouter() |
| 144 |
|
| 145 |
#### Pluggable router mixins |
| 146 |
|
| 147 |
*New in DRF-extensions 0.2.4* |
| 148 |
|
| 149 |
Every feature in extended routers has it's own mixin. That means that you can use the only features you need in your custom |
| 150 |
routers. `ExtendedRouterMixin` has all set of drf-extensions features. For example you can use it with third-party routes: |
| 151 |
|
| 152 |
from rest_framework_extensions.routers import ExtendedRouterMixin |
| 153 |
from third_party_app.routers import SomeRouter |
| 154 |
|
| 155 |
class ExtendedSomeRouter(ExtendedRouterMixin, SomeRouter): |
| 156 |
pass |
| 157 |
|
| 158 |
### Nested routes |
| 159 |
|
| 160 |
*New in DRF-extensions 0.2.4* |
| 161 |
|
| 162 |
Nested routes allows you create nested resources with [viewsets](https://www.django-rest-framework.org/api-guide/viewsets/). |
| 163 |
|
| 164 |
For example: |
| 165 |
|
| 166 |
from rest_framework_extensions.routers import ExtendedSimpleRouter |
| 167 |
from yourapp.views import ( |
| 168 |
UserViewSet, |
| 169 |
GroupViewSet, |
| 170 |
PermissionViewSet, |
| 171 |
) |
| 172 |
|
| 173 |
router = ExtendedSimpleRouter() |
| 174 |
( |
| 175 |
router.register(r'users', UserViewSet, basename='user') |
| 176 |
.register(r'groups', |
| 177 |
GroupViewSet, |
| 178 |
basename='users-group', |
| 179 |
parents_query_lookups=['user_groups']) |
| 180 |
.register(r'permissions', |
| 181 |
PermissionViewSet, |
| 182 |
basename='users-groups-permission', |
| 183 |
parents_query_lookups=['group__user', 'group']) |
| 184 |
) |
| 185 |
urlpatterns = router.urls |
| 186 |
|
| 187 |
There is one requirement for viewsets which used in nested routers. They should add mixin `NestedViewSetMixin`. That mixin |
| 188 |
adds automatic filtering by parent lookups: |
| 189 |
|
| 190 |
# yourapp.views |
| 191 |
from rest_framework_extensions.mixins import NestedViewSetMixin |
| 192 |
|
| 193 |
class UserViewSet(NestedViewSetMixin, ModelViewSet): |
| 194 |
model = UserModel |
| 195 |
|
| 196 |
class GroupViewSet(NestedViewSetMixin, ModelViewSet): |
| 197 |
model = GroupModel |
| 198 |
|
| 199 |
class PermissionViewSet(NestedViewSetMixin, ModelViewSet): |
| 200 |
model = PermissionModel |
| 201 |
|
| 202 |
|
| 203 |
With such kind of router we have next resources: |
| 204 |
|
| 205 |
* `/users/` - list of all users. Resolve name is **user-list** |
| 206 |
* `/users/<pk>/` - user detail. Resolve name is **user-detail** |
| 207 |
* `/users/<parent_lookup_user_groups>/groups/` - list of groups for exact user. |
| 208 |
Resolve name is **users-group-list** |
| 209 |
* `/users/<parent_lookup_user_groups>/groups/<pk>/` - user group detail. If user doesn't have group then resource will |
| 210 |
be not found. Resolve name is **users-group-detail** |
| 211 |
* `/users/<parent_lookup_group__user>/groups/<parent_lookup_group>/permissions/` - list of permissions for user group. |
| 212 |
Resolve name is **users-groups-permission-list** |
| 213 |
* `/users/<parent_lookup_group__user>/groups/<parent_lookup_group>/permissions/<pk>/` - user group permission detail. |
| 214 |
If user doesn't have group or group doesn't have permission then resource will be not found. |
| 215 |
Resolve name is **users-groups-permission-detail** |
| 216 |
|
| 217 |
Every resource is automatically filtered by parent lookups. |
| 218 |
|
| 219 |
# Request |
| 220 |
GET /users/1/groups/2/permissions/ HTTP/1.1 |
| 221 |
Accept: application/json |
| 222 |
|
| 223 |
# Response |
| 224 |
HTTP/1.1 200 OK |
| 225 |
Content-Type: application/json; charset=UTF-8 |
| 226 |
|
| 227 |
|
| 228 |
[ |
| 229 |
{ |
| 230 |
id: 3, |
| 231 |
name: "read" |
| 232 |
}, |
| 233 |
{ |
| 234 |
id: 4, |
| 235 |
name: "update" |
| 236 |
}, |
| 237 |
{ |
| 238 |
id: 5, |
| 239 |
name: "delete" |
| 240 |
} |
| 241 |
] |
| 242 |
|
| 243 |
For request above permissions will be filtered by user with pk `1` and group with pk `2`: |
| 244 |
|
| 245 |
Permission.objects.filter(group__user=1, group=2) |
| 246 |
|
| 247 |
Example with registering more then one nested resource in one depth: |
| 248 |
|
| 249 |
permissions_routes = router.register( |
| 250 |
r'permissions', |
| 251 |
PermissionViewSet, |
| 252 |
basename='permission' |
| 253 |
) |
| 254 |
permissions_routes.register( |
| 255 |
r'groups', |
| 256 |
GroupViewSet, |
| 257 |
basename='permissions-group', |
| 258 |
parents_query_lookups=['permissions'] |
| 259 |
) |
| 260 |
permissions_routes.register( |
| 261 |
r'users', |
| 262 |
UserViewSet, |
| 263 |
basename='permissions-user', |
| 264 |
parents_query_lookups=['groups__permissions'] |
| 265 |
) |
| 266 |
|
| 267 |
With such kind of router we have next resources: |
| 268 |
|
| 269 |
* `/permissions/` - list of all permissions. Resolve name is **permission-list** |
| 270 |
* `/permissions/<pk>/` - permission detail. Resolve name is **permission-detail** |
| 271 |
* `/permissions/<parent_lookup_permissions>/groups/` - list of groups for exact permission. |
| 272 |
Resolve name is **permissions-group-list** |
| 273 |
* `/permissions/<parent_lookup_permissions>/groups/<pk>/` - permission group detail. If group doesn't have |
| 274 |
permission then resource will be not found. Resolve name is **permissions-group-detail** |
| 275 |
* `/permissions/<parent_lookup_groups__permissions>/users/` - list of users for exact permission. |
| 276 |
Resolve name is **permissions-user-list** |
| 277 |
* `/permissions/<parent_lookup_groups__permissions>/user/<pk>/` - permission user detail. If user doesn't have |
| 278 |
permission then resource will be not found. Resolve name is **permissions-user-detail** |
| 279 |
|
| 280 |
#### Nested router mixin |
| 281 |
|
| 282 |
You can use `rest_framework_extensions.routers.NestedRouterMixin` for adding nesting feature into your routers: |
| 283 |
|
| 284 |
from rest_framework_extensions.routers import NestedRouterMixin |
| 285 |
from rest_framework.routers import SimpleRouter |
| 286 |
|
| 287 |
class SimpleRouterWithNesting(NestedRouterMixin, SimpleRouter): |
| 288 |
pass |
| 289 |
|
| 290 |
#### Usage with generic relations |
| 291 |
|
| 292 |
If you want to use nested router for [generic relation](https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#generic-relations) |
| 293 |
fields, you should explicitly filter `QuerySet` by content type. |
| 294 |
|
| 295 |
For example if you have such kind of models: |
| 296 |
|
| 297 |
class Task(models.Model): |
| 298 |
title = models.CharField(max_length=30) |
| 299 |
|
| 300 |
class Book(models.Model): |
| 301 |
title = models.CharField(max_length=30) |
| 302 |
|
| 303 |
class Comment(models.Model): |
| 304 |
content_type = models.ForeignKey(ContentType) |
| 305 |
object_id = models.PositiveIntegerField() |
| 306 |
content_object = generic.GenericForeignKey() |
| 307 |
text = models.CharField(max_length=30) |
| 308 |
|
| 309 |
Lets create viewsets for that models: |
| 310 |
|
| 311 |
class TaskViewSet(NestedViewSetMixin, ModelViewSet): |
| 312 |
model = TaskModel |
| 313 |
|
| 314 |
class BookViewSet(NestedViewSetMixin, ModelViewSet): |
| 315 |
model = BookModel |
| 316 |
|
| 317 |
class CommentViewSet(NestedViewSetMixin, ModelViewSet): |
| 318 |
queryset = CommentModel.objects.all() |
| 319 |
|
| 320 |
And router like this: |
| 321 |
|
| 322 |
router = ExtendedSimpleRouter() |
| 323 |
# tasks route |
| 324 |
( |
| 325 |
router.register(r'tasks', TaskViewSet) |
| 326 |
.register(r'comments', |
| 327 |
CommentViewSet, |
| 328 |
'tasks-comment', |
| 329 |
parents_query_lookups=['object_id']) |
| 330 |
) |
| 331 |
# books route |
| 332 |
( |
| 333 |
router.register(r'books', BookViewSet) |
| 334 |
.register(r'comments', |
| 335 |
CommentViewSet, |
| 336 |
'books-comment', |
| 337 |
parents_query_lookups=['object_id']) |
| 338 |
) |
| 339 |
|
| 340 |
As you can see we've added to `parents_query_lookups` only one `object_id` value. But when you make requests to `comments` |
| 341 |
endpoint for both tasks and books routes there is no context for current content type. |
| 342 |
|
| 343 |
# Request |
| 344 |
GET /tasks/123/comments/ HTTP/1.1 |
| 345 |
Accept: application/json |
| 346 |
|
| 347 |
# Response |
| 348 |
HTTP/1.1 200 OK |
| 349 |
Content-Type: application/json; charset=UTF-8 |
| 350 |
|
| 351 |
[ |
| 352 |
{ |
| 353 |
id: 1, |
| 354 |
content_type: 1, |
| 355 |
object_id: 123, |
| 356 |
text: "Good task!" |
| 357 |
}, |
| 358 |
{ |
| 359 |
id: 2, |
| 360 |
content_type: 2, // oops. Wrong content type (for book) |
| 361 |
object_id: 123, // task and book has the same id |
| 362 |
text: "Good book!" |
| 363 |
}, |
| 364 |
] |
| 365 |
|
| 366 |
For such kind of cases you should explicitly filter `QuerySets` of nested viewsets by content type: |
| 367 |
|
| 368 |
from django.contrib.contenttypes.models import ContentType |
| 369 |
|
| 370 |
class CommentViewSet(NestedViewSetMixin, ModelViewSet): |
| 371 |
queryset = CommentModel.objects.all() |
| 372 |
|
| 373 |
class TaskCommentViewSet(CommentViewSet): |
| 374 |
def get_queryset(self): |
| 375 |
return super(TaskCommentViewSet, self).get_queryset().filter( |
| 376 |
content_type=ContentType.objects.get_for_model(TaskModel) |
| 377 |
) |
| 378 |
|
| 379 |
class BookCommentViewSet(CommentViewSet): |
| 380 |
def get_queryset(self): |
| 381 |
return super(BookCommentViewSet, self).get_queryset().filter( |
| 382 |
content_type=ContentType.objects.get_for_model(BookModel) |
| 383 |
) |
| 384 |
|
| 385 |
Lets use new viewsets in router: |
| 386 |
|
| 387 |
router = ExtendedSimpleRouter() |
| 388 |
# tasks route |
| 389 |
( |
| 390 |
router.register(r'tasks', TaskViewSet) |
| 391 |
.register(r'comments', |
| 392 |
TaskCommentViewSet, |
| 393 |
'tasks-comment', |
| 394 |
parents_query_lookups=['object_id']) |
| 395 |
) |
| 396 |
# books route |
| 397 |
( |
| 398 |
router.register(r'books', BookViewSet) |
| 399 |
.register(r'comments', |
| 400 |
BookCommentViewSet, |
| 401 |
'books-comment', |
| 402 |
parents_query_lookups=['object_id']) |
| 403 |
) |
| 404 |
|
| 405 |
|
| 406 |
### Serializers |
| 407 |
|
| 408 |
Extensions for [serializers](https://www.django-rest-framework.org/api-guide/serializers/) functionality. |
| 409 |
|
| 410 |
#### PartialUpdateSerializerMixin |
| 411 |
|
| 412 |
*New in DRF-extensions 0.2.3* |
| 413 |
|
| 414 |
By default every saving of [ModelSerializer](https://www.django-rest-framework.org/api-guide/serializers#modelserializer) |
| 415 |
saves the whole object. Even partial update just patches model instance. For example: |
| 416 |
|
| 417 |
from myapps.models import City |
| 418 |
from myapps.serializers import CitySerializer |
| 419 |
|
| 420 |
moscow = City.objects.get(pk=10) |
| 421 |
city_serializer = CitySerializer( |
| 422 |
instance=moscow, |
| 423 |
data={'country': 'USA'}, |
| 424 |
partial=True |
| 425 |
) |
| 426 |
if city_serializer.is_valid(): |
| 427 |
city_serializer.save() |
| 428 |
|
| 429 |
# equivalent to |
| 430 |
moscow.country = 'USA' |
| 431 |
moscow.save() |
| 432 |
|
| 433 |
SQL representation for previous example will be: |
| 434 |
|
| 435 |
UPDATE city SET name='Moscow', country='USA' WHERE id=1; |
| 436 |
|
| 437 |
Django's `save` method has keyword argument [update_fields](https://docs.djangoproject.com/en/dev/ref/models/instances/#specifying-which-fields-to-save). |
| 438 |
Only the fields named in that list will be updated: |
| 439 |
|
| 440 |
moscow.country = 'USA' |
| 441 |
moscow.save(update_fields=['country']) |
| 442 |
|
| 443 |
SQL representation for example with `update_fields` usage will be: |
| 444 |
|
| 445 |
UPDATE city SET country='USA' WHERE id=1; |
| 446 |
|
| 447 |
To use `update_fields` for every partial update you should mixin `PartialUpdateSerializerMixin` to your serializer: |
| 448 |
|
| 449 |
from rest_framework_extensions.serializers import ( |
| 450 |
PartialUpdateSerializerMixin |
| 451 |
) |
| 452 |
|
| 453 |
class CitySerializer(PartialUpdateSerializerMixin, |
| 454 |
serializers.ModelSerializer): |
| 455 |
class Meta: |
| 456 |
model = City |
| 457 |
|
| 458 |
### Fields |
| 459 |
|
| 460 |
Set of serializer fields that extends [default fields](https://www.django-rest-framework.org/api-guide/fields/) functionality. |
| 461 |
|
| 462 |
#### ResourceUriField |
| 463 |
|
| 464 |
Represents a hyperlinking uri that points to the detail view for that object. |
| 465 |
|
| 466 |
from rest_framework_extensions.fields import ResourceUriField |
| 467 |
|
| 468 |
class CitySerializer(serializers.ModelSerializer): |
| 469 |
resource_uri = ResourceUriField(view_name='city-detail') |
| 470 |
|
| 471 |
class Meta: |
| 472 |
model = City |
| 473 |
|
| 474 |
Request example: |
| 475 |
|
| 476 |
# Request |
| 477 |
GET /cities/268/ HTTP/1.1 |
| 478 |
Accept: application/json |
| 479 |
|
| 480 |
# Response |
| 481 |
HTTP/1.1 200 OK |
| 482 |
Content-Type: application/json; charset=UTF-8 |
| 483 |
|
| 484 |
{ |
| 485 |
id: 268, |
| 486 |
resource_uri: "http://localhost:8000/v1/cities/268/", |
| 487 |
name: "Serpuhov" |
| 488 |
} |
| 489 |
|
| 490 |
|
| 491 |
### Permissions |
| 492 |
|
| 493 |
Extensions for [permissions](http://www.django-rest-framework.org/api-guide/permissions.html). |
| 494 |
|
| 495 |
#### Object permissions |
| 496 |
|
| 497 |
*New in DRF-extensions 0.2.2* |
| 498 |
|
| 499 |
Django Rest Framework allows you to use [DjangoObjectPermissions](http://www.django-rest-framework.org/api-guide/permissions#djangoobjectpermissions) out of the box. But it has one limitation - if user has no permissions for viewing resource he will get `404` as response code. In most cases it's good approach because it solves security issues by default. But what if you wanted to return `401` or `403`? What if you wanted to say to user - "You need to be logged in for viewing current resource" or "You don't have permissions for viewing current resource"? |
| 500 |
|
| 501 |
`ExtenedDjangoObjectPermissions` will help you to be more flexible. By default it behaves as standard [DjangoObjectPermissions](http://www.django-rest-framework.org/api-guide/permissions#djangoobjectpermissions). For example, it is safe to replace `DjangoObjectPermissions` with extended permissions class: |
| 502 |
|
| 503 |
from rest_framework_extensions.permissions import ( |
| 504 |
ExtendedDjangoObjectPermissions as DjangoObjectPermissions |
| 505 |
) |
| 506 |
|
| 507 |
class CommentView(viewsets.ModelViewSet): |
| 508 |
permission_classes = (DjangoObjectPermissions,) |
| 509 |
|
| 510 |
Now every request from unauthorized user will get `404` response: |
| 511 |
|
| 512 |
# Request |
| 513 |
GET /comments/1/ HTTP/1.1 |
| 514 |
Accept: application/json |
| 515 |
|
| 516 |
# Response |
| 517 |
HTTP/1.1 404 NOT FOUND |
| 518 |
Content-Type: application/json; charset=UTF-8 |
| 519 |
|
| 520 |
{"detail": "Not found"} |
| 521 |
|
| 522 |
With `ExtenedDjangoObjectPermissions` you can disable hiding forbidden for read objects by changing `hide_forbidden_for_read_objects` attribute: |
| 523 |
|
| 524 |
from rest_framework_extensions.permissions import ( |
| 525 |
ExtendedDjangoObjectPermissions |
| 526 |
) |
| 527 |
|
| 528 |
class CommentViewObjectPermissions(ExtendedDjangoObjectPermissions): |
| 529 |
hide_forbidden_for_read_objects = False |
| 530 |
|
| 531 |
class CommentView(viewsets.ModelViewSet): |
| 532 |
permission_classes = (CommentViewObjectPermissions,) |
| 533 |
|
| 534 |
Now lets see request response for user that has no permissions for viewing `CommentView` object: |
| 535 |
|
| 536 |
# Request |
| 537 |
GET /comments/1/ HTTP/1.1 |
| 538 |
Accept: application/json |
| 539 |
|
| 540 |
# Response |
| 541 |
HTTP/1.1 403 FORBIDDEN |
| 542 |
Content-Type: application/json; charset=UTF-8 |
| 543 |
|
| 544 |
{u'detail': u'You do not have permission to perform this action.'} |
| 545 |
|
| 546 |
`ExtenedDjangoObjectPermissions` could be used only with Django Rest Framework >= 2.3.8, because [DjangoObjectPermissions](https://www.django-rest-framework.org/topics/release-notes#238) was introduced in 2.3.8 version. |
| 547 |
|
| 548 |
|
| 549 |
### Caching |
| 550 |
|
| 551 |
To cache something is to save the result of an expensive calculation so that you don't have to perform the calculation next time. Here's some pseudocode explaining how this would work for a dynamically generated api response: |
| 552 |
|
| 553 |
given a URL, try finding that API response in the cache |
| 554 |
if the response is in the cache: |
| 555 |
return the cached response |
| 556 |
else: |
| 557 |
generate the response |
| 558 |
save the generated response in the cache (for next time) |
| 559 |
return the generated response |
| 560 |
|
| 561 |
#### Cache response |
| 562 |
|
| 563 |
DRF-extensions allows you to cache api responses with simple `@cache_response` decorator. |
| 564 |
There are two requirements for decorated method: |
| 565 |
|
| 566 |
* It should be method of class which is inherited from `rest_framework.views.APIView` |
| 567 |
* It should return `rest_framework.response.Response` instance. |
| 568 |
|
| 569 |
Usage example: |
| 570 |
|
| 571 |
from rest_framework.response import Response |
| 572 |
from rest_framework import views |
| 573 |
from rest_framework_extensions.cache.decorators import ( |
| 574 |
cache_response |
| 575 |
) |
| 576 |
from myapp.models import City |
| 577 |
|
| 578 |
class CityView(views.APIView): |
| 579 |
@cache_response() |
| 580 |
def get(self, request, *args, **kwargs): |
| 581 |
cities = City.objects.all().values_list('name', flat=True) |
| 582 |
return Response(cities) |
| 583 |
|
| 584 |
If you request view first time you'll get it from processed SQL query. (~60ms response time): |
| 585 |
|
| 586 |
# Request |
| 587 |
GET /cities/ HTTP/1.1 |
| 588 |
Accept: application/json |
| 589 |
|
| 590 |
# Response |
| 591 |
HTTP/1.1 200 OK |
| 592 |
Content-Type: application/json; charset=UTF-8 |
| 593 |
|
| 594 |
['Moscow', 'London', 'Paris'] |
| 595 |
|
| 596 |
Second request will hit the cache. No sql evaluation, no database query. (~30 ms response time): |
| 597 |
|
| 598 |
# Request |
| 599 |
GET /cities/ HTTP/1.1 |
| 600 |
Accept: application/json |
| 601 |
|
| 602 |
# Response |
| 603 |
HTTP/1.1 200 OK |
| 604 |
Content-Type: application/json; charset=UTF-8 |
| 605 |
|
| 606 |
['Moscow', 'London', 'Paris'] |
| 607 |
|
| 608 |
Reduction in response time depends on calculation complexity inside your API method. Sometimes it reduces from 1 second to 10ms, sometimes you win just 10ms. |
| 609 |
|
| 610 |
*New in DRF-extensions 0.4.0* |
| 611 |
|
| 612 |
The decorator will render and discard the original DRF response in favor of Django's `HttpResponse`. This allows the cache to retain a smaller memory footprint and eliminates the need to re-render responses on each request. Furthermore it eliminates the risk for users to unknowingly cache whole Serializers and QuerySets. |
| 613 |
|
| 614 |
You can disable this behavior in your test suite by using [dummy caching](https://docs.djangoproject.com/en/stable/topics/cache/#dummy-caching-for-development) for the DRF-extensions cache (set via `DEFAULT_USE_CACHE`). |
| 615 |
#### Timeout |
| 616 |
|
| 617 |
You can specify cache timeout in seconds, providing first argument: |
| 618 |
|
| 619 |
class CityView(views.APIView): |
| 620 |
@cache_response(60 * 15) |
| 621 |
def get(self, request, *args, **kwargs): |
| 622 |
... |
| 623 |
|
| 624 |
In the above example, the result of the `get()` view will be cached for 15 minutes. |
| 625 |
|
| 626 |
If you don't specify `timeout` argument then value from `REST_FRAMEWORK_EXTENSIONS` settings will be used. By default it's `None`, which means "cache forever". You can change this default in settings: |
| 627 |
|
| 628 |
REST_FRAMEWORK_EXTENSIONS = { |
| 629 |
'DEFAULT_CACHE_RESPONSE_TIMEOUT': 60 * 15 |
| 630 |
} |
| 631 |
|
| 632 |
#### Usage of the specific cache |
| 633 |
|
| 634 |
*New in DRF-extensions 0.2.3* |
| 635 |
|
| 636 |
`@cache_response` can also take an optional keyword argument, `cache`, which directs the decorator |
| 637 |
to use a specific cache (from your [CACHES](https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-CACHES) setting) when caching results. |
| 638 |
By default, the `default` cache will be used, but you can specify any cache you want: |
| 639 |
|
| 640 |
class CityView(views.APIView): |
| 641 |
@cache_response(60 * 15, cache='special_cache') |
| 642 |
def get(self, request, *args, **kwargs): |
| 643 |
... |
| 644 |
|
| 645 |
You can specify what cache to use by default in settings: |
| 646 |
|
| 647 |
REST_FRAMEWORK_EXTENSIONS = { |
| 648 |
'DEFAULT_USE_CACHE': 'special_cache' |
| 649 |
} |
| 650 |
|
| 651 |
#### Cache key |
| 652 |
|
| 653 |
By default every cached data from `@cache_response` decorator stored by key, which calculated |
| 654 |
with [DefaultKeyConstructor](#default-key-constructor). |
| 655 |
|
| 656 |
You can change cache key by providing `key_func` argument, which must be callable: |
| 657 |
|
| 658 |
def calculate_cache_key(view_instance, view_method, |
| 659 |
request, args, kwargs): |
| 660 |
return '.'.join([ |
| 661 |
len(args), |
| 662 |
len(kwargs) |
| 663 |
]) |
| 664 |
|
| 665 |
class CityView(views.APIView): |
| 666 |
@cache_response(60 * 15, key_func=calculate_cache_key) |
| 667 |
def get(self, request, *args, **kwargs): |
| 668 |
... |
| 669 |
|
| 670 |
You can implement view method and use it for cache key calculation by specifying `key_func` argument as string: |
| 671 |
|
| 672 |
class CityView(views.APIView): |
| 673 |
@cache_response(60 * 15, key_func='calculate_cache_key') |
| 674 |
def get(self, request, *args, **kwargs): |
| 675 |
... |
| 676 |
|
| 677 |
def calculate_cache_key(self, view_instance, view_method, |
| 678 |
request, args, kwargs): |
| 679 |
return '.'.join([ |
| 680 |
len(args), |
| 681 |
len(kwargs) |
| 682 |
]) |
| 683 |
|
| 684 |
Key calculation function will be called with next parameters: |
| 685 |
|
| 686 |
* **view_instance** - view instance of decorated method |
| 687 |
* **view_method** - decorated method |
| 688 |
* **request** - decorated method request |
| 689 |
* **args** - decorated method positional arguments |
| 690 |
* **kwargs** - decorated method keyword arguments |
| 691 |
|
| 692 |
#### Default key function |
| 693 |
|
| 694 |
If `@cache_response` decorator used without key argument then default key function will be used. You can change this function in |
| 695 |
settings: |
| 696 |
|
| 697 |
REST_FRAMEWORK_EXTENSIONS = { |
| 698 |
'DEFAULT_CACHE_KEY_FUNC': |
| 699 |
'rest_framework_extensions.utils.default_cache_key_func' |
| 700 |
} |
| 701 |
|
| 702 |
`default_cache_key_func` uses [DefaultKeyConstructor](#default-key-constructor) as a base for key calculation. |
| 703 |
|
| 704 |
#### Caching errors |
| 705 |
|
| 706 |
*New in DRF-extensions 0.2.7* |
| 707 |
|
| 708 |
By default every response is cached, even failed. For example: |
| 709 |
|
| 710 |
class CityView(views.APIView): |
| 711 |
@cache_response() |
| 712 |
def get(self, request, *args, **kwargs): |
| 713 |
raise Exception("500 error comes from here") |
| 714 |
|
| 715 |
First request to `CityView.get` will fail with `500` status code error and next requests to this endpoint will |
| 716 |
return `500` error from cache. |
| 717 |
|
| 718 |
You can change this behaviour by turning off caching error responses: |
| 719 |
|
| 720 |
class CityView(views.APIView): |
| 721 |
@cache_response(cache_errors=False) |
| 722 |
def get(self, request, *args, **kwargs): |
| 723 |
raise Exception("500 error comes from here") |
| 724 |
|
| 725 |
You can change default behaviour by changing `DEFAULT_CACHE_ERRORS` setting: |
| 726 |
|
| 727 |
REST_FRAMEWORK_EXTENSIONS = { |
| 728 |
'DEFAULT_CACHE_ERRORS': False |
| 729 |
} |
| 730 |
|
| 731 |
#### CacheResponseMixin |
| 732 |
|
| 733 |
It is common to cache standard [viewset](https://www.django-rest-framework.org/api-guide/viewsets/) `retrieve` and `list` |
| 734 |
methods. That is why `CacheResponseMixin` exists. Just mix it into viewset implementation and those methods will |
| 735 |
use functions, defined in `REST_FRAMEWORK_EXTENSIONS` [settings](#settings): |
| 736 |
|
| 737 |
* *"DEFAULT\_OBJECT\_CACHE\_KEY\_FUNC"* for `retrieve` method |
| 738 |
* *"DEFAULT\_LIST\_CACHE\_KEY\_FUNC"* for `list` method |
| 739 |
|
| 740 |
By default those functions are using [DefaultKeyConstructor](#default-key-constructor) and extends it: |
| 741 |
|
| 742 |
* With `RetrieveSqlQueryKeyBit` for *"DEFAULT\_OBJECT\_CACHE\_KEY\_FUNC"* |
| 743 |
* With `ListSqlQueryKeyBit` and `PaginationKeyBit` for *"DEFAULT\_LIST\_CACHE\_KEY\_FUNC"* |
| 744 |
|
| 745 |
You can change those settings for custom cache key generation: |
| 746 |
|
| 747 |
REST_FRAMEWORK_EXTENSIONS = { |
| 748 |
'DEFAULT_OBJECT_CACHE_KEY_FUNC': |
| 749 |
'rest_framework_extensions.utils.default_object_cache_key_func', |
| 750 |
'DEFAULT_LIST_CACHE_KEY_FUNC': |
| 751 |
'rest_framework_extensions.utils.default_list_cache_key_func', |
| 752 |
'DEFAULT_CACHE_RESPONSE_TIMEOUT': None, |
| 753 |
} |
| 754 |
|
| 755 |
Mixin example usage: |
| 756 |
|
| 757 |
from myapps.serializers import UserSerializer |
| 758 |
from rest_framework_extensions.cache.mixins import CacheResponseMixin |
| 759 |
|
| 760 |
class UserViewSet(CacheResponseMixin, viewsets.ModelViewSet): |
| 761 |
serializer_class = UserSerializer |
| 762 |
|
| 763 |
You can change cache key function by providing `object_cache_key_func` or |
| 764 |
`list_cache_key_func` methods in view class: |
| 765 |
|
| 766 |
class UserViewSet(CacheResponseMixin, viewsets.ModelViewSet): |
| 767 |
serializer_class = UserSerializer |
| 768 |
|
| 769 |
def object_cache_key_func(self, **kwargs): |
| 770 |
return 'some key for object' |
| 771 |
|
| 772 |
def list_cache_key_func(self, **kwargs): |
| 773 |
return 'some key for list' |
| 774 |
|
| 775 |
Of course you can use custom [key constructor](#key-constructor): |
| 776 |
|
| 777 |
from yourapp.key_constructors import ( |
| 778 |
CustomObjectKeyConstructor, |
| 779 |
CustomListKeyConstructor, |
| 780 |
) |
| 781 |
|
| 782 |
class UserViewSet(CacheResponseMixin, viewsets.ModelViewSet): |
| 783 |
serializer_class = UserSerializer |
| 784 |
object_cache_key_func = CustomObjectKeyConstructor() |
| 785 |
list_cache_key_func = CustomListKeyConstructor() |
| 786 |
|
| 787 |
*New in DRF-extensions development* |
| 788 |
|
| 789 |
You can change cache timeout by providing `object_cache_timeout` or |
| 790 |
`list_cache_timeout` properties in view class: |
| 791 |
|
| 792 |
class UserViewSet(CacheResponseMixin, viewsets.ModelViewSet): |
| 793 |
serializer_class = UserSerializer |
| 794 |
object_cache_timeout = 3600 # one hours (in seconds) |
| 795 |
list_cache_timeout = 60 # one minute (in seconds) |
| 796 |
|
| 797 |
If you want to cache only `retrieve` method then you could use `rest_framework_extensions.cache.mixins.RetrieveCacheResponseMixin`. |
| 798 |
|
| 799 |
If you want to cache only `list` method then you could use `rest_framework_extensions.cache.mixins.ListCacheResponseMixin`. |
| 800 |
|
| 801 |
|
| 802 |
### Key constructors |
| 803 |
|
| 804 |
As you could see from previous section cache key calculation might seem fairly simple operation. But let's see next example. We make ordinary HTTP request to cities resource: |
| 805 |
|
| 806 |
# Request |
| 807 |
GET /cities/ HTTP/1.1 |
| 808 |
Accept: application/json |
| 809 |
|
| 810 |
# Response |
| 811 |
HTTP/1.1 200 OK |
| 812 |
Content-Type: application/json; charset=UTF-8 |
| 813 |
|
| 814 |
['Moscow', 'London', 'Paris'] |
| 815 |
|
| 816 |
By the moment all goes fine - response returned and cached. Let's make the same request requiring XML response: |
| 817 |
|
| 818 |
# Request |
| 819 |
GET /cities/ HTTP/1.1 |
| 820 |
Accept: application/xml |
| 821 |
|
| 822 |
# Response |
| 823 |
HTTP/1.1 200 OK |
| 824 |
Content-Type: application/json; charset=UTF-8 |
| 825 |
|
| 826 |
['Moscow', 'London', 'Paris'] |
| 827 |
|
| 828 |
What is that? Oh, we forgot about format negotiations. We can add format to key bits: |
| 829 |
|
| 830 |
def calculate_cache_key(view_instance, view_method, |
| 831 |
request, args, kwargs): |
| 832 |
return '.'.join([ |
| 833 |
len(args), |
| 834 |
len(kwargs), |
| 835 |
request.accepted_renderer.format # here it is |
| 836 |
]) |
| 837 |
|
| 838 |
# Request |
| 839 |
GET /cities/ HTTP/1.1 |
| 840 |
Accept: application/xml |
| 841 |
|
| 842 |
# Response |
| 843 |
HTTP/1.1 200 OK |
| 844 |
Content-Type: application/xml; charset=UTF-8 |
| 845 |
|
| 846 |
<?xml version="1.0" encoding="utf-8"?> |
| 847 |
<root> |
| 848 |
<list-item>Moscow</list-item> |
| 849 |
<list-item>London</list-item> |
| 850 |
<list-item>Paris</list-item> |
| 851 |
</root> |
| 852 |
|
| 853 |
That's cool now - we have different responses for different formats with different cache keys. But there are many cases, where key should be different for different requests: |
| 854 |
|
| 855 |
* Response format (json, xml); |
| 856 |
* User (exact authorized user or anonymous); |
| 857 |
* Different request meta data (request.META['REMOTE_ADDR']); |
| 858 |
* Language (ru, en); |
| 859 |
* Headers; |
| 860 |
* Query params. For example, `jsonp` resources need `callback` param, which rendered in response; |
| 861 |
* Pagination. We should show different data for different pages; |
| 862 |
* Etc... |
| 863 |
|
| 864 |
Of course we can use custom `calculate_cache_key` methods and reuse them for different API methods, but we can't reuse just parts of them. For example, one method depends on user id and language, but another only on user id. How to be more DRYish? Let's see some magic: |
| 865 |
|
| 866 |
from rest_framework_extensions.key_constructor.constructors import ( |
| 867 |
KeyConstructor |
| 868 |
) |
| 869 |
from rest_framework_extensions.key_constructor import bits |
| 870 |
from your_app.utils import get_city_by_ip |
| 871 |
|
| 872 |
class CityGetKeyConstructor(KeyConstructor): |
| 873 |
unique_method_id = bits.UniqueMethodIdKeyBit() |
| 874 |
format = bits.FormatKeyBit() |
| 875 |
language = bits.LanguageKeyBit() |
| 876 |
|
| 877 |
class CityHeadKeyConstructor(CityGetKeyConstructor): |
| 878 |
user = bits.UserKeyBit() |
| 879 |
request_meta = bits.RequestMetaKeyBit(params=['REMOTE_ADDR']) |
| 880 |
|
| 881 |
class CityView(views.APIView): |
| 882 |
@cache_response(key_func=CityGetKeyConstructor()) |
| 883 |
def get(self, request, *args, **kwargs): |
| 884 |
cities = City.objects.all().values_list('name', flat=True) |
| 885 |
return Response(cities) |
| 886 |
|
| 887 |
@cache_response(key_func=CityHeadKeyConstructor()) |
| 888 |
def head(self, request, *args, **kwargs): |
| 889 |
city = '' |
| 890 |
user = self.request.user |
| 891 |
if user.is_authenticated and user.city: |
| 892 |
city = Response(user.city.name) |
| 893 |
if not city: |
| 894 |
city = get_city_by_ip(request.META['REMOTE_ADDR']) |
| 895 |
return Response(city) |
| 896 |
|
| 897 |
Firstly, let's revise `CityView.get` method cache key calculation. It constructs from 3 bits: |
| 898 |
|
| 899 |
* **unique\_method\_id** - remember our [default key calculation](#cache-key)? Here it is. Just one of the cache key bits. `head` method has different set of bits and they can't collide with `get` method bits. But there could be another view class with the same bits. |
| 900 |
* **format** - key would be different for different formats. |
| 901 |
* **language** - key would be different for different languages. |
| 902 |
|
| 903 |
The second method `head` has the same `unique_method_id`, `format` and `language` bits, buts extends with 2 more: |
| 904 |
|
| 905 |
* **user** - key would be different for different users. As you can see in response calculation we use `request.user` instance. For different users we need different responses. |
| 906 |
* **request_meta** - key would be different for different ip addresses. As you can see in response calculation we are falling back to getting city from ip address if couldn't get it from authorized user model. |
| 907 |
|
| 908 |
All default key bits are listed in [this section](#default-key-bits). |
| 909 |
|
| 910 |
#### Default key constructor |
| 911 |
|
| 912 |
`DefaultKeyConstructor` is located in `rest_framework_extensions.key_constructor.constructors` module and constructs a key |
| 913 |
from unique *method* id, request format and request language. It has the following implementation: |
| 914 |
|
| 915 |
class DefaultKeyConstructor(KeyConstructor): |
| 916 |
unique_method_id = bits.UniqueMethodIdKeyBit() |
| 917 |
format = bits.FormatKeyBit() |
| 918 |
language = bits.LanguageKeyBit() |
| 919 |
|
| 920 |
#### How key constructor works |
| 921 |
|
| 922 |
Key constructor class works in the same manner as the standard [django forms](https://docs.djangoproject.com/en/dev/topics/forms/) and |
| 923 |
key bits used like form fields. Lets go through key construction steps for [DefaultKeyConstructor](#default-key-constructor). |
| 924 |
|
| 925 |
Firstly, constructor starts iteration over every key bit: |
| 926 |
|
| 927 |
* **unique\_method\_id** |
| 928 |
* **format** |
| 929 |
* **language** |
| 930 |
|
| 931 |
Then constructor gets data from every key bit calling method `get_data`: |
| 932 |
|
| 933 |
* **unique\_method\_id** - `u'your_app.views.SometView.get'` |
| 934 |
* **format** - `u'json'` |
| 935 |
* **language** - `u'en'` |
| 936 |
|
| 937 |
Every key bit `get_data` method is called with next arguments: |
| 938 |
|
| 939 |
* **view_instance** - view instance of decorated method |
| 940 |
* **view_method** - decorated method |
| 941 |
* **request** - decorated method request |
| 942 |
* **args** - decorated method positional arguments |
| 943 |
* **kwargs** - decorated method keyword arguments |
| 944 |
|
| 945 |
After this it combines every key bit data to one dict, which keys are a key bits names in constructor, and values are returned data: |
| 946 |
|
| 947 |
{ |
| 948 |
'unique_method_id': u'your_app.views.SometView.get', |
| 949 |
'format': u'json', |
| 950 |
'language': u'en' |
| 951 |
} |
| 952 |
|
| 953 |
Then constructor dumps resulting dict to json: |
| 954 |
|
| 955 |
'{"unique_method_id": "your_app.views.SometView.get", "language": "en", "format": "json"}' |
| 956 |
|
| 957 |
And finally compresses json with **md5** and returns hash value: |
| 958 |
|
| 959 |
'b04f8f03c89df824e0ecd25230a90f0e0ebe184cf8c0114342e9471dd2275baa' |
| 960 |
|
| 961 |
#### Custom key bit |
| 962 |
|
| 963 |
We are going to create a simple key bit which could be used in real applications with next properties: |
| 964 |
|
| 965 |
* High read rate |
| 966 |
* Low write rate |
| 967 |
|
| 968 |
The task is - cache every read request and invalidate all cache data after write to any model, which used in API. This approach |
| 969 |
let us don't think about granular cache invalidation - just flush it after any model instance change/creation/deletion. |
| 970 |
|
| 971 |
Lets create models: |
| 972 |
|
| 973 |
# models.py |
| 974 |
from django.db import models |
| 975 |
|
| 976 |
class Group(models.Model): |
| 977 |
title = models.CharField() |
| 978 |
|
| 979 |
class Profile(models.Model): |
| 980 |
name = models.CharField() |
| 981 |
group = models.ForeignKey(Group) |
| 982 |
|
| 983 |
Define serializers: |
| 984 |
|
| 985 |
# serializers.py |
| 986 |
from yourapp.models import Group, Profile |
| 987 |
from rest_framework import serializers |
| 988 |
|
| 989 |
class GroupSerializer(serializers.ModelSerializer): |
| 990 |
class Meta: |
| 991 |
model = Group |
| 992 |
|
| 993 |
class ProfileSerializer(serializers.ModelSerializer): |
| 994 |
group = GroupSerializer() |
| 995 |
|
| 996 |
class Meta: |
| 997 |
model = Profile |
| 998 |
|
| 999 |
Create views: |
| 1000 |
|
| 1001 |
# views.py |
| 1002 |
from yourapp.serializers import GroupSerializer, ProfileSerializer |
| 1003 |
from yourapp.models import Group, Profile |
| 1004 |
|
| 1005 |
class GroupViewSet(viewsets.ReadOnlyModelViewSet): |
| 1006 |
serializer_class = GroupSerializer |
| 1007 |
queryset = Group.objects.all() |
| 1008 |
|
| 1009 |
class ProfileViewSet(viewsets.ReadOnlyModelViewSet): |
| 1010 |
serializer_class = ProfileSerializer |
| 1011 |
queryset = Profile.objects.all() |
| 1012 |
|
| 1013 |
And finally register views in router: |
| 1014 |
|
| 1015 |
# urls.py |
| 1016 |
from yourapp.views import GroupViewSet,ProfileViewSet |
| 1017 |
|
| 1018 |
router = DefaultRouter() |
| 1019 |
router.register(r'groups', GroupViewSet) |
| 1020 |
router.register(r'profiles', ProfileViewSet) |
| 1021 |
urlpatterns = router.urls |
| 1022 |
|
| 1023 |
At the moment we have API, but it's not cached. Lets cache it and create our custom key bit: |
| 1024 |
|
| 1025 |
# views.py |
| 1026 |
import datetime |
| 1027 |
from django.core.cache import cache |
| 1028 |
from django.utils.encoding import force_str |
| 1029 |
from yourapp.serializers import GroupSerializer, ProfileSerializer |
| 1030 |
from rest_framework_extensions.cache.decorators import cache_response |
| 1031 |
from rest_framework_extensions.key_constructor.constructors import ( |
| 1032 |
DefaultKeyConstructor |
| 1033 |
) |
| 1034 |
from rest_framework_extensions.key_constructor.bits import ( |
| 1035 |
KeyBitBase, |
| 1036 |
RetrieveSqlQueryKeyBit, |
| 1037 |
ListSqlQueryKeyBit, |
| 1038 |
PaginationKeyBit |
| 1039 |
) |
| 1040 |
|
| 1041 |
class UpdatedAtKeyBit(KeyBitBase): |
| 1042 |
def get_data(self, **kwargs): |
| 1043 |
key = 'api_updated_at_timestamp' |
| 1044 |
value = cache.get(key, None) |
| 1045 |
if not value: |
| 1046 |
value = datetime.datetime.utcnow() |
| 1047 |
cache.set(key, value=value) |
| 1048 |
return force_str(value) |
| 1049 |
|
| 1050 |
class CustomObjectKeyConstructor(DefaultKeyConstructor): |
| 1051 |
retrieve_sql = RetrieveSqlQueryKeyBit() |
| 1052 |
updated_at = UpdatedAtKeyBit() |
| 1053 |
|
| 1054 |
class CustomListKeyConstructor(DefaultKeyConstructor): |
| 1055 |
list_sql = ListSqlQueryKeyBit() |
| 1056 |
pagination = PaginationKeyBit() |
| 1057 |
updated_at = UpdatedAtKeyBit() |
| 1058 |
|
| 1059 |
class GroupViewSet(viewsets.ReadOnlyModelViewSet): |
| 1060 |
serializer_class = GroupSerializer |
| 1061 |
|
| 1062 |
@cache_response(key_func=CustomObjectKeyConstructor()) |
| 1063 |
def retrieve(self, *args, **kwargs): |
| 1064 |
return super(GroupViewSet, self).retrieve(*args, **kwargs) |
| 1065 |
|
| 1066 |
@cache_response(key_func=CustomListKeyConstructor()) |
| 1067 |
def list(self, *args, **kwargs): |
| 1068 |
return super(GroupViewSet, self).list(*args, **kwargs) |
| 1069 |
|
| 1070 |
class ProfileViewSet(viewsets.ReadOnlyModelViewSet): |
| 1071 |
serializer_class = ProfileSerializer |
| 1072 |
|
| 1073 |
@cache_response(key_func=CustomObjectKeyConstructor()) |
| 1074 |
def retrieve(self, *args, **kwargs): |
| 1075 |
return super(ProfileViewSet, self).retrieve(*args, **kwargs) |
| 1076 |
|
| 1077 |
@cache_response(key_func=CustomListKeyConstructor()) |
| 1078 |
def list(self, *args, **kwargs): |
| 1079 |
return super(ProfileViewSet, self).list(*args, **kwargs) |
| 1080 |
|
| 1081 |
As you can see `UpdatedAtKeyBit` just adds to key information when API models has been update last time. If there is no |
| 1082 |
information about it then new datetime will be used for key bit data. |
| 1083 |
|
| 1084 |
Lets write cache invalidation. We just connect models to standard signals and change value in cache by key `api_updated_at_timestamp`: |
| 1085 |
|
| 1086 |
# models.py |
| 1087 |
import datetime |
| 1088 |
from django.db import models |
| 1089 |
from django.db.models.signals import post_save, post_delete |
| 1090 |
|
| 1091 |
def change_api_updated_at(sender=None, instance=None, *args, **kwargs): |
| 1092 |
cache.set('api_updated_at_timestamp', datetime.datetime.utcnow()) |
| 1093 |
|
| 1094 |
class Group(models.Model): |
| 1095 |
title = models.CharField() |
| 1096 |
|
| 1097 |
class Profile(models.Model): |
| 1098 |
name = models.CharField() |
| 1099 |
group = models.ForeignKey(Group) |
| 1100 |
|
| 1101 |
for model in [Group, Profile]: |
| 1102 |
post_save.connect(receiver=change_api_updated_at, sender=model) |
| 1103 |
post_delete.connect(receiver=change_api_updated_at, sender=model) |
| 1104 |
|
| 1105 |
And that's it. When any model changes then value in cache by key `api_updated_at_timestamp` will be changed too. After this every |
| 1106 |
key constructor, that used `UpdatedAtKeyBit`, will construct new keys and `@cache_response` decorator will |
| 1107 |
cache data in new places. |
| 1108 |
|
| 1109 |
#### Key constructor params |
| 1110 |
|
| 1111 |
*New in DRF-extensions 0.2.3* |
| 1112 |
|
| 1113 |
You can change `params` attribute for specific key bit by providing `params` dict for key constructor initialization |
| 1114 |
function. For example, here is custom key constructor, which inherits from [DefaultKeyConstructor](#default-key-constructor) |
| 1115 |
and adds geoip key bit: |
| 1116 |
|
| 1117 |
class CityKeyConstructor(DefaultKeyConstructor): |
| 1118 |
geoip = bits.RequestMetaKeyBit(params=['GEOIP_CITY']) |
| 1119 |
|
| 1120 |
If you wanted to use `GEOIP_COUNTRY`, you could create new key constructor: |
| 1121 |
|
| 1122 |
class CountryKeyConstructor(DefaultKeyConstructor): |
| 1123 |
geoip = bits.RequestMetaKeyBit(params=['GEOIP_COUNTRY']) |
| 1124 |
|
| 1125 |
But there is another way. You can send `params` in key constructor initialization method. This is the dict attribute, where |
| 1126 |
keys are bit names and values are bit `params` attribute value (look at `CountryView`): |
| 1127 |
|
| 1128 |
class CityKeyConstructor(DefaultKeyConstructor): |
| 1129 |
geoip = bits.RequestMetaKeyBit(params=['GEOIP_CITY']) |
| 1130 |
|
| 1131 |
class CityView(views.APIView): |
| 1132 |
@cache_response(key_func=CityKeyConstructor()) |
| 1133 |
def get(self, request, *args, **kwargs): |
| 1134 |
... |
| 1135 |
|
| 1136 |
class CountryView(views.APIView): |
| 1137 |
@cache_response(key_func=CityKeyConstructor( |
| 1138 |
params={'geoip': ['GEOIP_COUNTRY']} |
| 1139 |
)) |
| 1140 |
def get(self, request, *args, **kwargs): |
| 1141 |
... |
| 1142 |
|
| 1143 |
If there is no item provided for key bit then default key bit `params` value will be used. |
| 1144 |
|
| 1145 |
#### Constructor's bits list |
| 1146 |
|
| 1147 |
You can dynamically change key constructor's bits list in initialization method by altering `bits` attribute: |
| 1148 |
|
| 1149 |
class CustomKeyConstructor(DefaultKeyConstructor): |
| 1150 |
def __init__(self, *args, **kwargs): |
| 1151 |
super(CustomKeyConstructor, self).__init__(*args, **kwargs) |
| 1152 |
self.bits['geoip'] = bits.RequestMetaKeyBit( |
| 1153 |
params=['GEOIP_CITY'] |
| 1154 |
) |
| 1155 |
|
| 1156 |
|
| 1157 |
### Default key bits |
| 1158 |
|
| 1159 |
Out of the box DRF-extensions has some basic key bits. They are all located in `rest_framework_extensions.key_constructor.bits` module. |
| 1160 |
|
| 1161 |
#### FormatKeyBit |
| 1162 |
|
| 1163 |
Retrieves format info from request. Usage example: |
| 1164 |
|
| 1165 |
class MyKeyConstructor(KeyConstructor): |
| 1166 |
format = FormatKeyBit() |
| 1167 |
|
| 1168 |
#### LanguageKeyBit |
| 1169 |
|
| 1170 |
Retrieves active language for request. Usage example: |
| 1171 |
|
| 1172 |
class MyKeyConstructor(KeyConstructor): |
| 1173 |
language = LanguageKeyBit() |
| 1174 |
|
| 1175 |
#### UserKeyBit |
| 1176 |
|
| 1177 |
Retrieves user id from request. If it is anonymous then returns *"anonymous"* string. Usage example: |
| 1178 |
|
| 1179 |
class MyKeyConstructor(KeyConstructor): |
| 1180 |
user = UserKeyBit() |
| 1181 |
|
| 1182 |
#### RequestMetaKeyBit |
| 1183 |
|
| 1184 |
Retrieves data from [request.META](https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpRequest.META) dict. |
| 1185 |
Usage example: |
| 1186 |
|
| 1187 |
class MyKeyConstructor(KeyConstructor): |
| 1188 |
ip_address_and_user_agent = bits.RequestMetaKeyBit( |
| 1189 |
['REMOTE_ADDR', 'HTTP_USER_AGENT'] |
| 1190 |
) |
| 1191 |
|
| 1192 |
You can use `*` for retrieving all meta data to key bit: |
| 1193 |
|
| 1194 |
*New in DRF-extensions 0.2.7* |
| 1195 |
|
| 1196 |
class MyKeyConstructor(KeyConstructor): |
| 1197 |
all_request_meta = bits.RequestMetaKeyBit('*') |
| 1198 |
|
| 1199 |
#### HeadersKeyBit |
| 1200 |
|
| 1201 |
Same as `RequestMetaKeyBit` retrieves data from [request.META](https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpRequest.META) dict. |
| 1202 |
The difference is that `HeadersKeyBit` allows to use normal header names: |
| 1203 |
|
| 1204 |
class MyKeyConstructor(KeyConstructor): |
| 1205 |
user_agent_and_geobase_id = bits.HeadersKeyBit( |
| 1206 |
['user-agent', 'x-geobase-id'] |
| 1207 |
) |
| 1208 |
# will process request.META['HTTP_USER_AGENT'] and |
| 1209 |
# request.META['HTTP_X_GEOBASE_ID'] |
| 1210 |
|
| 1211 |
You can use `*` for retrieving all headers to key bit: |
| 1212 |
|
| 1213 |
*New in DRF-extensions 0.2.7* |
| 1214 |
|
| 1215 |
class MyKeyConstructor(KeyConstructor): |
| 1216 |
all_headers = bits.HeadersKeyBit('*') |
| 1217 |
|
| 1218 |
#### ArgsKeyBit |
| 1219 |
|
| 1220 |
*New in DRF-extensions 0.2.7* |
| 1221 |
|
| 1222 |
Retrieves data from the view's positional arguments. |
| 1223 |
A list of position indices can be passed to indicate which arguments to use. For retrieving all arguments you can use `*` which is also the default value: |
| 1224 |
|
| 1225 |
class MyKeyConstructor(KeyConstructor): |
| 1226 |
args = bits.ArgsKeyBit() # will use all positional arguments |
| 1227 |
|
| 1228 |
class MyKeyConstructor(KeyConstructor): |
| 1229 |
args = bits.ArgsKeyBit('*') # same as above |
| 1230 |
|
| 1231 |
class MyKeyConstructor(KeyConstructor): |
| 1232 |
args = bits.ArgsKeyBit([0, 2]) |
| 1233 |
|
| 1234 |
#### KwargsKeyBit |
| 1235 |
|
| 1236 |
*New in DRF-extensions 0.2.7* |
| 1237 |
|
| 1238 |
Retrieves data from the views's keyword arguments. |
| 1239 |
A list of keyword argument names can be passed to indicate which kwargs to use. For retrieving all kwargs you can use `*` which is also the default value: |
| 1240 |
|
| 1241 |
class MyKeyConstructor(KeyConstructor): |
| 1242 |
kwargs = bits.KwargsKeyBit() # will use all keyword arguments |
| 1243 |
|
| 1244 |
class MyKeyConstructor(KeyConstructor): |
| 1245 |
kwargs = bits.KwargsKeyBit('*') # same as above |
| 1246 |
|
| 1247 |
class MyKeyConstructor(KeyConstructor): |
| 1248 |
kwargs = bits.KwargsKeyBit(['user_id', 'city']) |
| 1249 |
|
| 1250 |
#### QueryParamsKeyBit |
| 1251 |
|
| 1252 |
Retrieves data from [request.GET](https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpRequest.GET) dict. |
| 1253 |
Usage example: |
| 1254 |
|
| 1255 |
class MyKeyConstructor(KeyConstructor): |
| 1256 |
part_and_callback = bits.QueryParamsKeyBit( |
| 1257 |
['part', 'callback'] |
| 1258 |
) |
| 1259 |
|
| 1260 |
You can use `*` for retrieving all query params to key bit which is also the default value: |
| 1261 |
|
| 1262 |
*New in DRF-extensions 0.2.7* |
| 1263 |
|
| 1264 |
class MyKeyConstructor(KeyConstructor): |
| 1265 |
all_query_params = bits.QueryParamsKeyBit('*') # all qs parameters |
| 1266 |
|
| 1267 |
class MyKeyConstructor(KeyConstructor): |
| 1268 |
all_query_params = bits.QueryParamsKeyBit() # same as above |
| 1269 |
|
| 1270 |
#### PaginationKeyBit |
| 1271 |
|
| 1272 |
Inherits from `QueryParamsKeyBit` and returns data from used pagination params. |
| 1273 |
|
| 1274 |
class MyKeyConstructor(KeyConstructor): |
| 1275 |
pagination = bits.PaginationKeyBit() |
| 1276 |
|
| 1277 |
#### ListSqlQueryKeyBit |
| 1278 |
|
| 1279 |
Retrieves sql query for `view.filter_queryset(view.get_queryset())` filtering. |
| 1280 |
|
| 1281 |
class MyKeyConstructor(KeyConstructor): |
| 1282 |
list_sql_query = bits.ListSqlQueryKeyBit() |
| 1283 |
|
| 1284 |
#### RetrieveSqlQueryKeyBit |
| 1285 |
|
| 1286 |
Retrieves sql query for retrieving exact object. |
| 1287 |
|
| 1288 |
class MyKeyConstructor(KeyConstructor): |
| 1289 |
retrieve_sql_query = bits.RetrieveSqlQueryKeyBit() |
| 1290 |
|
| 1291 |
#### UniqueViewIdKeyBit |
| 1292 |
|
| 1293 |
Combines data about view module and view class name. |
| 1294 |
|
| 1295 |
class MyKeyConstructor(KeyConstructor): |
| 1296 |
unique_view_id = bits.UniqueViewIdKeyBit() |
| 1297 |
|
| 1298 |
#### UniqueMethodIdKeyBit |
| 1299 |
|
| 1300 |
Combines data about view module, view class name and view method name. |
| 1301 |
|
| 1302 |
class MyKeyConstructor(KeyConstructor): |
| 1303 |
unique_view_id = bits.UniqueMethodIdKeyBit() |
| 1304 |
|
| 1305 |
#### ListModelKeyBit |
| 1306 |
|
| 1307 |
*New in DRF-extensions 0.3.2* |
| 1308 |
|
| 1309 |
Computes the semantic fingerprint of a list of objects returned by `view.filter_queryset(view.get_queryset())` |
| 1310 |
using a flat representation of all objects' values. |
| 1311 |
|
| 1312 |
class MyKeyConstructor(KeyConstructor): |
| 1313 |
list_model_values = bits.ListModelKeyBit() |
| 1314 |
|
| 1315 |
#### RetrieveModelKeyBit |
| 1316 |
|
| 1317 |
*New in DRF-extensions 0.3.2* |
| 1318 |
|
| 1319 |
Computes the semantic fingerprint of a particular objects returned by `view.get_object()`. |
| 1320 |
|
| 1321 |
class MyKeyConstructor(KeyConstructor): |
| 1322 |
retrieve_model_values = bits.RetrieveModelKeyBit() |
| 1323 |
|
| 1324 |
|
| 1325 |
|
| 1326 |
|
| 1327 |
|
| 1328 |
### Conditional requests |
| 1329 |
|
| 1330 |
The etag functionality is pending an overhaul has been temporarily removed since 0.4.0. |
| 1331 |
|
| 1332 |
See discussion in [Issue #177](https://github.com/chibisov/drf-extensions/issues/177) |
| 1333 |
|
| 1334 |
<!--*This documentation section uses information from [RESTful Web Services Cookbook](http://shop.oreilly.com/product/9780596801694.do) 10-th chapter.*--> |
| 1335 |
|
| 1336 |
<!--Conditional HTTP requests allow API clients to accomplish 2 goals:--> |
| 1337 |
|
| 1338 |
<!--1. Conditional HTTP GET saves client and server [time and bandwidth](#saving-time-and-bandwidth).--> |
| 1339 |
<!--* For unsafe requests such as PUT, POST, and DELETE, conditional requests provide [concurrency control](#concurrency-control).--> |
| 1340 |
|
| 1341 |
<!--The second goal addresses the lost update problem, where a resource is altered and saved by user B while user A is still editing.--> |
| 1342 |
<!--In both cases, the 'condition' included in the request needs to be a unique identifier (e.g. unique semantic fingerprint) of the requested resource in order to detect changes.--> |
| 1343 |
<!--This fingerprint can be transient (i.e. using the cache as with `UpdatedAtKeyBit`), or persistent, i.e. computed from the model instance attribute values from the database. --> |
| 1344 |
<!--While the `UpdatedAtKeyBit` approach requires to add triggers to your models, the semantic fingerprint option is designed to be pluggable and does not require to alter your model code. --> |
| 1345 |
|
| 1346 |
|
| 1347 |
<!--#### HTTP ETag--> |
| 1348 |
|
| 1349 |
<!--*An ETag or entity tag, is part of HTTP, the protocol for the World Wide Web. --> |
| 1350 |
<!--It is one of several mechanisms that HTTP provides for web cache validation, and which allows a client to make conditional requests.* - [Wikipedia](http://en.wikipedia.org/wiki/HTTP_ETag)--> |
| 1351 |
|
| 1352 |
<!--For ETag calculation and conditional request processing you should use the decorators from `rest_framework_extensions.etag.decorators`.--> |
| 1353 |
<!--The `@etag` decorator works similar to the native [django decorator](https://docs.djangoproject.com/en/dev/topics/conditional-view-processing/).--> |
| 1354 |
|
| 1355 |
<!--<!-- THIS REFERS TO THE DEFAULT_OBJ_ETAG_FUNC --> |
| 1356 |
<!--The [default ETag function](#default-etag-function) used by the `@etag` decorator computes the value with respect to the particular view and HTTP method in the request and therefore *cannot detect changes in individual model instances*.--> |
| 1357 |
<!--If you need to compute the *semantic* fingerprint of a model independent of a particular view and method, implement your custom `etag_func`.--> |
| 1358 |
<!--Alternatively you could use the `@api_etag` decorator and specify the `viewset` in the view.--> |
| 1359 |
|
| 1360 |
|
| 1361 |
<!-- from rest_framework_extensions.etag.decorators import etag--> |
| 1362 |
|
| 1363 |
<!-- class CityView(views.APIView):--> |
| 1364 |
<!-- @etag()--> |
| 1365 |
<!-- def get(self, request, *args, **kwargs):--> |
| 1366 |
<!-- cities = City.objects.all().values_list('name', flat=True)--> |
| 1367 |
<!-- return Response(cities)--> |
| 1368 |
|
| 1369 |
<!--By default `@etag` would calculate the ETag header value with the same algorithm as [cache key](#cache-key) default calculation performs.--> |
| 1370 |
|
| 1371 |
<!-- # Request--> |
| 1372 |
<!-- GET /cities/ HTTP/1.1--> |
| 1373 |
<!-- Accept: application/json--> |
| 1374 |
|
| 1375 |
<!-- # Response--> |
| 1376 |
<!-- HTTP/1.1 200 OK--> |
| 1377 |
<!-- Content-Type: application/json; charset=UTF-8--> |
| 1378 |
<!-- ETag: "e7b50490dc546d116635a14cfa58110306dd6c5434146b6740ec08bf0a78f9a2"--> |
| 1379 |
|
| 1380 |
<!-- ['Moscow', 'London', 'Paris']--> |
| 1381 |
|
| 1382 |
<!--You can define a custom function for Etag value calculation with `etag_func` argument:--> |
| 1383 |
|
| 1384 |
<!-- from rest_framework_extensions.etag.decorators import etag--> |
| 1385 |
|
| 1386 |
<!-- def calculate_etag(view_instance, view_method,--> |
| 1387 |
<!-- request, args, kwargs):--> |
| 1388 |
<!-- return '.'.join([--> |
| 1389 |
<!-- len(args),--> |
| 1390 |
<!-- len(kwargs)--> |
| 1391 |
<!-- ])--> |
| 1392 |
|
| 1393 |
<!-- class CityView(views.APIView):--> |
| 1394 |
<!-- @etag(etag_func=calculate_etag)--> |
| 1395 |
<!-- def get(self, request, *args, **kwargs):--> |
| 1396 |
<!-- cities = City.objects.all().values_list('name', flat=True)--> |
| 1397 |
<!-- return Response(cities)--> |
| 1398 |
|
| 1399 |
|
| 1400 |
<!--You can implement a view method and use it for Etag calculation by specifying `etag_func` argument as string:--> |
| 1401 |
|
| 1402 |
<!-- from rest_framework_extensions.etag.decorators import etag--> |
| 1403 |
|
| 1404 |
<!-- class CityView(views.APIView):--> |
| 1405 |
<!-- @etag(etag_func='calculate_etag_from_method')--> |
| 1406 |
<!-- def get(self, request, *args, **kwargs):--> |
| 1407 |
<!-- cities = City.objects.all().values_list('name', flat=True)--> |
| 1408 |
<!-- return Response(cities)--> |
| 1409 |
|
| 1410 |
<!-- def calculate_etag_from_method(self, view_instance, view_method,--> |
| 1411 |
<!-- request, args, kwargs):--> |
| 1412 |
<!-- return '.'.join([--> |
| 1413 |
<!-- len(args),--> |
| 1414 |
<!-- len(kwargs)--> |
| 1415 |
<!-- ])--> |
| 1416 |
|
| 1417 |
<!--ETag calculation function will be called with following parameters:--> |
| 1418 |
|
| 1419 |
<!--* **view_instance** - view instance of decorated method--> |
| 1420 |
<!--* **view_method** - decorated method--> |
| 1421 |
<!--* **request** - decorated method request--> |
| 1422 |
<!--* **args** - decorated method positional arguments--> |
| 1423 |
<!--* **kwargs** - decorated method keyword arguments--> |
| 1424 |
|
| 1425 |
|
| 1426 |
<!--#### Default ETag function--> |
| 1427 |
|
| 1428 |
<!--If `@etag` decorator used without `etag_func` argument then default etag function will be used. You can change this function in--> |
| 1429 |
<!--settings:--> |
| 1430 |
|
| 1431 |
<!-- REST_FRAMEWORK_EXTENSIONS = {--> |
| 1432 |
<!-- 'DEFAULT_ETAG_FUNC':--> |
| 1433 |
<!-- 'rest_framework_extensions.utils.default_etag_func'--> |
| 1434 |
<!-- }--> |
| 1435 |
|
| 1436 |
<!--`default_etag_func` uses [DefaultKeyConstructor](#default-key-constructor) as a base for etag calculation.--> |
| 1437 |
|
| 1438 |
|
| 1439 |
<!--#### API ETag function--> |
| 1440 |
<!--<!-- This refers to the APIETagProcessor and @api_etag decorator --> |
| 1441 |
|
| 1442 |
<!--*New in DRF-extensions 0.3.2*--> |
| 1443 |
|
| 1444 |
<!--In addition, `APIETAGProcessor` explicitly requires a function that (ideally) creates an ETag value from model instances.--> |
| 1445 |
<!--If the `@api_etag` decorator is used without `etag_func` the framework will raise an `AssertionError`. --> |
| 1446 |
<!--Hence, the following snipped would not work:--> |
| 1447 |
|
| 1448 |
<!-- # BEGIN BAD CODE:--> |
| 1449 |
<!-- class View(views.APIView):--> |
| 1450 |
<!-- @api_etag() --> |
| 1451 |
<!-- def get(self, request, *args, **kwargs):--> |
| 1452 |
<!-- return super(View, self).get(request, *args, **kwargs)--> |
| 1453 |
<!-- # END BAD CODE--> |
| 1454 |
|
| 1455 |
<!--**Why's that?**--> |
| 1456 |
<!--It does not make sense to compute a default ETag here, because the processor would lock us out from the API by always issuing a `304` --> |
| 1457 |
<!--response on conditional requests, even if the resource was modified meanwhile.--> |
| 1458 |
<!--Therefore the `APIETAGProcessor` cannot be used without specifying an `etag_func` as keyword argument and there exists convenient --> |
| 1459 |
<!--[mixin classes](#apietagmixin).--> |
| 1460 |
|
| 1461 |
<!--You can use the decorator in regular `APIView`, and subclasses from the `rest_framework.generics` module, --> |
| 1462 |
<!--but ensure to include a `queryset` attribute or override `get_queryset()`:--> |
| 1463 |
|
| 1464 |
<!-- from rest_framework import generics--> |
| 1465 |
<!-- from rest_framework.response import Response--> |
| 1466 |
<!-- from rest_framework_extensions.utils import default_api_object_etag_func--> |
| 1467 |
<!-- from my_app.models import Book--> |
| 1468 |
|
| 1469 |
<!-- class BookCustomDestroyView(generics.DestroyAPIView): --> |
| 1470 |
<!-- # include the queryset here to enable the object lookup --> |
| 1471 |
<!-- queryset = Book.objects.all()--> |
| 1472 |
|
| 1473 |
<!-- @api_etag(etag_func=default_api_object_etag_func)--> |
| 1474 |
<!-- def delete(self, request, *args, **kwargs):--> |
| 1475 |
<!-- obj = Book.objects.get(id=kwargs['pk'])--> |
| 1476 |
<!-- # ... perform some custom operations here ...--> |
| 1477 |
<!-- obj.delete()--> |
| 1478 |
<!-- return Response(status=status.HTTP_204_NO_CONTENT)--> |
| 1479 |
|
| 1480 |
|
| 1481 |
<!--The next difference to the `@etag` decorator is that it defines an explicit map of --> |
| 1482 |
<!--required headers for each HTTP request verb, using the following default values for unsafe methods:--> |
| 1483 |
|
| 1484 |
<!-- precondition_map = {'PUT': ['If-Match'],--> |
| 1485 |
<!-- 'PATCH': ['If-Match'],--> |
| 1486 |
<!-- 'DELETE': ['If-Match']}--> |
| 1487 |
|
| 1488 |
<!--You can specify a custom set of headers in the decorator by passing the `precondition_map` keyword argument.--> |
| 1489 |
<!--For instance, this statement--> |
| 1490 |
<!-- @api_etag(etag_func=default_api_object_etag_func, precondition_map={'PUT': ['X-mycorp-custom']})--> |
| 1491 |
<!-- def put(self, request, *args, **kwargs):--> |
| 1492 |
<!-- obj = Book.objects.get(id=kwargs['pk'])--> |
| 1493 |
<!-- # ... perform some custom operations here ...--> |
| 1494 |
<!-- obj.save()--> |
| 1495 |
<!-- return Response(status=status.HTTP_200_OK)--> |
| 1496 |
|
| 1497 |
<!--checks for the presence of a custom header `X-mycorp-custom` in the request and permits the request, if it is present, --> |
| 1498 |
<!--or returns a `428 PRECONDITION REQUIRED` response.--> |
| 1499 |
|
| 1500 |
<!--Similarly, to disable all checks for a particular method simply pass an empty dict:--> |
| 1501 |
|
| 1502 |
<!-- @api_etag(etag_func=default_api_object_etag_func, precondition_map={})--> |
| 1503 |
<!-- def put(self, request, *args, **kwargs):--> |
| 1504 |
<!-- obj = Book.objects.get(id=kwargs['pk'])--> |
| 1505 |
<!-- # ... perform some custom operations here ...--> |
| 1506 |
<!-- obj.save()--> |
| 1507 |
<!-- return Response(status=status.HTTP_200_OK)--> |
| 1508 |
|
| 1509 |
<!--Please note that passing `None` in the `precondition_map` argument falls back to using the default map.--> |
| 1510 |
|
| 1511 |
<!--#### Usage ETag with caching--> |
| 1512 |
|
| 1513 |
<!--As you can see `@etag` and `@cache_response` decorators has similar key calculation approaches. --> |
| 1514 |
<!--They both can take key from simple callable function. And more than this - in many cases they share the same calculation logic. --> |
| 1515 |
<!--In the next example we use both decorators, which share one calculation function:--> |
| 1516 |
|
| 1517 |
<!-- from rest_framework_extensions.etag.decorators import etag--> |
| 1518 |
<!-- from rest_framework_extensions.cache.decorators import cache_response--> |
| 1519 |
<!-- from rest_framework_extensions.key_constructor import bits--> |
| 1520 |
<!-- from rest_framework_extensions.key_constructor.constructors import (--> |
| 1521 |
<!-- KeyConstructor--> |
| 1522 |
<!-- )--> |
| 1523 |
|
| 1524 |
<!-- class CityGetKeyConstructor(KeyConstructor):--> |
| 1525 |
<!-- format = bits.FormatKeyBit()--> |
| 1526 |
<!-- language = bits.LanguageKeyBit()--> |
| 1527 |
|
| 1528 |
<!-- class CityView(views.APIView):--> |
| 1529 |
<!-- key_constructor_func = CityGetKeyConstructor()--> |
| 1530 |
|
| 1531 |
<!-- @etag(key_constructor_func)--> |
| 1532 |
<!-- @cache_response(key_func=key_constructor_func)--> |
| 1533 |
<!-- def get(self, request, *args, **kwargs):--> |
| 1534 |
<!-- cities = City.objects.all().values_list('name', flat=True)--> |
| 1535 |
<!-- return Response(cities)--> |
| 1536 |
|
| 1537 |
<!--Note the decorators order. First goes `@etag` and then goes `@cache_response`. We want firstly perform conditional processing and after it response processing.--> |
| 1538 |
|
| 1539 |
<!--There is one more point for it. If conditional processing didn't fail then `key_constructor_func` would be called again in `@cache_response`.--> |
| 1540 |
<!--But in most cases first calculation is enough. To accomplish this goal you could use `KeyConstructor` initial argument `memoize_for_request`:--> |
| 1541 |
|
| 1542 |
<!-- >>> key_constructor_func = CityGetKeyConstructor(memoize_for_request=True)--> |
| 1543 |
<!-- >>> request1, request1 = 'request1', 'request2'--> |
| 1544 |
<!-- >>> print key_constructor_func(request=request1) # full calculation--> |
| 1545 |
<!-- request1-key--> |
| 1546 |
<!-- >>> print key_constructor_func(request=request1) # data from cache--> |
| 1547 |
<!-- request1-key--> |
| 1548 |
<!-- >>> print key_constructor_func(request=request2) # full calculation--> |
| 1549 |
<!-- request2-key--> |
| 1550 |
<!-- >>> print key_constructor_func(request=request2) # data from cache--> |
| 1551 |
<!-- request2-key--> |
| 1552 |
|
| 1553 |
<!--By default `memoize_for_request` is `False`, but you can change it in settings:--> |
| 1554 |
|
| 1555 |
<!-- REST_FRAMEWORK_EXTENSIONS = {--> |
| 1556 |
<!-- 'DEFAULT_KEY_CONSTRUCTOR_MEMOIZE_FOR_REQUEST': True--> |
| 1557 |
<!-- }--> |
| 1558 |
|
| 1559 |
|
| 1560 |
<!--It's important to note that this memoization is thread safe.--> |
| 1561 |
|
| 1562 |
<!--#### Saving time and bandwidth--> |
| 1563 |
|
| 1564 |
<!--When a server returns `ETag` header, you should store it along with the representation data on the client.--> |
| 1565 |
<!--When making GET and HEAD requests for the same resource in the future, include the `If-None-Match` header--> |
| 1566 |
<!--to make these requests "conditional". --> |
| 1567 |
|
| 1568 |
<!--For example, retrieve all cities:--> |
| 1569 |
|
| 1570 |
<!-- # Request--> |
| 1571 |
<!-- GET /cities/ HTTP/1.1--> |
| 1572 |
<!-- Accept: application/json--> |
| 1573 |
|
| 1574 |
<!-- # Response--> |
| 1575 |
<!-- HTTP/1.1 200 OK--> |
| 1576 |
<!-- Content-Type: application/json; charset=UTF-8--> |
| 1577 |
<!-- ETag: "some_etag_value"--> |
| 1578 |
|
| 1579 |
<!-- ['Moscow', 'London', 'Paris']--> |
| 1580 |
|
| 1581 |
<!--If you make same request with `If-None-Match` and there exists a cached value for this request,--> |
| 1582 |
<!--then server will respond with `304` status code without body data.--> |
| 1583 |
|
| 1584 |
<!-- # Request--> |
| 1585 |
<!-- GET /cities/ HTTP/1.1--> |
| 1586 |
<!-- Accept: application/json--> |
| 1587 |
<!-- If-None-Match: some_etag_value--> |
| 1588 |
|
| 1589 |
<!-- # Response--> |
| 1590 |
<!-- HTTP/1.1 304 NOT MODIFIED--> |
| 1591 |
<!-- Content-Type: application/json; charset=UTF-8--> |
| 1592 |
<!-- Etag: "some_etag_value"--> |
| 1593 |
|
| 1594 |
<!--After this response you can use existing cities data on the client. --> |
| 1595 |
|
| 1596 |
|
| 1597 |
|
| 1598 |
|
| 1599 |
|
| 1600 |
|
| 1601 |
|
| 1602 |
|
| 1603 |
<!--#### Concurrency control--> |
| 1604 |
|
| 1605 |
<!--Concurrency control ensures the correct processing of data under concurrent operations by clients.--> |
| 1606 |
<!--There are two ways to implement concurrency control:--> |
| 1607 |
|
| 1608 |
<!--* **Pessimistic concurrency control**. In this model, the client gets a lock, obtains--> |
| 1609 |
<!--the current state of the resource, makes modifications, and then releases the lock.--> |
| 1610 |
<!--During this process, the server prevents other clients from acquiring a lock on the same resource.--> |
| 1611 |
<!--Relational databases operate in this manner.--> |
| 1612 |
<!--* **Optimistic concurrency control**. In this model, the client first gets a token.--> |
| 1613 |
<!--Instead of obtaining a lock, the client attempts a write operation with the token included in the request.--> |
| 1614 |
<!--The operation succeeds if the token is still valid and fails otherwise.--> |
| 1615 |
|
| 1616 |
<!--HTTP, being a stateless application control, is designed for optimistic concurrency control.--> |
| 1617 |
<!--According to [RFC 6585](https://tools.ietf.org/html/rfc6585), the server can optionally require --> |
| 1618 |
<!--a condition for a request. This library returns a `428` status, if no ETag is supplied, but would be mandatory --> |
| 1619 |
<!--for a request to succeed.--> |
| 1620 |
|
| 1621 |
<!--Update:--> |
| 1622 |
|
| 1623 |
<!-- PUT/PATCH--> |
| 1624 |
<!-- +--> |
| 1625 |
<!-- +-----------+------------+--> |
| 1626 |
<!-- | ETag |--> |
| 1627 |
<!-- | supplied? |--> |
| 1628 |
<!-- ++-----------------+-----+--> |
| 1629 |
<!-- | |--> |
| 1630 |
<!-- Yes No--> |
| 1631 |
<!-- | |--> |
| 1632 |
<!-- +---------------------++ ++-------------+--> |
| 1633 |
<!-- | Do preconditions | | Precondition |--> |
| 1634 |
<!-- | match? | | required? |--> |
| 1635 |
<!-- +---+-----------------++ ++------------++--> |
| 1636 |
<!-- | | | |--> |
| 1637 |
<!-- Yes No No Yes--> |
| 1638 |
<!-- | | | |--> |
| 1639 |
<!-- +----------+------+ +-------+----------+ +---+-----+ |--> |
| 1640 |
<!-- | Does resource | | 412 Precondition | | 200 OK | |--> |
| 1641 |
<!-- | exist? | | failed | | Update | |--> |
| 1642 |
<!-- ++---------------++ +------------------+ +---------+ |--> |
| 1643 |
<!-- | | +-----------+------+--> |
| 1644 |
<!-- Yes No | 428 Precondition |--> |
| 1645 |
<!-- | | | required |--> |
| 1646 |
<!-- +----+----+ +----+----+ +------------------+--> |
| 1647 |
<!-- | 200 OK | | 404 Not |--> |
| 1648 |
<!-- | Update | | found |--> |
| 1649 |
<!-- +---------+ +---------+--> |
| 1650 |
|
| 1651 |
|
| 1652 |
<!--Delete:--> |
| 1653 |
|
| 1654 |
<!-- DELETE--> |
| 1655 |
<!-- +--> |
| 1656 |
<!-- +-----------+------------+--> |
| 1657 |
<!-- | ETag |--> |
| 1658 |
<!-- | supplied? |--> |
| 1659 |
<!-- ++-----------------+-----+--> |
| 1660 |
<!-- | |--> |
| 1661 |
<!-- Yes No--> |
| 1662 |
<!-- | |--> |
| 1663 |
<!-- +---------------------++ ++-------------+--> |
| 1664 |
<!-- | Do preconditions | | Precondition |--> |
| 1665 |
<!-- | match? | | required? |--> |
| 1666 |
<!-- +---+-----------------++ ++------------++--> |
| 1667 |
<!-- | | | |--> |
| 1668 |
<!-- Yes No No Yes--> |
| 1669 |
<!-- | | | |--> |
| 1670 |
<!-- +----------+------+ +-------+----------+ +---+-----+ |--> |
| 1671 |
<!-- | Does resource | | 412 Precondition | | 204 No | |--> |
| 1672 |
<!-- | exist? | | failed | | content | |--> |
| 1673 |
<!-- ++---------------++ +------------------+ +---------+ |--> |
| 1674 |
<!-- | | +-----------+------+--> |
| 1675 |
<!-- Yes No | 428 Precondition |--> |
| 1676 |
<!-- | | | required |--> |
| 1677 |
<!-- +----+----+ +----+----+ +------------------+--> |
| 1678 |
<!-- | 204 No | | 404 Not |--> |
| 1679 |
<!-- | content | | found |--> |
| 1680 |
<!-- +---------+ +---------+--> |
| 1681 |
|
| 1682 |
|
| 1683 |
|
| 1684 |
<!--**Example: transient key construction**--> |
| 1685 |
|
| 1686 |
<!--Here is an example implementation for all (C)RUD methods (except create, because it doesn't need concurrency control)--> |
| 1687 |
<!--wrapped with the default `etag` decorator. We use our [previous implementation](#custom-key-bit) of the `UpdatedAtKeyBit` that looks up the cache --> |
| 1688 |
<!--for the last timestamp the particular object was updated on the server. This required us to add `post_save` and `post_delete` signals--> |
| 1689 |
<!--to our models explicitly. See [below](#apietagmixin) for an example using `@api_etag` and mixins that computes the key from persistent data.--> |
| 1690 |
|
| 1691 |
<!-- from rest_framework.viewsets import ModelViewSet--> |
| 1692 |
<!-- from rest_framework_extensions.key_constructor import bits--> |
| 1693 |
<!-- from rest_framework_extensions.key_constructor.constructors import (--> |
| 1694 |
<!-- KeyConstructor--> |
| 1695 |
<!-- )--> |
| 1696 |
|
| 1697 |
<!-- from your_app.models import City--> |
| 1698 |
<!-- # use our own implementation that detects an update timestamp in the cache --> |
| 1699 |
<!-- from your_app.key_bits import UpdatedAtKeyBit--> |
| 1700 |
|
| 1701 |
<!-- class CityListKeyConstructor(KeyConstructor):--> |
| 1702 |
<!-- format = bits.FormatKeyBit()--> |
| 1703 |
<!-- language = bits.LanguageKeyBit()--> |
| 1704 |
<!-- pagination = bits.PaginationKeyBit()--> |
| 1705 |
<!-- list_sql_query = bits.ListSqlQueryKeyBit()--> |
| 1706 |
<!-- unique_view_id = bits.UniqueViewIdKeyBit()--> |
| 1707 |
|
| 1708 |
<!-- class CityDetailKeyConstructor(KeyConstructor):--> |
| 1709 |
<!-- format = bits.FormatKeyBit()--> |
| 1710 |
<!-- language = bits.LanguageKeyBit()--> |
| 1711 |
<!-- retrieve_sql_query = bits.RetrieveSqlQueryKeyBit()--> |
| 1712 |
<!-- unique_view_id = bits.UniqueViewIdKeyBit()--> |
| 1713 |
<!-- updated_at = UpdatedAtKeyBit()--> |
| 1714 |
|
| 1715 |
<!-- class CityViewSet(ModelViewSet):--> |
| 1716 |
<!-- list_key_func = CityListKeyConstructor(--> |
| 1717 |
<!-- memoize_for_request=True--> |
| 1718 |
<!-- )--> |
| 1719 |
<!-- obj_key_func = CityDetailKeyConstructor(--> |
| 1720 |
<!-- memoize_for_request=True--> |
| 1721 |
<!-- )--> |
| 1722 |
|
| 1723 |
<!-- @etag(list_key_func)--> |
| 1724 |
<!-- @cache_response(key_func=list_key_func)--> |
| 1725 |
<!-- def list(self, request, *args, **kwargs):--> |
| 1726 |
<!-- return super(CityViewSet, self).list(request, *args, **kwargs)--> |
| 1727 |
|
| 1728 |
<!-- @etag(obj_key_func)--> |
| 1729 |
<!-- @cache_response(key_func=obj_key_func)--> |
| 1730 |
<!-- def retrieve(self, request, *args, **kwargs):--> |
| 1731 |
<!-- return super(CityViewSet, self).retrieve(request, *args, **kwargs)--> |
| 1732 |
|
| 1733 |
<!-- @etag(obj_key_func)--> |
| 1734 |
<!-- def update(self, request, *args, **kwargs):--> |
| 1735 |
<!-- return super(CityViewSet, self).update(request, *args, **kwargs)--> |
| 1736 |
|
| 1737 |
<!-- @etag(obj_key_func)--> |
| 1738 |
<!-- def destroy(self, request, *args, **kwargs):--> |
| 1739 |
<!-- return super(CityViewSet, self).destroy(request, *args, **kwargs)--> |
| 1740 |
|
| 1741 |
|
| 1742 |
<!--#### ETag for unsafe methods--> |
| 1743 |
|
| 1744 |
<!--From previous section you could see that unsafe methods, such `update` (PUT, PATCH) or `destroy` (DELETE), have the same `@etag`--> |
| 1745 |
<!--decorator wrapping manner as the safe methods.--> |
| 1746 |
|
| 1747 |
<!--But every unsafe method has one distinction from safe method - it changes the data--> |
| 1748 |
<!--which could be used for Etag calculation. In our case it is `UpdatedAtKeyBit`. It means that we should calculate Etag:--> |
| 1749 |
|
| 1750 |
<!--* Before building response - for `If-Match` and `If-None-Match` conditions validation--> |
| 1751 |
<!--* After building response (if necessary) - for clients--> |
| 1752 |
|
| 1753 |
<!--`@etag` decorator has special attribute `rebuild_after_method_evaluation`, which by default is `False`.--> |
| 1754 |
|
| 1755 |
<!--If you specify `rebuild_after_method_evaluation` as `True` then Etag will be rebuilt after method evaluation:--> |
| 1756 |
|
| 1757 |
<!-- class CityViewSet(ModelViewSet):--> |
| 1758 |
<!-- ...--> |
| 1759 |
<!-- @etag(obj_key_func, rebuild_after_method_evaluation=True)--> |
| 1760 |
<!-- def update(self, request, *args, **kwargs):--> |
| 1761 |
<!-- return super(CityViewSet, self).update(request, *args, **kwargs)--> |
| 1762 |
|
| 1763 |
<!-- @etag(obj_key_func)--> |
| 1764 |
<!-- def destroy(self, request, *args, **kwargs):--> |
| 1765 |
<!-- return super(CityViewSet, self).destroy(request, *args, **kwargs)--> |
| 1766 |
|
| 1767 |
<!-- # Request--> |
| 1768 |
<!-- PUT /cities/1/ HTTP/1.1--> |
| 1769 |
<!-- Accept: application/json--> |
| 1770 |
|
| 1771 |
<!-- {"name": "London"}--> |
| 1772 |
|
| 1773 |
<!-- # Response--> |
| 1774 |
<!-- HTTP/1.1 200 OK--> |
| 1775 |
<!-- Content-Type: application/json; charset=UTF-8--> |
| 1776 |
<!-- ETag: "4e63ef056f47270272b96523f51ad938b5ea141024b767880eac047d10a0b339"--> |
| 1777 |
|
| 1778 |
<!-- {--> |
| 1779 |
<!-- id: 1,--> |
| 1780 |
<!-- name: "London"--> |
| 1781 |
<!-- }--> |
| 1782 |
|
| 1783 |
<!--As you can see we didn't specify `rebuild_after_method_evaluation` for `destroy` method. That is because there is no--> |
| 1784 |
<!--sense to use returned ETag value on clients if object deletion already performed.--> |
| 1785 |
|
| 1786 |
<!--With `rebuild_after_method_evaluation` parameter Etag calculation for `PUT`/`PATCH` method would look like:--> |
| 1787 |
|
| 1788 |
<!-- +--------------+--> |
| 1789 |
<!-- | Request |--> |
| 1790 |
<!-- +--------------+--> |
| 1791 |
<!-- |--> |
| 1792 |
<!-- +--------------------------+--> |
| 1793 |
<!-- | Calculate Etag |--> |
| 1794 |
<!-- | for condition matching |--> |
| 1795 |
<!-- +--------------------------+--> |
| 1796 |
<!-- |--> |
| 1797 |
<!-- +--------------------+--> |
| 1798 |
<!-- | Do preconditions |--> |
| 1799 |
<!-- | match? |--> |
| 1800 |
<!-- +--------------------+--> |
| 1801 |
<!-- | |--> |
| 1802 |
<!-- Yes No--> |
| 1803 |
<!-- | |--> |
| 1804 |
<!-- +--------------+ +--------------------+--> |
| 1805 |
<!-- | Update the | | 412 Precondition |--> |
| 1806 |
<!-- | resource | | failed |--> |
| 1807 |
<!-- +--------------+ +--------------------+--> |
| 1808 |
<!-- |--> |
| 1809 |
<!-- +--------------------+--> |
| 1810 |
<!-- | Calculate Etag |--> |
| 1811 |
<!-- | again and add it |--> |
| 1812 |
<!-- | to response |--> |
| 1813 |
<!-- +--------------------+--> |
| 1814 |
<!-- |--> |
| 1815 |
<!-- +------------+--> |
| 1816 |
<!-- | Return |--> |
| 1817 |
<!-- | response |--> |
| 1818 |
<!-- +------------+--> |
| 1819 |
|
| 1820 |
<!--`If-None-Match` example for `DELETE` method:--> |
| 1821 |
|
| 1822 |
<!-- # Request--> |
| 1823 |
<!-- DELETE /cities/1/ HTTP/1.1--> |
| 1824 |
<!-- Accept: application/json--> |
| 1825 |
<!-- If-None-Match: some_etag_value--> |
| 1826 |
|
| 1827 |
<!-- # Response--> |
| 1828 |
<!-- HTTP/1.1 304 NOT MODIFIED--> |
| 1829 |
<!-- Content-Type: application/json; charset=UTF-8--> |
| 1830 |
<!-- Etag: "some_etag_value"--> |
| 1831 |
|
| 1832 |
|
| 1833 |
<!--`If-Match` example for `DELETE` method:--> |
| 1834 |
|
| 1835 |
<!-- # Request--> |
| 1836 |
<!-- DELETE /cities/1/ HTTP/1.1--> |
| 1837 |
<!-- Accept: application/json--> |
| 1838 |
<!-- If-Match: another_etag_value--> |
| 1839 |
|
| 1840 |
<!-- # Response--> |
| 1841 |
<!-- HTTP/1.1 412 PRECONDITION FAILED--> |
| 1842 |
<!-- Content-Type: application/json; charset=UTF-8--> |
| 1843 |
<!-- Etag: "some_etag_value"--> |
| 1844 |
|
| 1845 |
|
| 1846 |
<!--#### ETAGMixin--> |
| 1847 |
|
| 1848 |
<!--It is common to process etags for standard [viewset](http://www.django-rest-framework.org/api-guide/viewsets)--> |
| 1849 |
<!--`retrieve`, `list`, `update` and `destroy` methods.--> |
| 1850 |
<!--That is why `ETAGMixin` exists. Just mix it into viewset--> |
| 1851 |
<!--implementation and those methods will use functions, defined in `REST_FRAMEWORK_EXTENSIONS` [settings](#settings):--> |
| 1852 |
|
| 1853 |
<!--* *"DEFAULT\_OBJECT\_ETAG\_FUNC"* for `retrieve`, `update` and `destroy` methods--> |
| 1854 |
<!--* *"DEFAULT\_LIST\_ETAG\_FUNC"* for `list` method--> |
| 1855 |
|
| 1856 |
<!--By default those functions are using [DefaultKeyConstructor](#default-key-constructor) and extends it:--> |
| 1857 |
|
| 1858 |
<!--* With `RetrieveSqlQueryKeyBit` for *"DEFAULT\_OBJECT\_ETAG\_FUNC"*--> |
| 1859 |
<!--* With `ListSqlQueryKeyBit` and `PaginationKeyBit` for *"DEFAULT\_LIST\_ETAG\_FUNC"*--> |
| 1860 |
|
| 1861 |
<!--You can change those settings for custom ETag generation:--> |
| 1862 |
|
| 1863 |
<!-- REST_FRAMEWORK_EXTENSIONS = {--> |
| 1864 |
<!-- 'DEFAULT_OBJECT_ETAG_FUNC':--> |
| 1865 |
<!-- 'rest_framework_extensions.utils.default_object_etag_func',--> |
| 1866 |
<!-- 'DEFAULT_LIST_ETAG_FUNC':--> |
| 1867 |
<!-- 'rest_framework_extensions.utils.default_list_etag_func',--> |
| 1868 |
<!-- }--> |
| 1869 |
|
| 1870 |
<!--Mixin example usage:--> |
| 1871 |
|
| 1872 |
<!-- from myapps.serializers import UserSerializer--> |
| 1873 |
<!-- from rest_framework_extensions.etag.mixins import ETAGMixin--> |
| 1874 |
|
| 1875 |
<!-- class UserViewSet(ETAGMixin, viewsets.ModelViewSet):--> |
| 1876 |
<!-- serializer_class = UserSerializer--> |
| 1877 |
|
| 1878 |
<!--You can change etag function by providing `object_etag_func` or--> |
| 1879 |
<!--`list_etag_func` methods in view class:--> |
| 1880 |
|
| 1881 |
<!-- class UserViewSet(ETAGMixin, viewsets.ModelViewSet):--> |
| 1882 |
<!-- serializer_class = UserSerializer--> |
| 1883 |
|
| 1884 |
<!-- def object_etag_func(self, **kwargs):--> |
| 1885 |
<!-- return 'some key for object'--> |
| 1886 |
|
| 1887 |
<!-- def list_etag_func(self, **kwargs):--> |
| 1888 |
<!-- return 'some key for list'--> |
| 1889 |
|
| 1890 |
<!--Of course you can use custom [key constructor](#key-constructor):--> |
| 1891 |
|
| 1892 |
<!-- from yourapp.key_constructors import (--> |
| 1893 |
<!-- CustomObjectKeyConstructor,--> |
| 1894 |
<!-- CustomListKeyConstructor,--> |
| 1895 |
<!-- )--> |
| 1896 |
|
| 1897 |
<!-- class UserViewSet(ETAGMixin, viewsets.ModelViewSet):--> |
| 1898 |
<!-- serializer_class = UserSerializer--> |
| 1899 |
<!-- object_etag_func = CustomObjectKeyConstructor()--> |
| 1900 |
<!-- list_etag_func = CustomListKeyConstructor()--> |
| 1901 |
|
| 1902 |
<!--It is important to note that ETags for unsafe method `update` is processed with parameter--> |
| 1903 |
<!--`rebuild_after_method_evaluation` equals `True`. You can read why from [this](#etag-for-unsafe-methods) section.--> |
| 1904 |
|
| 1905 |
<!--There are other mixins for more granular Etag calculation in `rest_framework_extensions.etag.mixins` module:--> |
| 1906 |
|
| 1907 |
<!--* **ReadOnlyETAGMixin** - only for `retrieve` and `list` methods--> |
| 1908 |
<!--* **RetrieveETAGMixin** - only for `retrieve` method--> |
| 1909 |
<!--* **ListETAGMixin** - only for `list` method--> |
| 1910 |
<!--* **DestroyETAGMixin** - only for `destroy` method--> |
| 1911 |
<!--* **UpdateETAGMixin** - only for `update` method--> |
| 1912 |
|
| 1913 |
|
| 1914 |
<!--#### APIETagMixin--> |
| 1915 |
|
| 1916 |
<!--*New in DRF-extensions 0.3.2*--> |
| 1917 |
|
| 1918 |
<!--In analogy to `ETAGMixin` the `APIETAGMixin` exists. Just mix it into DRF viewsets or `APIViews` --> |
| 1919 |
<!--and those methods will use the ETag functions, defined in `REST_FRAMEWORK_EXTENSIONS` [settings](#settings):--> |
| 1920 |
|
| 1921 |
<!--* *"DEFAULT\_API\_OBJECT\_ETAG\_FUNC"* for `retrieve`, `update` and `destroy` methods--> |
| 1922 |
<!--* *"DEFAULT\_API\_LIST\_ETAG\_FUNC"* for `list` method--> |
| 1923 |
|
| 1924 |
<!--By default those functions are using custom key constructors that create the key from **persisted model attributes**:--> |
| 1925 |
|
| 1926 |
<!--* `RetrieveModelKeyBit` (see [definition](#retrievemodelkeybit)) for *"DEFAULT\_API\_OBJECT\_ETAG\_FUNC"*--> |
| 1927 |
<!--* `ListModelKeyBit` (see [definition](#listmodelkeybit)) for *"DEFAULT\_API\_LIST\_ETAG\_FUNC"*--> |
| 1928 |
|
| 1929 |
<!--You can change those settings globally for your custom ETag generation, or use the default values, which should cover --> |
| 1930 |
<!--the most common use cases:--> |
| 1931 |
|
| 1932 |
<!-- REST_FRAMEWORK_EXTENSIONS = {--> |
| 1933 |
<!-- 'DEFAULT_API_OBJECT_ETAG_FUNC': --> |
| 1934 |
<!-- 'rest_framework_extensions.utils.default_api_object_etag_func',--> |
| 1935 |
<!-- 'DEFAULT_API_LIST_ETAG_FUNC': --> |
| 1936 |
<!-- 'rest_framework_extensions.utils.default_api_list_etag_func',--> |
| 1937 |
<!-- }--> |
| 1938 |
|
| 1939 |
<!--Mixin example usage:--> |
| 1940 |
|
| 1941 |
<!-- from myapps.serializers import UserSerializer--> |
| 1942 |
<!-- from rest_framework_extensions.etag.mixins import APIETAGMixin--> |
| 1943 |
|
| 1944 |
<!-- class UserViewSet(APIETAGMixin, viewsets.ModelViewSet):--> |
| 1945 |
<!-- serializer_class = UserSerializer--> |
| 1946 |
|
| 1947 |
<!--You can change etag function by providing `api_object_etag_func` or--> |
| 1948 |
<!--`api_list_etag_func` methods in view class:--> |
| 1949 |
|
| 1950 |
<!-- class UserViewSet(APIETAGMixin, viewsets.ModelViewSet):--> |
| 1951 |
<!-- serializer_class = UserSerializer--> |
| 1952 |
|
| 1953 |
<!-- def api_object_etag_func(self, **kwargs):--> |
| 1954 |
<!-- return 'some key for object'--> |
| 1955 |
|
| 1956 |
<!-- def api_list_etag_func(self, **kwargs):--> |
| 1957 |
<!-- return 'some key for list'--> |
| 1958 |
|
| 1959 |
<!--Of course you can use custom [key constructors](#key-constructor):--> |
| 1960 |
|
| 1961 |
<!-- from yourapp.key_constructors import (--> |
| 1962 |
<!-- CustomObjectKeyConstructor,--> |
| 1963 |
<!-- CustomListKeyConstructor,--> |
| 1964 |
<!-- )--> |
| 1965 |
|
| 1966 |
<!-- class UserViewSet(APIETAGMixin, viewsets.ModelViewSet):--> |
| 1967 |
<!-- serializer_class = UserSerializer--> |
| 1968 |
<!-- api_object_etag_func = CustomObjectKeyConstructor()--> |
| 1969 |
<!-- api_list_etag_func = CustomListKeyConstructor()--> |
| 1970 |
|
| 1971 |
<!--There are other mixins for more granular ETag calculation in `rest_framework_extensions.etag.mixins` module:--> |
| 1972 |
|
| 1973 |
<!--* **APIReadOnlyETAGMixin** - only for `retrieve` and `list` methods--> |
| 1974 |
<!--* **APIRetrieveETAGMixin** - only for `retrieve` method--> |
| 1975 |
<!--* **APIListETAGMixin** - only for `list` method--> |
| 1976 |
<!--* **APIDestroyETAGMixin** - only for `destroy` method--> |
| 1977 |
<!--* **APIUpdateETAGMixin** - only for `update` method--> |
| 1978 |
|
| 1979 |
<!--By default, all mixins require the conditional requests, i.e. they use the default `precondition_map` from the --> |
| 1980 |
<!--`APIETAGProcessor` class.--> |
| 1981 |
|
| 1982 |
|
| 1983 |
<!--#### Gzipped ETags--> |
| 1984 |
|
| 1985 |
<!--If you use [GZipMiddleware](https://docs.djangoproject.com/en/dev/ref/middleware/#module-django.middleware.gzip)--> |
| 1986 |
<!--and your client accepts Gzipped response, then you should return different ETags for compressed and not compressed responses.--> |
| 1987 |
<!--That's what `GZipMiddleware` does by default while processing response ---> |
| 1988 |
<!--it adds `;gzip` postfix to ETag response header if client requests compressed response.--> |
| 1989 |
<!--Lets see it in example. First request without compression:--> |
| 1990 |
|
| 1991 |
<!-- # Request--> |
| 1992 |
<!-- GET /cities/ HTTP/1.1--> |
| 1993 |
<!-- Accept: application/json--> |
| 1994 |
|
| 1995 |
<!-- # Response--> |
| 1996 |
<!-- HTTP/1.1 200 OK--> |
| 1997 |
<!-- Content-Type: application/json; charset=UTF-8--> |
| 1998 |
<!-- ETag: "e7b50490dc"--> |
| 1999 |
|
| 2000 |
<!-- ['Moscow', 'London', 'Paris']--> |
| 2001 |
|
| 2002 |
<!--Second request with compression:--> |
| 2003 |
|
| 2004 |
<!-- # Request--> |
| 2005 |
<!-- GET /cities/ HTTP/1.1--> |
| 2006 |
<!-- Accept: application/json--> |
| 2007 |
<!-- Accept-Encoding: gzip--> |
| 2008 |
|
| 2009 |
<!-- # Response--> |
| 2010 |
<!-- HTTP/1.1 200 OK--> |
| 2011 |
<!-- Content-Type: application/json--> |
| 2012 |
<!-- Content-Length: 675--> |
| 2013 |
<!-- Content-Encoding: gzip--> |
| 2014 |
<!-- ETag: "e7b50490dc;gzip"--> |
| 2015 |
|
| 2016 |
<!-- wS?n?0?_%o?cc?Ҫ?Eʒ?Cժʻ?a\1?a?^T*7q<>[Nvh?[?^9?x:/Ms?79?Fd/???ۦjES?ڽ?&??c%^?C[K۲%N?w{?졭2?m?}?Q&Egz??--> |
| 2017 |
|
| 2018 |
<!--As you can see there is `;gzip` postfix in ETag response header.--> |
| 2019 |
<!--That's ok but there is one caveat - drf-extension doesn't know how you post-processed calculated ETag value.--> |
| 2020 |
<!--And your clients could have next problem with conditional request:--> |
| 2021 |
|
| 2022 |
<!--* Client sends request to retrieve compressed data about cities to `/cities/`--> |
| 2023 |
<!--* DRF-extensions decorator calculates ETag header for response equals, for example, `123`--> |
| 2024 |
<!--* `GZipMiddleware` adds `;gzip` postfix to ETag header response, and now it equals `123;gzip`--> |
| 2025 |
<!--* Client retrieves response with ETag equals `123;gzip`--> |
| 2026 |
<!--* Client again makes request to retrieve compressed data about cities,--> |
| 2027 |
<!--but now it's conditional request with `If-None-Match` header equals `123;gzip`--> |
| 2028 |
<!--* DRF-extensions decorator calculates ETag value for processing conditional request.--> |
| 2029 |
<!--But it doesn't know, that `GZipMiddleware` added `;gzip` postfix for previous response.--> |
| 2030 |
<!--DRF-extensions decorator calculates ETag equals `123`, compares it with `123;gzip` and returns--> |
| 2031 |
<!--response with status code 200, because `123` != `123;gzip`--> |
| 2032 |
|
| 2033 |
<!--You can solve this problem by stripping `;gzip` postfix on client side.--> |
| 2034 |
|
| 2035 |
<!--But there are so many libraries that just magically uses ETag response header without allowing to--> |
| 2036 |
<!--pre-process conditional requests (for example, browser). If that's you case then you could add custom middleware which removes `;gzip`--> |
| 2037 |
<!--postfix from header:--> |
| 2038 |
|
| 2039 |
<!-- # yourapp/middleware.py--> |
| 2040 |
|
| 2041 |
<!-- class RemoveEtagGzipPostfix(object):--> |
| 2042 |
<!-- def process_response(self, request, response):--> |
| 2043 |
<!-- if response.has_header('ETag') and response['ETag'][-6:] == ';gzip"':--> |
| 2044 |
<!-- response['ETag'] = response['ETag'][:-6] + '"'--> |
| 2045 |
<!-- return response--> |
| 2046 |
|
| 2047 |
<!--Don't forget to add this middleware in your settings before `GZipMiddleware`:--> |
| 2048 |
|
| 2049 |
<!-- # settings.py--> |
| 2050 |
<!-- MIDDLEWARE_CLASSES = (--> |
| 2051 |
<!-- ...--> |
| 2052 |
<!-- 'yourapp.RemoveEtagGzipPostfix',--> |
| 2053 |
<!-- 'django.middleware.gzip.GZipMiddleware',--> |
| 2054 |
<!-- 'django.middleware.common.CommonMiddleware',--> |
| 2055 |
<!-- ...--> |
| 2056 |
<!-- )--> |
| 2057 |
|
| 2058 |
|
| 2059 |
|
| 2060 |
### Bulk operations |
| 2061 |
|
| 2062 |
*New in DRF-extensions 0.2.4* |
| 2063 |
|
| 2064 |
Bulk operations allows you to perform operations over set of objects with one request. There is third-party package |
| 2065 |
[django-rest-framework-bulk](django-rest-framework-bulk) with support for all CRUD methods, but it iterates over every |
| 2066 |
instance in bulk operation, serializes it and only after that executes operation. |
| 2067 |
|
| 2068 |
It plays nice with `create` or `update` |
| 2069 |
operations, but becomes unacceptable with `partial update` and `delete` methods over the `QuerySet`. Such kind of |
| 2070 |
`QuerySet` could contain thousands of objects and should be performed as database query over the set at once. |
| 2071 |
|
| 2072 |
Please note - DRF-extensions bulk operations applies over `QuerySet`, not over instances. It means that: |
| 2073 |
|
| 2074 |
* No serializer's `save` or `delete` methods would be called |
| 2075 |
* No viewset's `pre_save`, `post_save`, `pre_delete` and `post_delete` would be called |
| 2076 |
* No model signals would be called |
| 2077 |
|
| 2078 |
#### Safety |
| 2079 |
|
| 2080 |
Bulk operations are very dangerous in case of making stupid mistakes. For example you wanted to delete user instance |
| 2081 |
with `DELETE` request from your client application. |
| 2082 |
|
| 2083 |
# Request |
| 2084 |
DELETE /users/1/ HTTP/1.1 |
| 2085 |
Accept: application/json |
| 2086 |
|
| 2087 |
# Response |
| 2088 |
HTTP/1.1 204 NO CONTENT |
| 2089 |
Content-Type: application/json; charset=UTF-8 |
| 2090 |
|
| 2091 |
That was example of successful deletion. But there is the common situation when client could not get instance id and sends |
| 2092 |
request to endpoint without it: |
| 2093 |
|
| 2094 |
# Request |
| 2095 |
DELETE /users/ HTTP/1.1 |
| 2096 |
Accept: application/json |
| 2097 |
|
| 2098 |
# Response |
| 2099 |
HTTP/1.1 204 NO CONTENT |
| 2100 |
Content-Type: application/json; charset=UTF-8 |
| 2101 |
|
| 2102 |
If you used [bulk destroy mixin](#bulk-destroy) for `/users/` endpoint, then all your user objects would be deleted. |
| 2103 |
|
| 2104 |
To protect from such confusions DRF-extensions asks you to send `X-BULK-OPERATION` header |
| 2105 |
for every bulk operation request. With this protection previous example would not delete any user instances: |
| 2106 |
|
| 2107 |
# Request |
| 2108 |
DELETE /users/ HTTP/1.1 |
| 2109 |
Accept: application/json |
| 2110 |
|
| 2111 |
# Response |
| 2112 |
HTTP/1.1 400 BAD REQUEST |
| 2113 |
Content-Type: application/json; charset=UTF-8 |
| 2114 |
|
| 2115 |
{ |
| 2116 |
"detail": "Header 'X-BULK-OPERATION' should be provided for bulk operation." |
| 2117 |
} |
| 2118 |
|
| 2119 |
|
| 2120 |
With `X-BULK-OPERATION` header it works as expected - deletes all user instances: |
| 2121 |
|
| 2122 |
# Request |
| 2123 |
DELETE /users/ HTTP/1.1 |
| 2124 |
Accept: application/json |
| 2125 |
X-BULK-OPERATION: true |
| 2126 |
|
| 2127 |
# Response |
| 2128 |
HTTP/1.1 204 NO CONTENT |
| 2129 |
Content-Type: application/json; charset=UTF-8 |
| 2130 |
|
| 2131 |
You can change bulk operation header name in settings: |
| 2132 |
|
| 2133 |
REST_FRAMEWORK_EXTENSIONS = { |
| 2134 |
'DEFAULT_BULK_OPERATION_HEADER_NAME': 'X-CUSTOM-BULK-OPERATION' |
| 2135 |
} |
| 2136 |
|
| 2137 |
To turn off protection you can set `DEFAULT_BULK_OPERATION_HEADER_NAME` as `None`. |
| 2138 |
|
| 2139 |
#### Bulk destroy |
| 2140 |
|
| 2141 |
This mixin allows you to delete many instances with one `DELETE` request. |
| 2142 |
|
| 2143 |
from rest_framework_extensions.bulk_operations.mixins import ListDestroyModelMixin |
| 2144 |
|
| 2145 |
class UserViewSet(ListDestroyModelMixin, viewsets.ModelViewSet): |
| 2146 |
serializer_class = UserSerializer |
| 2147 |
|
| 2148 |
Bulk destroy example - delete all users which emails ends with `gmail.com`: |
| 2149 |
|
| 2150 |
# Request |
| 2151 |
DELETE /users/?email__endswith=gmail.com HTTP/1.1 |
| 2152 |
Accept: application/json |
| 2153 |
X-BULK-OPERATION: true |
| 2154 |
|
| 2155 |
# Response |
| 2156 |
HTTP/1.1 204 NO CONTENT |
| 2157 |
Content-Type: application/json; charset=UTF-8 |
| 2158 |
|
| 2159 |
#### Bulk update |
| 2160 |
|
| 2161 |
This mixin allows you to update many instances with one `PATCH` request. Note, that this mixin works only with partial update. |
| 2162 |
|
| 2163 |
from rest_framework_extensions.mixins import ListUpdateModelMixin |
| 2164 |
|
| 2165 |
class UserViewSet(ListUpdateModelMixin, viewsets.ModelViewSet): |
| 2166 |
serializer_class = UserSerializer |
| 2167 |
|
| 2168 |
Bulk partial update example - set `email_provider` of every user as `google`, if it's email ends with `gmail.com`: |
| 2169 |
|
| 2170 |
# Request |
| 2171 |
PATCH /users/?email__endswith=gmail.com HTTP/1.1 |
| 2172 |
Accept: application/json |
| 2173 |
X-BULK-OPERATION: true |
| 2174 |
|
| 2175 |
{"email_provider": "google"} |
| 2176 |
|
| 2177 |
# Response |
| 2178 |
HTTP/1.1 204 NO CONTENT |
| 2179 |
Content-Type: application/json; charset=UTF-8 |
| 2180 |
|
| 2181 |
### Settings |
| 2182 |
|
| 2183 |
DRF-extensions follows Django Rest Framework approach in settings implementation. |
| 2184 |
|
| 2185 |
[In Django Rest Framework](https://www.django-rest-framework.org/api-guide/settings/) you specify custom settings by changing `REST_FRAMEWORK` variable in settings file: |
| 2186 |
|
| 2187 |
REST_FRAMEWORK = { |
| 2188 |
'DEFAULT_RENDERER_CLASSES': ( |
| 2189 |
'rest_framework.renderers.YAMLRenderer', |
| 2190 |
), |
| 2191 |
'DEFAULT_PARSER_CLASSES': ( |
| 2192 |
'rest_framework.parsers.YAMLParser', |
| 2193 |
) |
| 2194 |
} |
| 2195 |
|
| 2196 |
In DRF-extensions there is a magic variable too called `REST_FRAMEWORK_EXTENSIONS`: |
| 2197 |
|
| 2198 |
REST_FRAMEWORK_EXTENSIONS = { |
| 2199 |
'DEFAULT_CACHE_RESPONSE_TIMEOUT': 60 * 15 |
| 2200 |
} |
| 2201 |
|
| 2202 |
#### Accessing settings |
| 2203 |
|
| 2204 |
If you need to access the values of DRF-extensions API settings in your project, you should use the `extensions_api_settings` object. For example: |
| 2205 |
|
| 2206 |
from rest_framework_extensions.settings import extensions_api_settings |
| 2207 |
|
| 2208 |
print extensions_api_settings.DEFAULT_CACHE_RESPONSE_TIMEOUT |
| 2209 |
|
| 2210 |
### Release notes |
| 2211 |
|
| 2212 |
You can read about versioning, deprecation policy and upgrading from |
| 2213 |
[Django REST framework documentation](https://www.django-rest-framework.org/community/release-notes/). |
| 2214 |
|
| 2215 |
|
| 2216 |
#### 0.8.0 |
| 2217 |
|
| 2218 |
* Added support for Django 4.2 to 5.2 |
| 2219 |
* DRF 3.15 support added |
| 2220 |
* Python 3.10 to 3.12 support added |
| 2221 |
* Removed deprecated libs |
| 2222 |
* Added handling for ValidationError while filtering queryset in NestedViewSetMixin |
| 2223 |
* Modified lookup_value to use lookup_url_kwarg aswell |
| 2224 |
* Migrated CI to Github actions |
| 2225 |
|
| 2226 |
|
| 2227 |
#### 0.7.1 |
| 2228 |
|
| 2229 |
* Added support for Django 3.2 |
| 2230 |
* Dropped drf 3.11 |
| 2231 |
|
| 2232 |
#### 0.7.0 |
| 2233 |
|
| 2234 |
* Added support for Django 3.1 |
| 2235 |
* Dropped support below Django 2.2 |
| 2236 |
* Added support for DRF 3.12 |
| 2237 |
* fix(PartialUpdateSerializerMixin): support nesting on same instance |
| 2238 |
|
| 2239 |
|
| 2240 |
|
| 2241 |
#### 0.6.0 |
| 2242 |
|
| 2243 |
*Jan 27, 2020* |
| 2244 |
|
| 2245 |
* Added support for Django 3.0 (#276) |
| 2246 |
* Dropped support for Django 2.0 |
| 2247 |
* Added support for DRF 3.10 and 3.11 (#261, #279) |
| 2248 |
* Added support for Python 3.8 (#282) |
| 2249 |
* Added paginate decorator (#266) |
| 2250 |
* Added limit/offset and cursor pagination to PaginationKeyBit (#204) |
| 2251 |
|
| 2252 |
|
| 2253 |
#### 0.5.0 |
| 2254 |
|
| 2255 |
*May 10, 2019* |
| 2256 |
|
| 2257 |
* Dropped python 2.7 and 3.4 |
| 2258 |
* Fix possible header mutation issue |
| 2259 |
* Added ability to [use a specific cache timeouts](#cacheresponsemixin) for `CacheResponseMixin` |
| 2260 |
* Test against Django 2.1, DRF 3.9 and django-filter 2.0.0 |
| 2261 |
* Dropped support of older DRF version lower than 3.9 |
| 2262 |
* Django 2.2 support added |
| 2263 |
|
| 2264 |
|
| 2265 |
#### 0.4.0 |
| 2266 |
|
| 2267 |
*Sep 5, 2018* |
| 2268 |
|
| 2269 |
* Added support for django 1.11 and 2.0 |
| 2270 |
* Dropped support for django versions lower then 1.11 |
| 2271 |
* Nested routes with over 2 levels now respect `lookup_value_regex` |
| 2272 |
* Added support for DRF 3.8 |
| 2273 |
* Dropped support of older DRF version lower then 3.8 |
| 2274 |
* Cache only the renered response instead of rendering whole response object |
| 2275 |
* The etag functionalties are not enabled by default, have to enable it manually |
| 2276 |
|
| 2277 |
|
| 2278 |
#### 0.3.2 |
| 2279 |
|
| 2280 |
*Jan 4, 2017* |
| 2281 |
|
| 2282 |
* Added `rest_framework_extensions.exceptions.PreconditionRequiredException` as subclass of `rest_framework.exceptions.APIException` |
| 2283 |
* Added `@api_etag` decorator function and `APIETAGProcessor` that uses *semantic* ETags per API resource, decoupled from views, such that it can be used in optimistic concurrency control |
| 2284 |
* Added new default key bits `RetrieveModelKeyBit` and `ListModelKeyBit` for computing the semantic fingerprint of a django model instance |
| 2285 |
* Added `APIETAGMixin` to be used in DRF viewsets and views |
| 2286 |
* Added new settings for default implementation of the API ETag functions: `DEFAULT_API_OBJECT_ETAG_FUNC`, `DEFAULT_API_LIST_ETAG_FUNC` |
| 2287 |
* Added test application for functional tests and demo as `tests_app/tests/functional/concurrency/conditional_request` |
| 2288 |
* Added unit tests for the `@api_etag` decorator |
| 2289 |
* DRF 3.5.x, Django pre-1.10 compatibility of the key bit construction |
| 2290 |
* (Test-)Code cleanup |
| 2291 |
|
| 2292 |
#### 0.3.1 |
| 2293 |
|
| 2294 |
*Sep 29, 2016* |
| 2295 |
|
| 2296 |
* Fix `schema_urls` `ExtendedDefaultRouter` compatibility issue introduced by DRF 3.4.0 |
| 2297 |
* Removed deprecated @action() and @link() decorators |
| 2298 |
* DRF 3.4.x compatibility |
| 2299 |
* Django 1.9 and 1.10 compatibility |
| 2300 |
|
| 2301 |
#### 0.2.8 |
| 2302 |
|
| 2303 |
*Sep 21, 2015* |
| 2304 |
|
| 2305 |
* Fixed `ListSqlQueryKeyBit` and `RetrieveSqlQueryKeyBit` [problems](https://github.com/chibisov/drf-extensions/issues/28) with `EmptyResultSet` exception ([pull](https://github.com/chibisov/drf-extensions/pull/75/)). |
| 2306 |
* All items are now by default in [ArgsKeyBit](#argskeybit), [KwargsKeyBit](#kwargskeybit) and [QueryParamsKeyBit](#queryparamskeybit) |
| 2307 |
* Respect parent lookup regex value for [Nested routes](#nested-routes) ([issue](https://github.com/chibisov/drf-extensions/pull/87)). |
| 2308 |
|
| 2309 |
#### 0.2.7 |
| 2310 |
|
| 2311 |
*Feb 2, 2015* |
| 2312 |
|
| 2313 |
* [DRF 3.x compatibility](https://github.com/chibisov/drf-extensions/issues/39) |
| 2314 |
* [DetailSerializerMixin](#detailserializermixin) is now [compatible with DRF 3.0](https://github.com/chibisov/drf-extensions/issues/46) |
| 2315 |
* Added [ArgsKeyBit](#argskeybit) |
| 2316 |
* Added [KwargsKeyBit](#kwargskeybit) |
| 2317 |
* Fixed [PartialUpdateSerializerMixin](#partialupdateserializermixin) [compatibility issue with DRF 3.x](https://github.com/chibisov/drf-extensions/issues/66) |
| 2318 |
* Added [cache_errors](#caching-errors) attribute for switching caching for error responses |
| 2319 |
* Added ability to specify usage of all items for [RequestMetaKeyBit](#requestmetakeybit), [HeadersKeyBit](#headerskeybit) |
| 2320 |
and [QueryParamsKeyBit](#queryparamskeybit) providing `params='*'` |
| 2321 |
* [Collection level controllers](#collection-level-controllers) is in pending deprecation |
| 2322 |
* [Controller endpoint name](#controller-endpoint-name) is in pending deprecation |
| 2323 |
|
| 2324 |
#### 0.2.6 |
| 2325 |
|
| 2326 |
*Sep 9, 2014* |
| 2327 |
|
| 2328 |
* Usage of [django.core.cache.caches](https://docs.djangoproject.com/en/dev/topics/cache/#django.core.cache.caches) for |
| 2329 |
django >= 1.7 |
| 2330 |
* [Documented ETag usage with GZipMiddleware](#gzipped-etags) |
| 2331 |
* Fixed `ListSqlQueryKeyBit` and `RetrieveSqlQueryKeyBit` [problems](https://github.com/chibisov/drf-extensions/issues/28) |
| 2332 |
with `EmptyResultSet`. |
| 2333 |
* Fixed [cache response](#cache-response) compatibility [issue](https://github.com/chibisov/drf-extensions/issues/32) |
| 2334 |
with DRF 2.4.x |
| 2335 |
|
| 2336 |
#### 0.2.5 |
| 2337 |
|
| 2338 |
*July 9, 2014* |
| 2339 |
|
| 2340 |
* Fixed [setuptools confusion with pyc files](https://github.com/chibisov/drf-extensions/issues/20) |
| 2341 |
|
| 2342 |
#### 0.2.4 |
| 2343 |
|
| 2344 |
*July 7, 2014* |
| 2345 |
|
| 2346 |
* Added tests for [Django REST Framework 2.3.14](https://www.django-rest-framework.org/topics/release-notes#2314) |
| 2347 |
* Added [Bulk operations](#bulk-operations) |
| 2348 |
* Fixed [extended routers](#routers) compatibility issue with [default controller decorators](http://www.django-rest-framework.org/api-guide/viewsets#marking-extra-methods-for-routing) |
| 2349 |
* Documented [pluggable router mixins](#pluggable-router-mixins) |
| 2350 |
* Added [nested routes](#nested-routes) |
| 2351 |
|
| 2352 |
#### 0.2.3 |
| 2353 |
|
| 2354 |
*Apr. 25, 2014* |
| 2355 |
|
| 2356 |
* Added [PartialUpdateSerializerMixin](#partialupdateserializermixin) |
| 2357 |
* Added [Key constructor params](#key-constructor-params) |
| 2358 |
* Documented dynamically [constructor's bits list](#constructor-s-bits-list) altering |
| 2359 |
* Added ability to [use a specific cache](#usage-of-the-specific-cache) for `@cache_response` decorator |
| 2360 |
|
| 2361 |
#### 0.2.2 |
| 2362 |
|
| 2363 |
*Mar. 23, 2014* |
| 2364 |
|
| 2365 |
* Added [PaginateByMaxMixin](#paginatebymaxmixin) |
| 2366 |
* Added [ExtenedDjangoObjectPermissions](#object-permissions) |
| 2367 |
* Added tests for django 1.7 |
| 2368 |
|
| 2369 |
#### 0.2.1 |
| 2370 |
|
| 2371 |
*Feb. 1, 2014* |
| 2372 |
|
| 2373 |
* Rewritten tests to nose and tox |
| 2374 |
* New tests directory structure |
| 2375 |
* Rewritten HTTP documentation requests examples into more raw manner |
| 2376 |
* Added trailing_slash on extended routers for Django Rest Framework versions`>=2.3.6` (which supports this feature) |
| 2377 |
* Added [caching](#caching) |
| 2378 |
* Added [key constructor](#key-constructor) |
| 2379 |
* Added [conditional requests](#conditional-requests) with Etag calculation |
| 2380 |
* Added [Cache/ETAG mixins](#cache-etag-mixins) |
| 2381 |
* Added [CacheResponseMixin](#cacheresponsemixin) |
| 2382 |
* Added [ETAGMixin](#etagmixin) |
| 2383 |
* Documented [ResourceUriField](#resourceurifield) |
| 2384 |
* Documented [settings](#settings) customization |
| 2385 |
|
| 2386 |
#### 0.2 |
| 2387 |
|
| 2388 |
*Nov. 5, 2013* |
| 2389 |
|
| 2390 |
* Moved docs from readme to github pages |
| 2391 |
* Docs generation with [Backdoc](https://github.com/chibisov/backdoc) |