Django에서 템플릿을 사용하지 않고 JSON을 반환하려면 어떻게 해야 하나요?
이는 다음 질문과 관련이 있습니다.클라이언트 Python에 따라 Json과 html을 반환하는 Django
저는 Django 앱용 명령줄 Python API를 가지고 있습니다.API를 통해 앱에 접속하면 JSON이 반환되고 브라우저에서는 HTML이 반환됩니다.다른 URL을 사용하여 다른 버전에 접속할 수 있는데 어떻게 템플릿 하나로 views.py에서 HTML 템플릿과 JSON을 렌더링할 수 있습니까?
HTML을 렌더링하려면 다음 명령을 사용합니다.
return render_to_response('sample/sample.html....')
JSON JSON (the (the)content-type
should be application/json
text/html
)
JSON 및 HTML 출력은 어떻게 결정됩니까?
그래서 제가 봤을 때.py:
if something:
return render_to_response('html_template',.....)
else:
return HttpReponse(jsondata,mimetype='application/json')
당신이 무엇을 원하는지 문제가 혼란스러워진 것 같아요.실제로 HTML을 JSON 응답에 넣으려고 하는 것이 아니라 HTML 또는 JSON 중 하나를 반환하고 싶다고 생각합니다.
먼저, 두 가지 사이의 핵심 차이점을 이해할 필요가 있습니다.HTML은 프레젠테이션 형식입니다.데이터 자체보다 데이터를 표시하는 방법을 더 많이 다룹니다.JSON은 반대야.이것은 순수 데이터입니다.기본적으로 일부 Python(이 경우) 데이터셋의 JavaScript 표현입니다.이것은 단순히 교환 레이어 역할을 하며, 일반적으로 서로 액세스할 수 없는 앱의 한 영역(보기)에서 다른 영역(JavaScript)으로 데이터를 이동할 수 있습니다.
이를 염두에 두고 JSON을 "렌더"하지 않으며 템플릿도 포함되지 않습니다.재생 중인 데이터(대부분 템플릿에 컨텍스트로 전달되는 데이터)를 JSON으로 변환하기만 하면 됩니다.이는 자유 형식 데이터인 경우 Django의 JSON 라이브러리(simplejson)를 통해, 쿼리셋인 경우 직렬화 프레임워크를 통해 수행할 수 있습니다.
심플
from django.utils import simplejson
some_data_to_dump = {
'some_var_1': 'foo',
'some_var_2': 'bar',
}
data = simplejson.dumps(some_data_to_dump)
시리얼화
from django.core import serializers
foos = Foo.objects.all()
data = serializers.serialize('json', foos)
어느 쪽이든 해당 데이터를 응답에 전달합니다.
return HttpResponse(data, content_type='application/json')
[편집] 장고 1.6 이전 버전에서는 응답을 반환하는 코드가
return HttpResponse(data, mimetype='application/json')
[EDIT]: simplejson이 django에서 제거되었습니다. 다음을 사용할 수 있습니다.
import json
json.dumps({"foo": "bar"})
'아까보다'를 .django.core.serializers
상기와 같이
Django 1.7에서는 내장된 Json Response를 통해 이를 더욱 쉽게 수행할 수 있습니다.
https://docs.djangoproject.com/en/dev/ref/request-response/ #json response-module
# import it
from django.http import JsonResponse
def my_view(request):
# do something with the your data
data = {}
# just return a JsonResponse
return JsonResponse(data)
JSON 응답의 경우 렌더링할 템플릿이 없습니다.템플릿은 HTML 응답을 생성하기 위한 것입니다.JSON은 HTTP 응답입니다.
그러나 JSON 응답을 사용하여 템플리트에서 렌더링된 HTML을 가질 수 있습니다.
html = render_to_string("some.html", some_dictionary)
serialized_data = simplejson.dumps({"html": html})
return HttpResponse(serialized_data, mimetype="application/json")
JSON에서 모델을 django 1.9로 렌더링하기 위해 다음과 같은 작업을 수행해야 했습니다.py:
from django.core import serializers
from django.http import HttpResponse
from .models import Mymodel
def index(request):
objs = Mymodel.objects.all()
jsondata = serializers.serialize('json', objs)
return HttpResponse(jsondata, content_type='application/json')
Django REST 프레임워크는 사용할 렌더러를 자동으로 결정하기 위해 요청의 HTTP accept 헤더를 사용하는 것으로 보입니다.
http://www.django-rest-framework.org/api-guide/renderers/
HTTP accept 헤더를 사용하면 "if something"에 대한 대체 소스를 제공할 수 있습니다.
또한 rfc에 지정된 대로 request accept 콘텐츠유형을 체크할 수도 있습니다.이 방법으로 기본 HTML을 렌더링할 수 있으며 클라이언트가 응용 프로그램/제이슨을 수락한 경우 템플릿이 필요하지 않고 응답에 json을 반환할 수 있습니다.
from django.utils import simplejson
from django.core import serializers
def pagina_json(request):
misdatos = misdatos.objects.all()
data = serializers.serialize('json', misdatos)
return HttpResponse(data, mimetype='application/json')
다음은 요청 내용에 따라 json 또는 html을 조건부로 렌더링하기 위해 필요한 예입니다.Accept
머리글자
# myapp/views.py
from django.core import serializers
from django.http import HttpResponse
from django.shortcuts import render
from .models import Event
def event_index(request):
event_list = Event.objects.all()
if request.META['HTTP_ACCEPT'] == 'application/json':
response = serializers.serialize('json', event_list)
return HttpResponse(response, content_type='application/json')
else:
context = {'event_list': event_list}
return render(request, 'polls/event_list.html', context)
당신은 이것을 컬이나 httpie로 테스트할 수 있다.
$ http localhost:8000/event/
$ http localhost:8000/event/ Accept:application/json
주의: 사용하지 않기로 선택하였습니다.JsonReponse
불필요하게 모델을 재시리얼화할 수 있기 때문입니다.
결과를 렌더링된 템플릿으로 전달하려면 템플릿을 로드하고 렌더링한 결과를 json에 전달합니다.다음과 같은 경우가 있습니다.
from django.template import loader, RequestContext
#render the template
t=loader.get_template('sample/sample.html')
context=RequestContext()
html=t.render(context)
#create the json
result={'html_result':html)
json = simplejson.dumps(result)
return HttpResponse(json)
이렇게 하면 렌더링된 템플릿을 json으로 클라이언트에 전달할 수 있습니다.이 기능은 다양한 요소를 포함하는 a를 완전히 대체하려는 경우 유용합니다.
언급URL : https://stackoverflow.com/questions/9262278/how-do-i-return-json-without-using-a-template-in-django
'itsource' 카테고리의 다른 글
Angular가 DOM에 스코프 업데이트를 추가한 후 메서드를 트리거하는 방법은 무엇입니까? (0) | 2023.02.26 |
---|---|
Oracle Date Time in Where 절? (0) | 2023.02.26 |
약속 오류: 개체가 반응 자식 개체로 유효하지 않습니다. (0) | 2023.02.14 |
웹 팩을 사용하여 라이브러리 소스 맵을 로드하는 방법 (0) | 2023.02.14 |
Ajax 요청에 대한 전체 페이지 업데이트 (0) | 2023.02.14 |