django + django restframework 에서, parameter 로 json 을 사용하는 방법을 알아보자.
parameter 로 json 사용하기
ref. 1 을 보면 json 형식의 parameter 를 넘어올 때 어떻게 처리하는지 알 수 있다. 일단 개략적인 절차는 아래와 같다.- 클라이언트
- request 의 contentType 을 'applicaton/json' 으로 설정한다.
- POST type (GET 도 가능하겠지만, 여기선 생략한다.)
- parameter 를 JSON string 으로 변경한다.
- 서버
- view class 에 parser_classes = (JSONParser, ) 를 설정하면, JSONParser 가 설정되고 이녀석이 media type 'application/json' 에 대한 처리를 담당하게 된다. 이녀석은 default 로 설정된 녀석이라 이부분은 필요없다. 참고로 알아두기만 하자. 참고로 위처럼 JSONParser 만 설정하면 다른 media type 에 대한 처리가 안되지 참고하자.
- request.data 에 parameter 가 들어가 있다.
javascript code
# coffee script code
param = {
param1: {
param11: 'test11',
param12: 'test12',
},
param2: 'test2',
}
$.ajax
contentType: 'application/json'
url: url,
data: JSON.stringify(param)
type:'POST'
dataType: 'json'
cache: false
success: (res) ->
console.log("success")
return
django restframework code
from rest_framework.authentication import SessionAuthentication
from rest_framework.parsers import JSONParser
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from beluga.utils.resp import success
class FactorsEarningRatioView(APIView):
"""
"""
authentication_classes = (SessionAuthentication, )
permission_classes = (IsAuthenticated,)
# parser_classes = (JSONParser, )
def post(self, request):
"""
:param request:
:return:
"""
print request.data
return Response(data=success({}))
댓글 없음:
댓글 쓰기