1. Plan of Profiles API
2. Create user profile serializer
3. Create profiles Viewset
4. Add authentication and permissions
5. Add search feature
1. Plan of Profiles API
(1) Create new profile
- Handle registration of new users
- Validate profile data
(2) Listing existing profile
- Show Id ,Email and name
- A way to search for user
(3) View specific profile
(4) Update profile of logged in user
- User cna change name, email, and password
(5) Delete profile
(6) API URLs
프로필을 관리하는 것이므로 profile이라는 이름을 주면 되겠지

2,3. Create user profile viewset
이번에는 regular serializer와 달리 model serializer를 만든다. model serializer는 Django database models와 잘 호환되는 추가적인 functionality 가 많다.
(1) 구현


(2) TEST

4. Add authentication and permissions
(1) 현재 상황의 문제점
API에 들어와서 누구나 수정할 수 있음. Authentication이 필요한 상황
(2) permissions.py 함수 만들기
경로 profiles_api/permissions.py
from rest_framework import permissions
# custompermission class를 만들수 있게 도와주는 django rest framework class 가 BasePermission
class UpdateOwnProfile(permissions.BasePermission):
"""Allow users to edit their own profile"""
# 이 class를 이용할 때는 has_object_permission 함수를 정의하는 것부터 시작한다
# 이 함수는 permission을 붙인 API에 request가 올 때마다 call 된다.
# authenticated user 여부에 따른 Boolean 값을 return한다.
def has_object_permission(self, request, view, obj):
"""Check user is trying to edit their own profile"""
# request.method가 SAFE_METHODS 인지 확인한다.
# SAFE_METHODS의 대표적인 예시는 obj의 내용을 바꾸지 않는 method을 말한다. 즉 GET method.
if request.method in permissions.SAFE_METHODS:
return True
return obj.id == request.user.id
(3) view에 permission 등록 및 테스트
cf. TokenAuthentication이 무엇인가?
로그인 할 때 random string token을 만들고, 유저가 api에 request를 보낼 때 마다 header에 이 token을 붙여서 인증절차를 간편하게 도와주는 기능. 참고: 2021.12.24 - [IT 일반 공부/네트워크] - [Network Jargon] Authentication Token

5. Add search feature
from rest_framework import filters
...
class UserProfileViewSet(viewsets.ModelViewSet):
"""Handle creating, creating and updating profiles"""
...
filter_backends = (filters.SearchFilter,)
search_fields = ('name', 'email',)


'BE > Python & Django REST API' 카테고리의 다른 글
| [Django REST API] 12. Create profile feed API (0) | 2021.12.25 |
|---|---|
| [Django REST API] 11. Create login API (0) | 2021.12.24 |
| [Django REST API] 9. Introduction to Viewsets (0) | 2021.12.20 |
| [Django REST API] 8. Introduction to API Views (0) | 2021.12.18 |
| [Django REST API] 7. Setup Django Admin (0) | 2021.12.18 |
댓글