공부2021. 10. 19. 09:04

django-deubg-toolbar 사용을 할 때, DRF를 사용하신다면 return값이 response content가 json 이기 때문에 django-debug-toolbar가 제대로 작동 안합니다.

 

이럴 경우 사용하기 위해서 미들웨어를 사용해서 리턴값을 바꿔줘야하는데요 그래야지 html이 랜더링되서 나가게 됩니다.

아래 블로그처럼 진행하면 django-debug-toolbar 를 jsonresponse에서도 사용할 수 잇습니다.

https://khsiea.github.io/2018/04/30/django-debug-toolbar.html

 

django-debug-toolbar 소개 - Heesang Blog

장고 웹 개발에 있어서 유용한 디버그 툴에 대해서 소개를 하려고 합니다. django-debug-toolbar 입니다. django-debug-toolbar 사이트 : https://django-debug-toolbar.readthedocs.io/en/stable/installation.html 설치하기 pip ins

khsiea.github.io

 

그러나 저같은경우는 윗 소스를 적용했을 때 툴바 클릭시 아래와 같은 오류가 있었습니다.

Unexpected token < in JSON at position 1 

오류가 발생하게 됩니다. 또한 받아지는 json 응답의 한글이 깨져서 보이게 됩니다.

 

따라서 미들웨어를 조금 수정해줬습니다.

 

 

from django.utils.deprecation import MiddlewareMixin
from django.http import HttpResponse
from config.settings import STAGE, STATICFILES_DIRS
import json


class NonHtmlDebugToolbarMiddleware(MiddlewareMixin):

def process_response(self, request, response):
if STAGE == "development":
print(request.path_info)
if (response["Content-Type"] == "application/json") and ("__debug__" not in request.path_info):
content = json.dumps(json.loads(response.content), sort_keys=True, indent=2, ensure_ascii=False)
response = HttpResponse(u'<html><body><pre>{}</pre></body></html>'.format(content))
return response

 

위의 소스에 있는 클래스를 미들웨어에 추가하면 제대로 django-debug-toolbar가 작동하는 모습을 볼 수 있습니다.

 

django-debug-toolbar에서 __debug__ url 을 사용한다는 점과,

json.loads에 ensure_ascii 옵션을 추가하여 한글이 깨지는것을 방지했습니다.

 

대신 한가지 문제점으로 response 컨텐트 타입이 text/html 로 변하기 때문에 기존 json과 달라진다는 점이 있습니다.

 

 

아래 소스코드를 참고했습니다.

https://gist.github.com/fabiosussetto/c534d84cbbf7ab60b025

 

Enable Django toolbar for JSON responses

Enable Django toolbar for JSON responses. GitHub Gist: instantly share code, notes, and snippets.

gist.github.com

 

Posted by richcherry