۱. قالب¶
تنظیمات¶
سه خط در REST_FRAMEWORK، هر کدام مستقل از بقیه:
example/config/settings.py
REST_FRAMEWORK = {
# Nobody signs in to the example: it shows the shape of the answers, not who may ask.
'DEFAULT_AUTHENTICATION_CLASSES': [],
'DEFAULT_PERMISSION_CLASSES': [],
'UNAUTHENTICATED_USER': None,
# drf-parcel: the three lines - each works without the others.
'EXCEPTION_HANDLER': 'drf_parcel.handlers.exception_handler',
'DEFAULT_PAGINATION_CLASS': 'drf_parcel.pagination.PageNumberPagination',
'DEFAULT_SCHEMA_CLASS': 'drf_parcel.schema.ParcelAutoSchema',
}
یک ViewSet در قالب¶
example/shop/api.py
class ProductViewSet(EnvelopeMixin, viewsets.ModelViewSet[Product]):
"""Products, a numbered page at a time."""
queryset = Product.objects.all()
serializer_class = ProductSerializer
# drf-parcel: the client may send ?page_size=, and never gets more than 20.
client_page_size = True
max_page_size = 20
# drf-parcel: this view's own sentence for one action; the rest say the default.
envelope_messages = {'create': _('The product was added.')}
def perform_destroy(self, instance: Product) -> None:
services.delete_product(instance)
@action(detail=True, methods=['post'])
def restock(self, request: Request, pk: str) -> Response:
"""Add to the stock - an answer written by hand, with a message of its own."""
product = self.get_object()
asked = RestockSerializer(data=request.data)
asked.is_valid(raise_exception=True)
product.stock += asked.validated_data['quantity']
product.save(update_fields=['stock'])
return success_response(
ProductSerializer(product).data, message=_('The stock was updated.')
)
سه نکته:
EnvelopeMixinاول میآید. پاسخ view را درfinalize_response، یک بار، در قالب میگذارد -list،create،destroyو اکشنrestockیکسان.envelope_messagesبه یک اکشن جملهی خودش را میدهد. هر اکشن دیگر پیام پیشفرض را میگوید، که از روی درخواست تعیین میشود.restockدستی جواب میدهد، باsuccess_response. پاسخی که از قبل در قالب است هرگز دو بار در قالب گذاشته نمیشود.
هر پاسخ چه میگوید¶
وقتی کسی پیامی ننوشته، از روی درخواست تعیین میشود:
| درخواست | پیام |
|---|---|
پاسخ 201 |
Created. |
PUT یا PATCH |
Saved. |
DELETE |
Deleted. |
| هر چیز دیگر | Done. |
curl -X POST -H 'Content-Type: application/json' \
-d '{"name": "Brooch", "price": "60.00"}' http://127.0.0.1:8000/api/products/
{"success": true, "status_code": 201, "message": "The product was added.",
"data": {"id": 29, "name": "Brooch", "price": "60.00", "stock": 0}}
جملهی خود view، چون create یکی نام برده بود. پیام در سه سطح عوض میشود و
نزدیکترین برنده است: یک پاسخ (success_response(..., message=...))، یک view
(envelope_messages)، یا کل پروژه (DRF_PARCEL['MESSAGES']).
حذف یعنی 200
DELETE /api/products/29/ با 200 همراه با قالب و «Deleted.» جواب
میدهد، نه 204. پاسخ 204 طبق تعریف بدنه ندارد، پس کلاینت چیزی برای خواندن
نداشت.