Django REST API Framework PDF
Document Details

Uploaded by ConvincingOceanWave
Đại học Mở Thành phố Hồ Chí Minh
2021
Dương Hữu Thành
Tags
Summary
These slides are about the Django REST API framework. They cover topics such as introductory concepts, requests and responses, serializers, authentication, and integration with OAuth2 and JWT. It also covers debug toolbar and Swagger.
Full Transcript
DJANGO REST API ThS. Dương Hữu Thành, Khoa CNTT, Đại học Mở TP.HCM,...
DJANGO REST API ThS. Dương Hữu Thành, Khoa CNTT, Đại học Mở TP.HCM, [email protected]. 1 1This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Nội dung chính Giới thiệu Django REST framework Request & Response Serializer View, GenericView và ViewSets Authentication OAuth2 và JWT Tích hợp công cụ bổ trợ: Debug Toolbar, Swagger 2 2This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Giới thiệu Django Rest API Django REST framework (DRF) là bộ công cụ mạnh và linh hoạt để phát triển API. Một số ưu điểm sử dụng Django REST API. – Hỗ trợ giao diện duyệt API hiệu quả cho dev. – Hỗ trợ nhiều authentication policies, chứng thực bao gồm OAuth1a và OAuth2. – Serialization hỗ trợ cả các data source theo ORM và không ORM (non-ORM). – Tài liệu phong phú và cộng đồng lớn. 3 Dương Hữu Thành 3This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Cài đặt Django Rest API Cài đặt môi trường pip install django pip install djangorestframework pip install markdown pip install django-filter Cập nhật biến INSTALLED_APPS INSTALLED_APPS = [... 'rest_framework', ] 4 Dương Hữu Thành 4This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Viết API đầu tiên Tạo courses/serializers.py from rest_framework.serializers import ModelSerializer from.models import Course class CourseSerializer(ModelSerializer): class Meta: model = Course fields = ['id', 'subject', 'created_date', 'category'] 5 Dương Hữu Thành 5This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Viết API đầu tiên Viết courses/views.py from rest_framework import viewsets, permissions from.models import Course from.serializers import CourseSerializer class CourseViewSet(viewsets.ModelViewSet): queryset = Course.objects.filter(active=True) serializer_class = CourseSerializer permission_classes = [permissions.IsAuthenticated] 6 Dương Hữu Thành 6This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Viết API đầu tiên Viết courses/urls.py from django.urls import path, include from. import views from rest_framework import routers router = routers.DefaultRouter() router.register('courses', views.CourseViewSet) urlpatterns = [ path('', include(router.urls)) ] Chạy server và truy cập http://127.0.0.1:8000/ 7 Dương Hữu Thành 7This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Viết API đầu tiên 8 Dương Hữu Thành 8This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Viết API đầu tiên 9 Dương Hữu Thành 9This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Viết API đầu tiên 10 Dương Hữu Thành 10 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Viết API đầu tiên Phân trang cho phép chỉ định số phần tử hiển thị trên từng trang. Truy cập vào admin thêm vài khoá học 11 Dương Hữu Thành 11 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Viết API đầu tiên Ta phân mỗi trang hiển thị tối đa 2 khoá học. Trong tâp tin settings.py thiết lập cấu hình sau REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 2 } Truy cập http://localhost:8000/courses/ 12 Dương Hữu Thành 12 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Viết API đầu tiên 13 Dương Hữu Thành 13 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Request Request của REST framework kế thừa từ HttpRequest chuẩn, nhưng linh hoạt hơn trong xử lý và chứng thực request (request parsing và request authentication). Request giúp cho việc xử lý dữ liệu request dạng json hay một media type nào khác theo cùng cách thức làm việc với dữ liệu form. 14 Dương Hữu Thành 14 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Các thuộc tính của Request request.data: dữ liệu của request body. request.query_params: các tham số truyền từ request get. request.method: trả về phương thức (chữ in hoa) thực hiện request như GET, POST, PUT, DELETE, PATCH. request.content_type: trả về chuỗi đại diện cho media type của request body. 15 Dương Hữu Thành 15 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Các thuộc tính của Request request.user: các user đã chứng thực thì nó trả về thể hiện của – django.contrib.auth.models.User Ngược lại, nó là thể hiện của – django.contrib.auth.models.AnonymousUser request.auth: chứa thông tin bổ sung chứng thực, nó phụ thuộc cách thức chứng thực, nhưng nó thường chứa thông tin token của request. 16 Dương Hữu Thành 16 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Các thuộc tính của Request request.authenticators: các chính sách chứng thực, trong các lớp APIView hoặc @api_view thuộc tính được thiết lập thông qua thuộc tính authentication_classes hoặc giá trị thuộc tính cấu hình DEFAULT_AUTHENTICATORS. 17 Dương Hữu Thành 17 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Response REST framework cung cấp lớp Response trả về nội dung với nhiều dạng media type phụ thuộc client request. Lớp Response là lớp con của Django SimpleTemplateResponse. Cú pháp tạo response: Response(data, status=None, template_name=None, headers=None, content_type=None) 18 Dương Hữu Thành 18 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Các thuộc tính của Response data: dữ liệu đã được serialize. status: status code cho response, mặc định 200. headers: từ điển HTTP headers cho response. content_type: content type cho response. template_name: tên template sử dụng nếu HTMLRenderer được chọn. 19 Dương Hữu Thành 19 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Serializer Serializer cho phép chuyển các dữ liệu phức tạp như querysets hoặc thể hiện của model thành các kiểu dữ liệu python và dễ dàng kết xuất thành dữ liệu JSON, XML hay một content type nào khác. Nó cũng cung cấp khả năng deserializer để chuyển dữ liệu đã được chuyển về kiểu dữ liệu phức tạp ban đầu sau khi đã kiểm tra (validate). 20 Dương Hữu Thành 20 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Serializer Phương thức validate() dùng để kiểm tra chung cho nhiều trường trong serializer, phương thức có một đối số duy nhất là từ điển chứa giá trị các trường. Phương thức validate_ sẽ trả về giá trị kiểm tra của trường tương ứng hoặc ném ngoại lệ serializers.ValidationError. Chú ý nếu được khai báo required là False thì validate sẽ không được thực hiện. 21 Dương Hữu Thành 21 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Serializer Lớp Serializer cung cấp các phương thức chung để xử lý output cho response. Lớp ModelSerializer giúp nhanh chóng tạo lớp Serializer với các trường tương ứng với các trường của Model. Khi đó – Tự tạo các field giống model. – Tự tạo validator cho serializer. – Bao gồm các phương thức mặc định như save, update, create. 22 Dương Hữu Thành 22 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Serializer Lớp HyperlinkedModelSerializer tương tự ModelSerializer, nhưng nó sử dụng siêu liên kết đại diện cho các quan hệ. 23 Dương Hữu Thành 23 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com ModelSerializer Thuộc tính trong meta class – model: lớp model liên kết cho serialize. – fields: chỉ định các field sẽ được serialize, thiết lập là '__all__' để serializer tất cả field. – read_only_fields: chỉ định các field chỉ đọc. – exclude: chỉ định các field không serialize. – extra_kwargs: bổ sung một số thông tin ràng buộc trên fields. – deep 24 Dương Hữu Thành 24 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com ModelSerializer Ví dụ tạo serializer cho Lesson class TagSerializer(ModelSerializer): class Meta: model = Tag fields = ['id', 'name'] class LessonSerializer(ModelSerializer): tags = TagSerializer(many=True) class Meta: model = Lesson fields = ['id', 'subject', 'content', 'created_date', 'updated_date', 'tags'] 25 Dương Hữu Thành 25 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com ModelSerializer Sử dụng cho 1 đối tượng QuerySet lesson = Lesson.objects.get(pk=1) LessonSerializer(lesson).data Sử dụng cho danh sách QuerySet lessons = Lesson.objects.filter(active=True) LessonSerializer(lessons, many=True).data Cung cấp thêm thông tin context cho serializer LessonSerializer(lesson, context={'request': request}).data 26 Dương Hữu Thành 26 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com ModelSerializer 27 Dương Hữu Thành 27 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com ModelSerializer Sau đây 2 serializer minh hoạ việc chỉnh sửa hoặc ghi đè xử lý của serializer – Ví dụ 1: chỉnh sửa thông tin serialize image của CourseSerializer trả về đường dẫn tuyệt đối cho client. – Ví dụ 2: ghi đè phương thức create của UserSerializer trong chức năng đăng ký người dùng để băm mật khẩu trước khi lưu xuống CSDL. 28 Dương Hữu Thành 28 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com ModelSerializer class CourseSerializer(HyperlinkedModelSerializer): image = serializers.SerializerMethodField(source='image') def get_image(self, obj): request = self.context['request'] if obj.image.name.startswith('static/'): path = "/%s" % obj.image.name else: path = '/static/%s' % (obj.image) return request.build_absolute_uri(path) class Meta: model = Course fields = ['id', 'subject', 'image', 'created_date', 'category_id'] 29 Dương Hữu Thành 29 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com ModelSerializer class UserSerializer(ModelSerializer): class Meta: model = User fields = ['id', 'first_name', 'last_name', 'username', 'password', 'email', 'avatar'] extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): data = validated_data.copy() user = User(**data) user.set_password(user.password) user.save() return user 30 Dương Hữu Thành 30 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com View View APIView GenericAPIView ViewSet GenericViewSet ModelViewSet ReadOnlyModelViewSet 31 Dương Hữu Thành 31 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com APIView REST framework cung cấp lớp APIView là lớp con của lớp View trong Django. Trong đó – Đối tượng request là thể hiện Request của REST framework. – Các phương thức trả về reponse là thể hiện Response của REST framework. – Sử dụng cũng tương tự View sẽ có các phương thức request tương ứng như get(), post() và nhiều thuộc tính cho API policy. 32 Dương Hữu Thành 32 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com APIView from rest_framework.views import APIView from rest_framework.permissions import IsAuthenticated class CommentAPIView(APIView): def get_permissions(self): if self.request.method == 'GET': return [permissions.AllowAny()] return [permissions.IsAuthenticated()] def get(self, request, lesson_id): pass def post(self, request, lesson_id): pass 33 Dương Hữu Thành 33 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com APIView Viết phương thức get() của CommentAPIView class CommentAPIView(APIView):... def get(self, request, lesson_id): comments = Comment.objects.filter(lesson_id=lesson_id) serializer = CommentSerializer(comments, many=True) return Response(serializer.data, status=status.HTTP_200_OK)... 34 Dương Hữu Thành 34 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com APIView class CommentAPIView(APIView):... def post(self, request, lesson_id): content = request.data.get('content') if content is not None: try: c = Comment.objects.create(content=content, user=request.user, lesson_id=lesson_id) except IntegrityError: err_msg = "Lesson does not exist!" else: return Response(CommentSerializer(c).data, status=status.HTTP_201_CREATED) else: err_msg = "Content is required!!!" return Response(data={'error_msg': err_msg}, status=status.HTTP_400_BAD_REQUEST) 35... Dương Hữu Thành 35 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com APIView Ngoài ra ta có thể viết view bằng function from rest_framework.decorators import api_view @api_view(['GET', 'POST']) @permission_classes([IsAuthenticated]) def comment_api_view(request): if request.method == 'GET': pass elif request.method == 'POST': pass 36 Dương Hữu Thành 36 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com APIView Cập nhật courses/urls.py urlpatterns = [... path('lessons//comments/', views.CommentAPIView.as_view()), ] Khi đó, ta có các API sau: – /lessons/{lesson_id}/comments – GET – /lessons/{lesson_id}/comments – POST 37 Dương Hữu Thành 37 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Generic View Generic View giúp phát triển nhanh API view. GenericAPIView kế thừa APIView, bổ sung thêm một số hành vi chuẩn như list và detail. 38 Dương Hữu Thành 38 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Generic View queryset: trả về các đối tượng từ view. Queryset sẽ được thực thi một lần khi nó được sử dụng (evaluated) và nó sẽ lưu đệm (cached) cho các lần truy vấn sau. Nếu có ghi đè phương thức get_queryset() thì kết quả sẽ ưu tiên cao hơn. serializer_class: lớp serializer được sử dụng validate, deserialize input và serialize output. Ta có thể ghi đè phương thức get_serializer_class() thay thế. 39 Dương Hữu Thành 39 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Generic View lookup_field: các trường dùng lọc dữ liệu trong các thể hiện model, mặc định là pk. lookup_url_kwarg: các đối số URL argument. pagination_class: chỉ định lớp để để phân trang cho kết quả list, mặc định sử dụng giá trị cấu hình của DEFAULT_PAGINATION_CLASS. Nếu paginate_class=None sẽ không phân trang. get_object(): trả về thể hiện của đối tượng được sử dụng cho detail. 40 Dương Hữu Thành 40 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Generic View cụ thể CreateAPIView ListAPIView RetrieveAPIView DestroyAPIView UpdateAPIView ListCreateAPIView RetrieveUpdateAPIView RetrieveDestroyAPIView RetrieveUpdateDestroyAPIView 41 Dương Hữu Thành 41 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Các lớp Mixins Các lớp mixins (rest_framework.mixins) cung cấp các action hiện thực sẵn các hành vi view cơ bản. Một số lớp mixins – ListModelMixin: hiện thực sẵn list(). – CreateModelMixin: hiện thực sẵn create(). – RetrieveModelMixin: hiện thực sẵn retrieve(). – UpdateModelMixin: hiện thực sẵn update() và update_partial() – DestroyModelMixin: hiện thực sẵn destroy(). 42 Dương Hữu Thành 42 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com ViewSet Django REST framework cho phép kết hợp logic của các view liên quan trong một lớp duy nhất gọi là ViewSet. ViewSet không cung cấp các phương thức get(), post(), thay vào đó là các phương thức như list(), create(), retrieve(), destroy(), update(). Chú ý: các lớp ViewSet không hiện thực sẵn các action. 43 Dương Hữu Thành 43 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com ViewSet Các phương thức của ViewSets class LessonViewSet(viewsets.ViewSet): def list(self, request): pass def create(self, request): pass def retrieve(self, request, pk=None): pass def update(self, request, pk=None): pass def partial_update(self, request, pk=None): pass def destroy(self, request, pk=None): pass 44 Dương Hữu Thành 44 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com class LessonViewSet(viewsets.ViewSet): def list(self, request): ViewSet lessons = Lesson.objects.filter(active=True) serializer = LessonSerializer(lessons, many=True) return Response(data=serializer.data) def retrieve(self, request, pk): try: lesson = Lesson.objects.get(pk=pk) except Lesson.DoesNotExist: return Http404() return Response(LessonSerializer(lesson).data) def create(self, request): d = request.data l = Lesson.objects.create(subject=d['subject'], content=d['content'], course_id=d['course_id']) serializer = LessonSerializer(l) return Response(serializer.data, 45 Dương Hữu Thành status=status.HTTP_201_CREATED) 45 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com ViewSet Một số thuộc tính trong ViewSet – basename: tên URL được tạo. – action: tên các hành vi trong ViewSet như list, retrieve, create. – name: tên của ViewSet. – description: mô tả View của ViewSet. – detail: chỉ định action hiện tại có được cấu hình cho list và detail không. – suffix: phần đuôi của ViewSet type. 46 Dương Hữu Thành 46 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com ViewSet Kiểm tra quyền trong LessonViewSet như sau: class LessonViewSet(viewsets.ViewSet): def get_permissions(self): if self.action in ['list', 'retrieve']: return [IsAuthenticated()] return [IsAdminUser()]... 47 Dương Hữu Thành 47 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Routers Ta đăng ký ViewSet cho lớp router, nó sẽ tự động tạo các urlconfs. from django.urls import path, include from. import views from rest_framework import routers router = routers.DefaultRouter() router.register('courses', views.CourseViewSet) router.register('lessons', views.LessonViewSet, basename='lesson') urlpatterns = [ path('', include(router.urls)) ] 48 Dương Hữu Thành 48 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Routers Hai đối số bắt buộc của register() – prefix: phần tên trước trên URL được sử dụng cho tất cả router, dạng {prefix}/ – viewset: lớp ViewSet. Đối số tuỳ chọn – basename: tên URL được tạo ra, mặc định dựa trên thuộc tính queryset trong ViewSet. 49 Dương Hữu Thành 49 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Routers Với khai báo ViewSet này, ta có các API sau: – /lessons/ – GET (list): lấy danh sách bài học, có tên là lesson-list. – /lessons/ – POST (create): thêm bài học, có tên là lesson-add. – /lessons/{pk}/ – GET (retrieve): xem chi tiết thông tin một bài học, có tên là lesson-detail. 50 Dương Hữu Thành 50 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Routers 51 Dương Hữu Thành 51 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Routers Kết quả response 52 Dương Hữu Thành 52 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com ModelViewSet ModelViewSet cung cấp một số xử lý mặc định cho ViewSet. Ví dụ tạo ModelViewSet cho Lesson. class LessonViewSet(viewsets.ModelViewSet): serializer_class = LessonSerializer queryset = Lesson.objects.filter(active=True) Bổ sung các urls của ViewSet này vào route của REST framework. 53 Dương Hữu Thành 53 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com ModelViewSet Các API sau được tạo ra tự động – /lessons/ - GET – /lessons/ - POST – /lessons/{id}/ - GET – /lessons/{id}/ - PUT – /lessons/{id}/ - PATCH – /lessons/{id}/ - DELETE 54 Dương Hữu Thành 54 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com ModelViewSet Thêm action vào ViewSet, bổ sung thêm API ẩn bài học (cập nhật active thành False) from rest_framework.decorators import action class LessonViewSet(viewsets.ModelViewSet): @action(methods=['post'], detail=True) def hide_lesson(self, request, pk=None):... Mặc định API được tạo (ta có thể đổi thông in URL bằng thuộc tính url_path và url_name) – /lessons/{pk}/hide_lesson/ - POST 55 Dương Hữu Thành 55 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com ModelViewSet class LessonViewSet(viewsets.ModelViewSet):... @action(methods=['post'], detail=True, name='Hide this lesson', url_path='hide-lesson', url_name='hide-lesson') def hide_lesson(self, request, pk=None): try: lesson = Lesson.objects.get(pk=pk) lesson.active = False lesson.save() except Course.DoesNotExist: return Response(status=status.HTTP_400_BAD_REQUEST) serializer = LessonSerializer(lesson) return Response(serializer.data, status=status.HTTP_200_OK) 56 Dương Hữu Thành 56 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com ModelViewSet Truy cập vào một bài học cụ thể 57 Dương Hữu Thành 57 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com ModelViewSet 58 Dương Hữu Thành 58 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com ModelViewSet Thêm action cho phép gán tag vào cho lesson. 59 Dương Hữu Thành 59 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com class LessonViewSet(viewsets.ModelViewSet): @action(methods=['post'], detail=True, ViewSets name="Add tags to a lesson", url_path='add-tags-to-lesson', url_name='add-tags') def add_tags_to_lesson(self, request, pk): try: lesson = Lesson.objects.get(pk=pk) tags = request.data.get('tags') for tag in tags.split(','): t, _ = Tag.objects.get_or_create(name=tag.strip()) lesson.tags.add(t) lesson.save() except Lesson.DoesNotExist | KeyError: return Response(status=status.HTTP_404_NOT_FOUND) serializer = LessonSerializer(lesson) return Response(serializer.data, status=status.HTTP_200_OK) 60 Dương Hữu Thành 60 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com ModelViewSet 61 Dương Hữu Thành 61 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com ModelViewSet 62 Dương Hữu Thành 62 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Parsers REST cung nhiều lớp Parser cho phép xử lý các request với nhiều media type khác nhau. Khi nhận request.data, REST dựa trên Content- Type của request để xác định sử dụng parser nào để parse nội dung request. Ta có thể thiết lập parser mặc định toàn cục cho ứng dụng trong settings giống như sau: REST_FRAMEWORK = { 'DEFAULT_PARSER_CLASSES': [ 'rest_framework.parsers.JSONParser', ] } 63 Dương Hữu Thành 63 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Parsers Ví dụ sử dụng FileUploadParser cho view đăng ký người dùng vì cần upload ảnh đại diện. from rest_framework.parsers import MultiPartParser class UserViewSet(viewsets.ViewSet, generics.CreateAPIView): serializer_class = UserSerializer queryset = User.objects.filter(is_active=True) parser_classes = [MultiPartParser, ] 64 Dương Hữu Thành 64 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Authentication Authentication là cơ chế kết hợp các request nhận được với tập các thông tin chứng thực. Các chính sách permission và throttling sử dụng các thông tin chứng thực để quyết định request có quyền truy cập không. Authentication luôn chạy khi bắt đầu view và trước khi kiểm tra permisson và throttling. 65 Dương Hữu Thành 65 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Authentication request.user là thể hiện của lớp User thuộc gói contrib.auth. request.auth chứa thông tin chứng thực khác, chẳng hạn lưu token. 66 Dương Hữu Thành 66 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Thực hiện Authentication Các loại chứng thực (authentication schemes) được định nghĩa danh sách lớp python. REST framework sẽ chứng thực mỗi lớp trong danh sách và thiết lập giá trị request.user và request.auth cho lớp đầu tiên được chứng thực thành công. Nếu không có lớp nào chứng thực thành công – request.user là thể hiện của django.contrib.auth.models.AnonymousUser – Request.auth = None 67 Dương Hữu Thành 67 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Thực hiện Authentication Cấu hình DEFAULT_AUTHENTICATION_CLASSES trong biến REST_FRAMEWORK trong settings.py để chỉ định các lớp mặc định dùng chứng thực. REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.TokenAuthentication' ] } 68 Dương Hữu Thành 68 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Thực hiện Authentication Ngoài ra, ta có thể thiết lập các lớp chứng thực trong các lớp view thông qua thuộc tính authentication_classes class UserView(APIView): authentication_classes = [BasicAuthentication, TokenAuthentication] permission_classes = [IsAdminUser] def get(self, request): pass 69 Dương Hữu Thành 69 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Thực hiện Authentication Nếu một request không được chứng thực thì có 2 error code sau đây phù hợp – HTTP 401 – Unauthorized: luôn có header WWW-Authenticate hướng dẫn client làm thế nào chứng thực. – HTTP 403 – Permission Denied Chú ý khi request được chứng thực thành công, nhưng không có quyền truy cập tài nguyên nào đó thì HTTP 403 luôn được sử dụng. 70 Dương Hữu Thành 70 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Các lớp Authentication BasicAuthentication: chứng thực người dùng thông qua username và password. Nếu chứng thực thành công thì – request.user là thể hiện của User của Django. – request.auth = None – Nếu request không được chứng thức thì HTTP 401 Unauthorized sẽ được trả về. 71 Dương Hữu Thành 71 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Các lớp Authentication TokenAuthentication: chứng thực người dùng thông qua token, phù hợp cho ứng dụng theo kiến trúc client-server. Để sử dụng lớp chứng thực này, ta cần cấu hình thêm cho biến INSTALLED_APP như sau: INSTALLED_APPS = [... 'rest_framework.authtoken' ] Thực thi lệnh migrate. 72 Dương Hữu Thành 72 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Các lớp Authentication Tạo token cho user from rest_framework.authtoken.models import Token token = Token.objects.create(user=...) print(token.key) Phía client chứng thực thiết lập Authorization trong headers như sau: Authorization: Token Khi đó request.auth là thể hiện của rest_framework.authtoken.models.Token 73 Dương Hữu Thành 73 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Các lớp Authentication SessionAuthentication: lớp chứng thực này sử dụng session của django. Lớp chứng thực này phù hợp cho client dùng ajax chạy trong cùng ngữ cảnh session của website. RemoteUserAuthentication: lớp chứng thực này cho phép uỷ quyền chứng thực cho web server, thiết lập cho biến môi trường REMOTE_USER. 74 Dương Hữu Thành 74 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com OAuth2 OAuth là một giao thức mở và an toàn để chứng thực người dùng giữa các dịch vụ liên quan. OAuth uỷ quyền một dịch vụ được phép truy cập những tài nguyên từ một dịch vụ khác đại diện cho người dùng, mà không cần cung cấp thông tin như username, password. OAuth2 là phiên bản mới nhất của giao thức OAuth. 75 Dương Hữu Thành 75 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com OAuth2 Client: ứng dụng thực hiện hành vi đại diện người dùng truy cập các tài nguyên. Resource Owner/User: là người dùng uỷ quyền cho ứng dụng truy cập vào các tài nguyên được bảo vệ bởi nhà cung cấp khác. Authorization Server: server chứng thực yêu cầu từ phía client. Resource Server: server chứa các tài nguyên được bảo vệ. 76 Dương Hữu Thành 76 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com OAuth2 Các bước thực hiện giao tiếp giữa client và server theo giao thức OAuth2: – Authorize: chứng thực yêu cầu quyền truy cập từ client. – Yêu cầu access token. – Truy cập các tài nguyên được bảo vệ. 77 Dương Hữu Thành 77 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com OAuth2 Authorization request User Authorization grant (Resource Owner) Authorization grant Client Authorization Server Access token Access token Protected Resource Resource Server 78 Dương Hữu Thành 78 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com OAuth2 Trước khi sử dụng OAuth2 để chứng thực, người phát triển (developer) phải đăng ký một application với OAuth2 provider. Sau khi đăng ký xong sẽ được cung cấp thông tin: client ID, client secret, authorization server URL, access token URL, resource server URL. 79 Dương Hữu Thành 79 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com OAuth2 Client ID: thông tin công khai định danh ứng dụng, giống như username. Client secret: thông tin riêng tư gửi kèm lên server, giống như password. Authorization server URL: URL để client thực hiện các yêu cầu (request). Access token URL: URL để client yêu cầu access token. Resource server URL: URL để client truy cập các tài nguyên được bảo vệ. 80 Dương Hữu Thành 80 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Django OAuth Toolkits Django OAuth Toolkit cung cấp tất cả các endpoint, dữ liệu và logic cần thiết để thực hiện giao thức OAuth2 cho django project. Cài đặt pip install django-oauth-toolkit 81 Dương Hữu Thành 81 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Django OAuth Toolkits Cập nhật biến INSTALLED_APP trong settings.py INSTALLED_APPS = (... 'oauth2_provider', ) Bổ sung thông tin cấu hình cho biến REST_FRAMEWORK trong settings.py REST_FRAMEWORK = {... 'DEFAULT_AUTHENTICATION_CLASSES': ( 'oauth2_provider.contrib.rest_framework.OAuth2Authentication', ) } 82 Dương Hữu Thành 82 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Django OAuth Toolkits Cập nhật urls cho URLConfig của project from django.urls import include, path urlpatterns = [... path('o/', include('oauth2_provider.urls', namespace='oauth2_provider')), ] Thực thi migrate python manage.py migrate oauth2_provider 83 Dương Hữu Thành 83 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Django OAuth Toolkits Truy cập: http://127.0.0.1:8000/o/applications/ 84 Dương Hữu Thành 84 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Django OAuth Toolkits Yêu cầu lấy access token – Url: /o/token/ – Method: POST – Body data { "grant_type": "password", "username": "", "password": "", "client_id": "", "client_secret ": "" } 85 Dương Hữu Thành 85 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Django OAuth Toolkits 86 Dương Hữu Thành 86 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Django OAuth Toolkits Sau khi có access token, ta có thể sử dụng để yêu cầu truy cập môt số tài nguyên yêu cầu chứng thực mà không cần gửi username, password. Trong HTTP header của mỗi request phải gửi kèm Authorization, giá trị của nó có thể là Token hoặc Bearer phụ thuộc OAuth2 provider. Cú pháp – Authorization: Bearer 87 Dương Hữu Thành 87 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Django OAuth Toolkits Phần trước ta đã cấu hình cho API /courses/ chỉ được truy cập khi đăng nhập, giờ truy cập vào không có thông tin access token để chứng thực. 88 Dương Hữu Thành 88 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Django OAuth Toolkits 89 Dương Hữu Thành 89 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com CORS CORS (Cross-origin resource sharing) là cơ chế cho phép giới hạn các tài nguyên trên trang web được yêu cầu truy cập từ domain khác. CORS cho phép trình duyệt và server xác định được request cross-origin có an toàn không. 90 Dương Hữu Thành 90 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com CORS Cài cors middleware pip install django-cors-headers Bổ sung biến INSTALLED_APP trong settings.py INSTALLED_APP = [..., 'corsheaders' ] 91 Dương Hữu Thành 91 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com CORS Cập nhật biến MIDDLEWARE của settings.py giá trị corsheaders.middleware.CorsMiddleware. Giá trị này nên đặt trước các middleware có thể tạo ra response. MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware',... ] Thiết lập giá trị biến sau trong settings.py CORS_ALLOW_ALL_ORIGINS = True 92 Dương Hữu Thành 92 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com JSON Web Token JSON Web Token (JWT) là tiêu chuẩn chứng thực mới dựa trên token, nhưng không giống với TokenAuthentication có sẵn, JWT không sử dụng CSDL để kiểm tra token. Ở đây minh hoạ sử dụng JWT thông qua thư viện Simple JWT. 93 Dương Hữu Thành 93 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Simple JWT Cài đặt pip install djangorestframework-simplejwt Chỉ định lớp chứng thực trong settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': (... 'rest_framework_simplejwt.authentication.JWTAuthentication', ) } 94 Dương Hữu Thành 94 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Simple JWT Cập nhật urls cho URLConfig của project from rest_framework_simplejwt.views import ( TokenObtainPairView, TokenRefreshView ) urlpatterns = [... path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), ] 95 Dương Hữu Thành 95 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Simple JWT 96 Dương Hữu Thành 96 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Simple JWT 97 Dương Hữu Thành 97 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Tích hợp Swagger Cài đặt drf-yasg (Yet Another Swagger Generator) pip install drf-yasg Cập nhật biến INSTALLED_APP INSTALLED_APPS = [... 'django.contrib.staticfiles', 'drf_yasg', ] 98 Dương Hữu Thành 98 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Tích hợp Swagger Cập nhật urls cho URLConfs của project from rest_framework import permissions from drf_yasg.views import get_schema_view from drf_yasg import openapi schema_view = get_schema_view( openapi.Info( title="Course API", default_version='v1', description="APIs for CourseApp", contact=openapi.Contact(email="[email protected]"), license=openapi.License(name="Dương Hữu Thành@2021"), ), public=True, permission_classes=(permissions.AllowAny,), 99 ) Hữu Thành Dương 99 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Tích hợp Swagger Cập nhật urls cho URLConf của project... urlpatterns = [... re_path(r'^swagger(?P\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), name='schema-json'), re_path(r'^swagger/$', schema_view.with_ui('swagger’, cache_timeout=0), name='schema-swagger-ui'), re_path(r'^redoc/$', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc') ] 100 Dương Hữu Thành 100 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Tích hợp Swagger 101 Dương Hữu Thành 101 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Tích hợp Swagger 102 Dương Hữu Thành 102 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Tích hợp Swagger Ta có thể thiết lập ẩn một api để không đưa vào swagger bằng cách thiết lập thuộc tính swagger_schema = None class UserList(APIView): swagger_schema = None... 103 Dương Hữu Thành 103 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Tích hợp Swagger from drf_yasg.utils import swagger_auto_schema from drf_yasg import openapi class LessonViewSet(viewsets.ModelViewSet): @swagger_auto_schema( operation_description='Add tags to a lesson', responses={ status.HTTP_200_OK: LessonSerializer() } ) @action(methods=['post'], detail=True, name="Add tags to a lesson", url_path='add-tags-to-lesson’, url_name='add-tags') def add_tags_to_lesson(self, request, pk):... 104 Dương Hữu Thành 104 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Tích hợp Debug Toolbar Cài đặt pip install django-debug-toolbar Cập nhật biến INSTALLED_APP và STATIC_URL INSTALLED_APPS = [ #... 'django.contrib.staticfiles', #... 'debug_toolbar', ] STATIC_URL = '/static/' 105 Dương Hữu Thành 105 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Tích hợp Debug Toolbar Debug Toolbar chủ yếu được thực hiện trong middleware. Trong settings.py bật middleware MIDDLEWARE = [... 'debug_toolbar.middleware.DebugToolbarMiddleware', ] Debug Toolbar chỉ được hiển thị trên các địa chỉ IP có trong danh sách INTERNAL_IPS của tập tin cấu hình. INTERNAL_IPS = [ '127.0.0.1' ] 106 Dương Hữu Thành 106 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Tích hợp Debug Toolbar Cập nhật urls cho URLConfig của project import debug_toolbar from django.conf import settings from django.urls import include, path urlpatterns = [... path('__debug__/', include(debug_toolbar.urls)) ] 107 Dương Hữu Thành 107 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Tích hợp Debug Toolbar 108 Dương Hữu Thành 108 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Tích hợp Debug Toolbar 109 Dương Hữu Thành 109 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com Q&A ThS. Dương Hữu Thành, Khoa CNTT, Đại học Mở TP.HCM, [email protected]. 110 110 This presentation uses a free template provided by FPPT.com www.free-power-point-templates.com