일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
- Resources are low on NN
- 카카오 자물쇠와 열쇠
- hive beeline 에러
- mac hive 3
- hive beeline
- Safe mode is ON
- mac hadoop 설치
- 기업 조사 빨리 하는 법
- 자소서 시간 줄이기
- mac hadoop 설정
- 도커 교과서
- hive beeline 실행
- 자소서 빨리 쓰는 법
- hadoop safe mode leave
- 자소서 빨리
- mac hadoop
- 백준 18428
- Failed to connect to localhost:10000
- 카카오 2020 코테
- mac hadoop 3
- code=0)
- 이더리움 #ethereum
- 카카오 2020 코딩테스트
- Could not open client transport with JDBC Uri: jdbc:hive2://localhost:10000
- 이더리움
- mac hive
- 자소서 너무 오래 걸림
- hadoop safe mode
- is not allowed to impersonate hive (state=08S01
- hive beeline 설정
- Today
- Total
A seeker after truth
231101 수 Day12 - 장고3: 직렬화, REST 본문
1. Serilaizer
serialize를 해 주기 위해서는 먼저 model의 column들 모두 serializers 작업을 해줘야 한다. 또한 시리얼라이저는 유효성 검증을 통과한 애들을 대상으로 한다. 유효성 검증 통과한 애들은 ordereddict 타입으로 주어진다(넘겨진다)
from collections import OrderedDict
이거 오늘 첨 알았음... 오랜 파이썬 사용 인생에 참 부끄러운 부분이로군. 구현체가 뭔데?
class _Link(object):
__slots__ = 'prev', 'next', 'key', '__weakref__'
class OrderedDict(dict):
'Dictionary that remembers insertion order'
# An inherited dict maps keys to values.
# The inherited dict provides __getitem__, __len__, __contains__, and get.
# The remaining methods are order-aware.
# Big-O running times for all methods are the same as regular dictionaries.
# The internal self.__map dict maps keys to links in a doubly linked list.
# The circular doubly linked list starts and ends with a sentinel element.
# The sentinel element never gets deleted (this simplifies the algorithm).
# The sentinel is in self.__hardroot with a weakref proxy in self.__root.
# The prev links are weakref proxies (to prevent circular references).
# Individual links are kept alive by the hard reference in self.__map.
# Those hard references disappear when a key is deleted from an OrderedDict.
def __init__(self, other=(), /, **kwds):
'''Initialize an ordered dictionary. The signature is the same as
regular dictionaries. Keyword argument order is preserved.
'''
try:
self.__root
except AttributeError:
self.__hardroot = _Link()
self.__root = root = _proxy(self.__hardroot)
root.prev = root.next = root
self.__map = {}
self.__update(other, **kwds)
근데 Python 3.7부터는 Dictionary 역시 키-값으로 이루어지고 순서를 보장한다고 한다!
2. 장고쉘에서 (역)직렬화 작업 해보기
- Django Shell을 통해 구현한 Serializer가 어떻게 동작하는지 확인할 수 있다.
- serializer를 사용할 시 처음 들어가는 데이터면 create, 이미 들어갔던 데이터라면 update 함수를 타게 된다.
- 또한 serializer를 한 값을 그냥 .save()로 저장하거나 validated_data를 확인하려 하면 오류가 발생한다. -> .is_valid()를 통해 유효한 데이터인지 확인해 줘야 한다.
#Serialize
>>> from polls.models import Question
>>> from polls_api.serializers import QuestionSerializer
>>> q = Question.objects.first()
>>> q
<Question: 제목: 휴가를 어디서 보내고 싶으세요?, 날짜: 2023-02-05 18:52:59+09:00>
>>> serializer = QuestionSerializer(q)
>>> serializer.data
{'id': 1, 'question_text': '휴가를 어디서 보내고 싶으세요?', 'pub_date': '2023-02-05T18:52:59Z'}
>>> from rest_framework.renderers import JSONRenderer
>>> json_str = JSONRenderer().render(serializer.data)
>>> json_str
b'{"id":1,"question_text":"\xed\x9c\xb4\xea\xb0\x80\xeb\xa5\xbc \xec\x96\xb4\xeb\x94\x94\xec\x84\x9c \xeb\xb3\xb4\xeb\x82\xb4\xea\xb3\xa0 \xec\x8b\xb6\xec\x9c\xbc\xec\x84\xb8\xec\x9a\x94?","pub_date":"2023-02-05T18:52:59Z"}'
# Deserialize
>>> import json
>>> data = json.loads(json_str)
>>> data
{'id': 1, 'question_text': '휴가를 어디서 보내고 싶으세요?', 'pub_date': '2023-02-05T18:52:59Z'}
>>> serializer = QuestionSerializer(data=data)
>>> serializer.is_valid()
True
>>> serializer.validated_data
OrderedDict([('question_text', '휴가를 어디서 보내고 싶으세요?')])
>>> new_question = serializer.save() # Create
>>> new_question
<Question: 제목: 휴가를 어디서 보내고 싶으세요?, 날짜: 2023-02-14 18:46:56.209215+00:00>
>>> data={'question_text': '제목수정'}
>>> serializer = QuestionSerializer(new_question, data=data)
>>> serializer.is_valid()
True
>>> serializer.save() # Update
<Question: 제목: 제목수정[시리얼라이저에서 업데이트], 날짜: 2023-04-25 13:15:05.852404+00:00>
#Validation이 통과하지 않는 경우
>>> long_text = "abcd"*300
>>> data = {'question_text':long_text}
>>> serializer = QuestionSerializer(data=data)
>>> serializer.is_valid()
False
>>> serializer.errors
{'question_text': [ErrorDetail(string='Ensure this field has no more than 200 characters.', code='max_length')]}
3. ModelSerializer
- ModelSerializer은 create와 update 기능을 기본적으로 제공하기 때문에 코드로 구현할 필요가 없다. 앞서 작성한 serializer보다 코드가 더 간단하다.
- Meta 클래스 내부의 model 속성을 통해 Serialize할 대상 모델을 지정할 수 있다.
- Meta 클래스 내부의 fields 속성을 통해 Serialize할 대상 필드들을 리스트 형태로 나열하여 지정할 수 있다.
4. API의 VIEW 구현
4-1. HTTP METHOD로 구현
1) GET
정보 조회 기능은 요걸로 구현. 반면 새로운 데이터를 만들어 달라는 요청은 post. 모질라 재단 <HTTP 요청 메서드> 문서에 post 설명으로 나와 있는 "특정 리소스에 엔티티를 제출할 때 쓰입니다" 란 말이 이 말이다.
부가적으로 put의 경우 알다시피 당연 데이터 업데이트인데, 모질라 재단 문서엔 더 정확히 나와있음. "The PUT method replaces all current representations of the target resource with the request payload" 여기서 "요청 페이로드"에 나와 있는 데이터를 이용해 바꾼다는 점은 나도 몰랐기에.. 이런거 주목하자!
좀더 자세히 공부하려면 개발자 도구의 네트워크 탭을 보면 된다. 예시로 프로그래머스에 새로운 질문을 등록하는 상황을 보자. 확인 누르면?
요청 URL, 그의 메서드가 포스트인거 보면 된다.
44233번쨰 질문에 대해 get 요청을 허용한다는 뜻이다.
그럼 수정을 하면?
이번엔 put 인데, post일땐 대상 리소스가 뭔지 정의할 수 없어 url 끝에 44233이란 번호 안붙어 있었는데 이번엔 다르다.
삭제일 땐 delete.
그럼 우리가 detail.html에서
<form action='#' method="post">
이렇게 post 돼있던 게 이상할 수 있다. 새로 만드는 게 아니라 models.py-Choice-votes 에 해당하는 부분을 업뎃하기만 했기 때문에 put이 맞는 것 같아 보일 수 있. 하지만 사용자 관점에서 꼭 그렇지만도 않다. 사용자는 Choice에 vote가 저장돼있는지, 내 투표가 따로 저장되고 있는지 알 방법이 없기 때문. 개발자 입장선 Choice-votes를 count로 구현해 놨기 때문에 업뎃하니까 put이라 생각할 수 있지만, 사용자 입장선 새로운 투표를 제출하는 것이기 때문. 코드 리뷰하다보면 이걸 포스트 풋 중 뭐로 할지 얘기 오갈 때가 있는데 그 때 그 때 맞춰서 하면 되겠다.
'Data > 데엔 데브코스 TIL' 카테고리의 다른 글
231120~24 7주차 AWS - 이론 (0) | 2023.11.27 |
---|---|
231102 목 Day13 - 장고4: 인증 (0) | 2023.11.02 |
231031 화 Day11 - 장고2: 뷰, 템플릿, 폼, 에러 (0) | 2023.10.31 |
231030 월 Day10 - 장고1: 설정, model, timezone (0) | 2023.10.30 |
231027 금 Day9 - 크롤링5: 시각화(seaborn, wordcloud) (0) | 2023.10.27 |