一、路由
1、什么是路由?
在入門篇中我們已經(jīng)實現(xiàn)了一個最小的Flask應用,當我們訪問到http://127.0.0.1:5000/ 時頁面就會顯示出我們在hello()返回的“Hello World!”。像在這個應用中的route("/")裝飾器將一個方法綁定到某一個指定的URL上就叫做路由。
2、路由變量規(guī)則
在URL中可以添加變量,<variable_name>標記變量的名字, 可以作為命名參數(shù)傳遞到視圖函數(shù)中使用??筛鶕?jù)規(guī)則<converter:variable_name>來指定一個可選的轉(zhuǎn)換器。如:
@app.route("/<name>/")
def print_name(name):
return "名字是:%s" % name
?
@app.route("/<int:age>/")
def print_age(age):
return "年齡是:%d" % age
?
@app.route("/<float:height>/")
def print_height(height):
return "身高是:%s" % height
支持的轉(zhuǎn)換器有:
| 數(shù)據(jù)類型 | |
|---|---|
| int | 整型變量 |
| float | 整型或浮點型變量 |
| path | 和默認的相似,但也接受斜線 |
規(guī)范的URL在末尾帶有”/“。如:
app.route("/home/")
def hello():
return "in home!"
?
app.route("/outside")
def hello():
return "outside!"
如果在瀏覽器中輸入”http://127.0.0.1:5000/home“或者”http://127.0.0.1:5000/home/“你都可以看到輸出”in home!“;
當在瀏覽器中輸入”http://127.0.0.1:5000/outside“你可以看到”outside“,但是輸入”http://127.0.0.1:5000/outside/“你可能就會看到”404“;
3、構造URL
url_for()方法可以構造一個url。該方法的第一個參數(shù)是str類型,是一個試圖函數(shù)名, 后面可添加在url中聲名的命名參數(shù),或者get請求的其他參數(shù)。
from flask import url_for
?
@app.route("/hello/")
def hello(height):
return "hello"
?
@app.route("/yourname/<name>/")
def print_name(name):
return "名字是:%s" % name
?
@app.route("/yourage/")
def print_age():
return "年齡是:%s" % request.args.get("age", "18")
?
print(url_for('hello'))
print(url_for('print_name', name="Mike"))
print(utl_for('print_age', age=20))
優(yōu)點:
描述性好,修改方便;
轉(zhuǎn)義特殊字符和Unicode數(shù)據(jù);
方便處理復雜的路由關系;
二、HTTP方法
HTTP方法("謂詞"),常見的有:
GET:獲取頁面信息,通過
?參數(shù)名=值&參數(shù)名=值...傳遞數(shù)據(jù);POST:通常是html通過表單給服務器傳數(shù)據(jù)的方法;
HEAD:獲取消息頭;
PUT:與POST類似,但是服務器可能觸發(fā)了存儲過程多次,多次覆蓋掉舊值。
DELETE:刪除給定位置的信息;
OPTIONS:給客戶端提供一個敏捷的途徑來弄清這個 URL 支持哪些 HTTP 方法。
可以在route('/',methods=[])methods中指定允許的請求方法。默認為“GET”方法。
@app.route('/', methods=["GET", "POST"])
def hello():
pass
后記
繼續(xù)整理,如有錯誤之處還請多多指教!(o?v?)ノ