從問題說開去
接口又返回了亂碼咋辦呢?
看現象, 查原因
$: curl http://127.0.0.1:8000
{"code": "00", "message": "\u6570\u636e\u7c7b\u578b\u9519\u8bef", "data": {}}
- 貼到瀏覽器窗口看

- ipython打開貼上去看
In [3]: {"code": "00", "message": "\u6570\u636e\u7c7b\u578b\u9519\u8bef", "data"
...: : {}}
Out[3]: {'code': '00', 'message': '數據類型錯誤', 'data': {}}
說明瀏覽器和ipython都可以解碼


后端怎么給前端准備數據的?
//正常 后端json.dumps返回數據, 設置response的請求頭application/json
data = {
"code": "00",
"message": "數據類型錯誤",
"data": {},
}
josn.dumps(data) # 這種即會造成上面出現的亂碼現象.
//后端修復:
josn.dumps(data, ensure_ascii=false)
If ``ensure_ascii`` is false, then the return value can contain non-ASCII
characters if they appear in strings contained in ``obj``. Otherwise, all
such characters are escaped in JSON strings.
因為data中有非ascii,所以確定都是ascii項為false
為什么會亂碼?
世界上存在着多種編碼方式,同一個二進制數字可以被解釋成不同的符號。
因此,要想打開一個文本文件,就必須知道它的編碼方式,否則用錯誤的編碼方式解讀,就會出現亂碼。
為什么電子郵件常常出現亂碼?就是因為發信人和收信人使用的編碼方式不一樣。
前端返得到那些亂碼是什么
\u#### 表示一個Unicode編碼的字符, 6570為unicode碼點
"\u6570"
python3中b'\xe4\xb8\xad\xe6\x96\x87' 又是什么東西
b'\xe4\xb8\xad\xe6\x96\x87' # 帶b的表示bytes類型數據
bytes是一種比特流,它的存在形式是01010001110這種.
如上表示,\x表示轉義, 用十六進制展示.
str使用utf8編碼成下面的了
>>> s = "中文"
>>> s
'中文'
>>> type(s)
<class 'str'>
>>> b = bytes(s, encoding='utf-8')
>>> b
b'\xe4\xb8\xad\xe6\x96\x87' #\x 代表是十六進制
>>> type(b)
<class 'bytes'>
str使用unicode編碼成下面的了
In [15]: bytes(s, encoding='unicode_escape')
Out[15]: b'\\u4e2d\\u6587'
關於unicode如何映射到utf8編碼的轉換規則, 可以看上面鏈接.
python3 str和bytes轉換
# py3默認用utf8, 解決py2默認用ascii對中文不友好的坑.
>>> import sys
>>> sys.getdefaultencoding()
'utf-8'
>>>

encode 負責字符到字節的編碼轉換。默認使用 UTF-8 編碼准換。
In [16]: s = "毛台"
In [17]: s.encode()
Out[17]: b'\xe6\xaf\x9b\xe5\x8f\xb0'
In [19]: s.encode("gbk")
Out[19]: b'\xc3\xab\xcc\xa8'
decode 負責字節到字符的解碼轉換,通用使用 UTF-8 編碼格式進行轉換。
In [21]: b'\xe6\xaf\x9b\xe5\x8f\xb0'.decode()
Out[21]: '毛台'
n [22]: b'\xc3\xab\xcc\xa8'.decode("gbk")
Out[22]: '毛台'
獲取字符的unicode編碼: ord(),和chr()
In [12]: chr(0x4e25)
Out[12]: '嚴'
In [13]: ord('嚴')
Out[13]: 20005
