drf: Chu kỳ sống của APIView, mô-đun yêu cầu, mô-đun phân tích, mô-đun phản hồi, mô-đun hiển thị

Cấu hình dự án cơ bản

Cài đặt trong file settings.py:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'corsheaders',  # Giải quyết vấn đề CORS
    'app01.apps.App01Config',
    'amp',  # Đăng ký ứng dụng
]

CORS_ORIGIN_ALLOW_ALL = True

LANGUAGE_CODE = 'zh-hans'

TIME_ZONE = 'Asia/Shanghai'

Cấu hình CORS

Các điều kiện đồng nguồn: giao thức, địa chỉ IP, cổng ứng dụng giống nhau. Khác biệt bất kỳ yếu tố nào sẽ gây ra vấn đề vượt miền.

Cách xử lý trong Django:

  1. Cài đặt gói django-cors-headers bằng lệnh pip install django-cors-headers
  2. Thêm vào INSTALLED_APPS và cấu hình middleware
  3. Kích hoạt phép vượt miền bằng CORS_ORIGIN_ALLOW_ALL = True

Cấu hình URL cho dự án

from django.conf.urls import url, include

urlpatterns = [
    url(r'^amp/', include('amp.urls')),
]

Các file trong ứng dụng amp

File urls.py

from amp import views
from django.conf.urls import url, include

urlpatterns = [
    url(r'^books/$', views.BookAPIView.as_view()),
    url(r'^books/(?P<id>\d+)/$', views.BookAPIView.as_view())
]

File views.py

from rest_framework.views import APIView
from rest_framework.response import Response
from . import models

class BookAPIView(APIView):
    def get_single(self, id):
        book_data = models.Book.objects.filter(id=id).values('name', 'price').first()
        if not book_data:
            return Response({
                'status': 1,
                'message': 'Không tìm thấy tài nguyên'
            })
        return Response({
            'status': 0,
            'message': 'Lấy dữ liệu đơn lẻ thành công',
            'results': book_data
        })

    def get_multiple(self):
        books = models.Book.objects.values('name', 'price')
        return Response({
            'status': 0,
            'message': 'Lấy dữ liệu nhóm thành công',
            'results': list(books)
        })

    def get(self, request, *args, **kwargs):
        id = kwargs.get('id')
        return self.get_single(id) if id else self.get_multiple()

File models.py

from django.db import models

class Book(models.Model):
    name = models.CharField(max_length=32)
    price = models.DecimalField(max_digits=6, decimal_places=2)

Các giao diện truy cập

  • GET https://127.0.0.1:8000/amp/books - Lấy dữ liệu nhóm
  • GET https://127.0.0.1:8000/amp/books/2 - Lấy dữ liệu đơn lẻ

Tính năng nổi bật của rest_framework

from rest_framework.views import APIView
from rest_framework.response import Response

class BookAPIView(APIView):
    def get(self, request, *args, **kwargs):
        return Response({'message': 'GET APIView thành công'})

    def post(self, request, *args, **kwargs):
        return Response({'message': 'POST APIView thành công'})

Chu kỳ sống của APIView

  1. Kế thừa từ lớp View và ghi đè phương thức as_view(), dispatch()
  2. Khởi tạo đối tượng Request mới, xử lý dữ liệu đầu vào
  3. Xử lý ngoại lệ khi có lỗi xảy ra
  4. Tạo phản hồi và hiển thị kết quả

Mô-đun yêu cầu

  • Chuyển đổi đối tượng request của WSGI thành lớp Request của DRF
  • Xử lý tham số query (request.query_params) và dữ liệu đầu vào (request.data)

Mô-đun phân tích

  • Hỗ trợ phân tích định dạng JSON, form-data, urlencoded
  • Cấu hình toàn cục và cục bộ cho các lớp view
  • Ưu tiên tìm kiếm cấu hình: cục bộ -> toàn cục -> mặc định

Mô-đun phản hồi

Response(
    data={...},
    status=status.HTTP_200_OK,
    template_name=None,
    headers={},
    exception=False,
    content_type='application/json'
)

Mô-đun hiển thị

Cho phép tùy chỉnh định dạng hiển thị: JSON hoặc giao diện trình duyệt

Ví dụ triển khai

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.parsers import JSONParser, FormParser
from rest_framework.renderers import JSONRenderer

class BookAPIView(APIView):
    parser_classes = [JSONParser, FormParser]
    renderer_classes = [JSONRenderer]

    def get(self, request, *args, **kwargs):
        return Response({
            'message': 'GET APIView thành công',
            'status': 200
        })

    def post(self, request, *args, **kwargs):
        print(request.method)
        print(request.data)
        return Response({'message': 'POST APIView thành công'})

Thẻ: Django rest_framework CORS api_view request_parser

Đăng vào ngày 4 tháng 6 lúc 03:59