๐[Django] Django JsonResponse safe ์์ฑ?
JsonResponse?
JsonResponse
๋ Django์์ HTTP ์๋ต์ ์ํด ์ฌ์ฉํ๋ ํด๋์ค์.
Response
ํด๋์ค๋ฅผ ์์๋ฐ์ JSON ํํ์ HTTP ์๋ต ํด๋์ค๋ก, dict
, list
, json ์ง๋ ฌํ ๊ฐ๋ฅํ ๊ฐ์ฒด
๋ฑ์ ๋ฐ์ดํฐ๋ฅผ JSON ํํ๋ก response ํ ์ ์์.
JsonResponse ํด๋์ค๋ Response Body๋ก ์ ๋ฌ๋๋ ๋ฐ์ดํฐ๋ฅผ ์๋์ผ๋ก JSON์ผ๋ก ์ง๋ ฌํํ์ฌ ์ฒ๋ฆฌํ๊ณ , Content-Type ํค๋ฌ๋ฅผ application/json
์ผ๋ก ์ค์ ํ์ฌ ํด๋ผ์ด์ธํธ์๊ฒ JSON ์๋ต์์ ๋ช
์ํ๋ค.
์ฆ, Response
ํด๋์ค๋ ๋ค์ํ ์๋ต์, JsonResponse
๋ JSON ํํ์ ์๋ต์ ๋ด๋นํ๋ ๋๋ค์ธ ๊ฒ์ด๋ค.
์ฌ๊ธฐ์ JsonResponse์ safe
๋ผ๋ ์ต์
ํ๋๊ฐ ์กด์ฌํ๋๋ฐ, ์ด๊ฒ ๋ญ์ง ๊ถ๊ธํ๋ค.
safe=False?
JsonResponse
๋ ๊ธฐ๋ณธ์ ์ผ๋ก JSON ๊ฐ์ฒด๋ง ํ์ฉํ๋๋ก ๋์ด์์.
๋ฐ๋ผ์ JSON ๋ฐฐ์ด์ ๋ฐํํ ๋๋ safe=False
๋ฅผ ํด์ฃผ๋ ๊ฒ์ด๋ค.
์ฆ, json(dict) ์ด์ธ์ ํ์๋ ๋ณํ ๊ฐ๋ฅํ๋ค๋ ๋ง์..!
- ๋ง์ฝ
safe=True
๋ก ํ๊ณ , json ์ด์ธ์ ๊ฐ์ ๋ณด๋ด๋ฉดType Error
๊ฐ ๋ฐ์ํ ๊ฒ์ด๋ค!
safe ๋งค๊ฐ๋ณ์์ ์ฌ๋ฐ๋ฅธ ์ฌ์ฉ
>>> response = JsonResponse({"key1":"value1", "key2":"value2"}, safe=True)
>>> response = JsonResponse({"key1":[1, 2, 3], "key2":"value1"}, safe=True)
>>> response = JsonResponse([1, 2, 3], safe=False)
safe ๋งค๊ฐ๋ณ์์ ์๋ชป๋ ์ฌ์ฉ
>>> response = JsonResponse([1, 2, 3], safe=True)
>>> response = JsonResponse({[1, 2, 3]}, safe=True)
TypeError: In order to allow non-dict objects to be serialized set the safe parameter to False.
์ฌ๊ธฐ์ safe๋ผ๋ ์ด๋ฆ ๋๋ฌธ์ ๋ณด์์ ์ธ ์ธก๋ฉด์์ ์ทจ์ฝํ์ง ์์๊น ํ๋ ์์ฌ์ด ๋๋๋ฐ, ๋ณด์์์ ๋ฌธ์ ๊ฐ ๋ฐ์ํ ๊ฐ๋ฅ์ฑ์ ๋ฎ๋ค๊ณ ํ๋ค.
JSON ๋ฐฐ์ด์ ๋ฐํํ ๋, safe=False
๋ฅผ ์ค์ ํ๋ฉด ํด๋ผ์ด์ธํธ๊ฐ JSON ๋ฐฐ์ด์ ๋ํ ์ฒ๋ฆฌ๋ฅผ ์ํํ ์ ์๋๋ก ํ์ฉํ๋๊ฒ์ด๋ฉฐ, ์ด๋ ์ผ๋ฐ์ ์ผ๋ก ๋ณด์์์ ๋ฌธ์ ๋ฅผ ๋ฐ์์ํค๋ ์์ธ์ด ์๋๊ธฐ ๋๋ฌธ์ด๋ค.
ํ์ง๋ง, ํด๋ผ์ด์ธํธ๊ฐ JSON ๋ฐฐ์ด์ ์์ ํ๊ฒ ์ฒ๋ฆฌํ๋ค๋ ๊ฐ์ ํ์ ๊ทธ๋ฐ ๊ฒ์ด๊ณ , ํด๋ผ์ด์ธํธ์์ ์ ์ ํ ์ฒ๋ฆฌ๋ฅผ ํ์ง ์๋ ๊ฒฝ์ฐ์๋ ๋ฌธ์ ๊ฐ ๋ฐ์ํ ์ ์๋ค..
๊ทธ๋ฌ๋ฏ๋ก ํด๋ผ์ด์ธํธ์์ JSON ๋ฐฐ์ด์ ์์ ํ๊ฒ ์ฒ๋ฆฌํ์ง ๋ชปํ๋ ๊ฒฝ์ฐ๋ผ๋ฉด ๋ค๋ฅธ ๋ฐฉ๋ฒ์ ๊ณ ๋ คํด์ผ ํ๋ค..!
๋๊ธ๋จ๊ธฐ๊ธฐ