백엔드 중심으로 서술되었음
간단히 이해하면 1 2 3 4 작업 중에 3에서 막혔으면 1로 롤백 해줘서 에러 안나고 손실 안 나게 해주는 것.
있으면 get, 없으면 create 해주는 기능. 디폴트 값을 지정할 수 있다.
re_path(r'^/(?P<product_id>\d+)$', ProductView.as_view()),
정규표현식까지 보다는
path('/<int:product_id>', ProductView.as_view()),
리턴 데이터 타입 : product.price가 decimal 타입인데 프론트엔드에서 받을 때 "5500.55"로 string처리 됨. 이를 float 처리해줘서 숫자로 바꿔주기
돈 단위는 int로 받기 보다는 decimal로.(유로, 달러)
리스트 컴프리헨션 공부하기 : 리스트, 딕셔너리 안에서 리스트, 딕셔너리를 돌려서 만들기.
이것도 추가로 공부 더 해주기
>>> id_name = {1: '박진수', 2: '강만진', 3: '홍수정'}
>>> name_id = {val:key for key,val in id_name.items()}
>>> name_id
{'박진수': 1, '강만진': 2, '홍수정': 3}
>>> dictionary = {'a':1, 'b':2, 'c':3}
>>> dicc = {k:v for v,k in dictionary.items()}
>>> dicc
{1: 'a', 2: 'b', 3: 'c'}
이를 views.py에 추가해줘야 하는 것 필요
>>> from timeit import timeit
>>> timeit("[]")
0.040084982867934334
>>> timeit("list()")
0.17704233359267718
>>> timeit("{}")
0.033620194745424214
>>> timeit("dict()")
import json
from json import JSONDecodeError
from django.views import View
from django.http import JsonResponse
from .models import WishList
from product.models import Product, ProductOption, Option, DiscountRate
from user.models import User
class WishListView(View):
def post(self, request):
try:
data = json.loads(request.body)
user = User.objects.get(username=data['username'])
# user는 아이디로 가져옴
wishlist = WishList.objects.create(
quantity = data['quantity'],
product_id = data['product_id'],
user = user,
product_option_id = data['product_option_id']
)
# 들어가야 할 4가지 자료, 모두 프론트가 입력해준다는 생각으로
return JsonResponse({'message' : 'SUCCESS'}, status=200)
except JSONDecodeError:
return JsonResponse({'message' : 'JSON_DECODE_ERROR'}, status=400)
except KeyError:
return JsonResponse({'message' : 'KEY_ERROR'}, status=400)
except WishList.DoesNotExist:
return JsonResponse({'message' : 'WISHLIST_DOES_NOT_EXIST'}, status=404)
def get(self, request):
wishlists = WishList.objects.filter(user_id=3)
# 아직 데이터 데코레이터 안해서 3번 아이디를 기준
result = list()
try:
for wishlist in wishlists:
my_dict = dict(
quantity = wishlist.quantity,
product_id = wishlist.product.id,
user_id = wishlist.user.id,
product_option_id = wishlist.product_option.id
)
result.append(my_dict)
return JsonResponse({'result' : result}, status=200)
except JSONDecodeError:
return JsonResponse({'message' : 'JSON_DECODE_ERROR'}, status=400)
except KeyError:
return JsonResponse({'message' : 'KEY_ERROR'}, status=400)
except WishList.DoesNotExist:
return JsonResponse({'message' : 'WISHLIST_DOES_NOT_EXIST'}, status=404)
# 최대한 많은 예외처리
단순히 아이디만 보내주는 것이 아니라 받을 때는 아이디를 받되 보낼 때는 명을 보내주는것(point, 가격 포함)
import json
from json import JSONDecodeError
from django.views import View
from django.http import JsonResponse
from django.db import transaction
from .models import WishList
from product.models import Product, ProductOption, Option, DiscountRate
from user.models import User
class WishListView(View):
@transaction.atomic
def post(self, request):
try:
data = json.loads(request.body)
user = User.objects.get(username=data['username'])
wishlist = WishList.objects.create(
quantity = data['quantity'],
product_id = data['product_id'],
user = user,
product_option_id = data['product_option_id']
)
return JsonResponse({'message' : 'SUCCESS'}, status=200)
except JSONDecodeError:
return JsonResponse({'message' : 'JSON_DECODE_ERROR'}, status=400)
except KeyError:
return JsonResponse({'message' : 'KEY_ERROR'}, status=400)
except WishList.DoesNotExist:
return JsonResponse({'message' : 'WISHLIST_DOES_NOT_EXIST'}, status=404)
def get(self, request):
wishlists = WishList.objects.filter(user_id=3)
result = list()
try:
for wishlist in wishlists:
product = wishlist.product
user = wishlist.user
# product 직접 접근 가능
my_dict = dict(
quantity = wishlist.quantity,
product_id = product.id,
product = product.name,
product_thumnail = product.thumbnail_image_url,
user_id = wishlist.user.id,
product_option_id = wishlist.product_option.id,
price = product.price,
point = user.point
)
result.append(my_dict)
return JsonResponse({'result' : result}, status=200)
except JSONDecodeError:
return JsonResponse({'message' : 'JSON_DECODE_ERROR'}, status=400)
except KeyError:
return JsonResponse({'message' : 'KEY_ERROR'}, status=400)
except WishList.DoesNotExist:
return JsonResponse({'message' : 'WISHLIST_DOES_NOT_EXIST'}, status=404)
<최종 프론트엔드 통신 현황>
from django.views import View
from django.http import JsonResponse
from django.db import transaction
from .models import WishList
from product.models import Product, ProductOption, Option, DiscountRate
from user.models import User
class WishListView(View):
@transaction.atomic
def post(self, request):
내 팀원 PR이 리뷰를 거친 후 최종 머지가 되었을때 내가 작업하던 브랜치에 해당 내용을 병합할때 스텝