기본 콘텐츠로 건너뛰기

[Python] Flask Response Encoding 문제

[Python] Flask Response Encoding 문제

파이썬에서 response를 보내는데, utf8이아닌, 유니코드 그대로 보내지고, 화면에 출력되는 문제가 발생했다. 정말 파이썬 하면서 encoding 문제는 진짜… 항상 마주할때마다 이렇게 해서 고쳐야지~라고 생각하고 고쳤을때 바로 안되면, 그냥 당황스럽기 짝이없음.

{

"code": 100,

"data": {

"\uc548\ub155": 2,

"\ud558\uc774\ub8e8": 2

},

"mesg": "success",

"method": "get",

"target": "/api/test",

"time": 0.001

}

아무래 utf8로 encoding을 해도 결과는 같음, postman에서 json으로 보면 아주 예쁘게 보여서 content-type을 appliction/json으로 보내면 되나 했더니 그것도 안되니, 이제 여기서부터 당황 스러움이 시작되었다.

아무튼 결론적으로 엄청나게 삽질을하고 삽질을 했다.

문제는 내가 response를 할때 dict의 형태로 생성해서 보내는게 가장 문제

flask에서 지원하는 make_response를 사용하면 문제는 쉽게 해결을 할 수 있다.

함수 내부에서 header에 text/html; charset=utf-8를 설정해주기 때문에 문제 없이 utf8로 응답이 보내진다.

이전에는 header없이 body만 전달했기 때문에 unicode그대로 화면에 출력을 했다.

flask의 make_response를 사용하기 위해서는 아래와 같이 사용한다.

{"code": 100, "target": "/api/test", "mesg": "success", "time": 0.0018, "data": {"안녕": 2}, "method": "get"}

[참고]

http://flask.pocoo.org/docs/0.12/api/#flask.Flask.response_class

http://flask.pocoo.org/docs/0.12/api/#flask.Response

from http://ourcstory.tistory.com/234 by ccl(A) rewrite - 2020-03-07 12:54:57

댓글

이 블로그의 인기 게시물

Flask 13. pythonanywhere에 배포하기

Flask 13. pythonanywhere에 배포하기 Login: PythonAnywhere It's always a pleasure to hear from you! Ask us a question, or tell us what you love or hate about PythonAnywhere. We'll get back to you over email ASAP. Sorry, there was an error connecting to the server. Please try again in a few moments... www.pythonanywhere.com from http://ohdowon064.tistory.com/124 by ccl(A) rewrite - 2020-03-11 15:54:10

외래어 정리

외래어 정리 [A] acacia 아카시아 academic 아카데믹 academy 아카데미 acanthus 아칸서스 accelerator 액셀러레이터 accent 악센트 acceptor 억셉터 access 액세스 accessory 액세서리 accordion 아코디언 ace 에이스 acetate 아세테이트 acetaldehyde 아세트알데히드 acetic acid 아세트(산) acetone 아세톤 acetyl 아세틸 acetylene 아세틸렌 Achilles tendon 아킬레스(건) acre 에이커 acrylic acid 아크릴(산) action 액션 active 액티브 acyl 아실 AD 에이디 adagio 아다지오 adapter 어댑터 ad + balloon 애드벌룬 address 어드레스 adenine 아데닌 adrenaline 아드레날린 advantage 어드밴티지 aerobic dance 에어로빅 댄스 aerofoil 에어로포일 aerosol 에어로졸 afghan 아프간 [편물] after + service 애프터서비스 agape 아가페 Ainu 아이누 air conditioner 에어컨(디셔너) airspray 에어스프레이 album 앨범 albumin 알부민 alcohol 알코올 aldehyde 알데히드 ALGOL 알골 algorism 알고리즘 alibi 알리바이 alkali 알칼리 alkaloid 알칼로이드 Allah 알라 allegory 알레고리 allegretto 알레그레토 allegro 알레그로 alleluia 알렐루야 Allergie 알레르기 alligator 앨리게이터 all-in-one 올인원 almond 아몬드 aloha 'oe 알로하 오에 Alpenhorn 알펜호른 alpha 알파 alphabet 알파벳 ...