接下來的四天會來講述此專案會使用到的 Flask 概念,而今天要來分享的是 Python Flask URL 的使用,把路徑的設定和應用和大家講述!
@app.route("/")
def index():
return "Hello World!"
由以上的程式碼可以知道,整體組成分成兩個部分,分別是:
@app.route("/") => 主要設定 URL 路徑。def index() => 設定該 URL 路徑中要進行的處理和返回,並且函式名可以自己取,這裡以 index 為例。@app.route("/first/second")
def index():
return "Hello World"
此為一般路徑的寫法,填入想要的路徑以後,設定返回值,因此在此範例中,當你啟動 Flask 輸入 http://localhost:5000/first/second 即可得到 Hello World
@app.route("/first/<name>")
def index(name):
return "My name is " + name
此為加入參數的路徑寫法,主要注意點如以下:
/first/name 此路徑使用,會使用 <> 刮起來是為了要辨別此是參數。<name> 當中的 name 要填入 index(name),此為 Python Flask 獲取參數值的方法。<name> 的參數型態,則其會套用預設的型態,str。在此範例中,輸入了 http://localhost:5000/first/kyle 後,即可得到 My name is Kyle。
@app.route("/first/<int:age>")
def index(age):
return "My age is " + str(age)
此為加入參數的路徑寫法,主要注意點如以下:
str、int、float、path,而 str 為預設的參數。age 本身參數型態為 int,因此這裡做了 str(age) 轉換變數型態的處理。在此範例中,輸入了 http://localhost:5000/first/22 後,即可得到 My age is 22。