Flask——路由與變量

1 路由與視圖

@app.route("/")
def	hello():
	return	"Hello	World!"

這三行代碼的意思就是:如果瀏覽器要訪問服務器程序的根地址("/"),那麼Flask 程序實例就會執行函數 hello() ,返回『Hello World!』。
也就是說,上面三行代碼定義了一個 URL 到 Python 函數的映射關係,我們將處理這種映射關係的程序稱爲『路由』,而hello()就是視圖函數。

2 動態路由

假設服務器域名爲 https://hello.com , 我們來看下面一個路由:

@app.route("/ethan")
def	hello():
	return	'<h1>Hello,	ethan!</h1>'

再來看一個路由:

@app.route("/peter")
def	hello():
	return	'<h1>Hello,	peter!</h1>'

可以看到,上面兩個路由的功能是當用戶訪問https://hello.com/<user_name> 時,網頁顯示對該用戶的問候。按上面的寫法,如果對每個用戶都需要寫一個路由,那麼 100 個用戶豈不是要寫 100 個路由!這當然是不能忍受的,可以設置一個動態路由,這一的話一個路由就夠了!看下面:

@app.route("/<user_name>")
def	hello(user_name):
	return	'<h1>Hello,	%s!</h1>'	%	user_name

任何類似 https://hello.com/<user_name> 的 URL 都會映射到這個路由上,比如 https://hello.com/ethan-funny , https://hello.com/torvalds ,訪問這些 URL 都會執行上面的路由程序。
也就是說,Flask 支持這種動態形式的路由,路由中的動態部分默認是字符串,像上面這種情況。

常用動態路由的規則:
1). url路由的一部分可以標記爲變量, <變量名>;
2):. flask中路由變量可以指定的類型: int, string, float, uuid

@app.route("/<int:id>/comments/")
def comments(id):
    return "這是一個%s評論頁面" %(id)

# 字符穿
@app.route("/welcome/<string:username>/")
def welcome(username):
    return  "<h1>歡迎用戶%s登陸網站</h1>" %(username)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章