HTML form 태그에서 기본으로 지원하는 인코딩
<form action="https://httpbin.org/post" method="post"
enctype="application/x-www-form-urlencoded">
<input type="text" name="message" />
<input type="file" name="photo" />
<input type="submit"/>
</form>
enctype에서 지정하거나 enctype을 생략해도 기본 default로 urlencoded가 지정된다!
요청 Raw 데이터
message(key)=hello(value)&photo=profile.jpg
문자열로 key:value를 묶는 인코딩 특성상 파일전송은 불가능하다.
HTML from 태그에서는 GET/POST 요청만을 지원하기 때문에
데이터 조회 시 request.POST로 요청 데이터 조회가 가능하다.
하지만 DRF의 API에서 요청 데이터 조회는 아래와 같이 가능하다!
request.data["message"]
request.data["photo"]
request.data 속성은 request.POST + .FILES와 동일한 기능으로 사용된다.
PUT/PATCH 요청에서도 동일하게 .data 속성으로 요청 데이터 참조가 가능하다!
파일 전송이 가능한 유일한 인코딩!
<form action="https://httpbin.org/post" method="post"
enctype="multipart/form-data">
<input type="text" name="message" />
<input type="file" name="photo" />
<input type="submit"/>
</form>
enctype="multipart/form-data"로 지정한다!
요청 Raw 데이터
------WebKitFormBoundary2p1xAnK5YSFySSB6
Content-Disposition: form-data; name="message"
hello
------WebKitFormBoundary2p1xAnK5YSFySSB6
Content-Disposition: form-data; name="photo"; filename="profile.jpg"
Content-Type: image/jpeg
파일내용
------WebKitFormBoundary2p1xAnK5YSFySSB6--
DRF의 API에서 요청 데이터 조회는 아래와 같이 가능하다!
request.data["message"]
request.data["photo"]
API에서 많이 사용되는 인코딩!
JSON 인코딩으로 아래와 같이 요청!
<script>
(async function () {
const url = "https://httpbin.org/post";
const params = {message: "hello"};
const jsonString = JSON.stringify(params);
const res = await fetch(url, {
method: "POST",
headers: {"Content-Type": "application/json"},
body: jsonString,
});
console.log("res.json :", await res.json());
})();
</script>
코드에서 아래의 순서대로 요청 시 인코딩이 진행된다!
const params = {message: "hello"};
const jsonString = JSON.stringify(params);
body: jsonString
요청 Raw 데이터
{"message":"hello"}
마찬가지로 문자열 형식으로 파일업로드는 지원하지 않는다.
HTML Form 태그와 Django 기본 view는 application/json 인코딩 미지원하며 Django의 경우에는 아래와 같이 추가적으로 직접 변환이 필요하다.
import json
@api_view(["POST"])
def post_new(request):
request.POST # 빈 QueryDict
request.FILES # 빈 MutiValueDict
request.body # b'{"message": "hello"}'
request_data = json.loads(request.body)
request_data["message"]
추가적인 직접 변환 없이 단순하게 request.body을 통해 요청 Raw 데이터 조회는 가능하다!
DRF의 API에서 요청 데이터 조회는 아래와 같이 가능하다!
def post_new(request):
request.data["message"]
3개의 인코딩을 모두 지원하며
모두 requset.data(POST,PUT,PETCH,FILES) 단일 속성으로 요청 데이터의 조회가 가능하다!