出處: Youtube 彭彭的課程 Python Flask 網站後端開發 – 回應與導向 Response & Redirect
實作筆記
將字典轉成Json格式的字串
import json
@app.route("/")
def index():
lang =request.headers.get("accept-language")
if lang.startswith("en"):
return json.dumps({
"status":"ok",
"text":"Hi"
})
elif lang.startswith("ja"):
return json.dumps({
"status":"ok",
"text":"こにちは"
},ensure_ascii = False) #指示不要用ASCII碼處理日文
else:
return json.dumps({
"status":"ok",
"text":"你好"
},ensure_ascii = False) #指示不要用ASCII碼處理中文

沒加ensure_ascii = False

有加ensure_ascii = False

關於 Redirect 模組 的重新導向
from flask import redirect #import redirect物件
#建立路徑 /en/ 對應的處理函式
@app.route("/en/")
def index_english():
return json.dumps({
"status":"ok",
"text":"Hi"
})
#建立路徑 /ja/ 對應的處理函式
@app.route("/ja/")
def index_japanese():
return json.dumps({
"status":"ok",
"text":"こにちは"
},ensure_ascii = False) #指示不要用ASCII碼處理日文
#建立路徑 /other/ 對應的處理函式
@app.route("/other/")
def index_other():
return json.dumps({
"status":"ok",
"text":"你好"
},ensure_ascii = False) #指示不要用ASCII碼處理中文
@app.route("/")
def index():
lang =request.headers.get("accept-language")
if lang.startswith("en"):
return redirect("/en/")
elif lang.startswith("ja"):
return redirect("/ja/")
else:
return redirect("/other/")
#回傳網站首頁的內容

因為瀏覽器偏好是日文,所以會導向到/ja/顯示日文

因為瀏覽器偏好是中文,所以會導向到/other/顯示中文

不想改偏好但想要看英文也可以直接自己手動導向 http://127.0.0.1:1000/en/
那也是可以直接看英文版的hi
