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:
- Cài đặt gói
django-cors-headersbằng lệnhpip install django-cors-headers - Thêm vào
INSTALLED_APPSvà cấu hình middleware - 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ómGET 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
- Kế thừa từ lớp View và ghi đè phương thức
as_view(),dispatch() - Khởi tạo đối tượng
Requestmới, xử lý dữ liệu đầu vào - Xử lý ngoại lệ khi có lỗi xảy ra
- 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
requestcủa WSGI thành lớpRequestcủ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'})