基本帶參路由
@app.route('/show/<name>')
def show1(name):
#在函數(shù)中name表示的就是地址欄上傳遞過來的數(shù)據(jù)
return ‘xxxx’
指定參數(shù)類型的路由
@app.route('/show3/<name>/<int:age>')
def show3(name, age):
pass
#<int:age>:表示age參數(shù)是一個
Flask中所支持的類型轉(zhuǎn)換器:
缺?。? 字符串類型,但不能有/斜杠
int: 整形
float: 浮點
多URL的路由匹配
允許在一個視圖函數(shù)中設(shè)置多個url的路由規(guī)則
@app.route('/')
@app.route('/index')
def index():
pass
路由中設(shè)置HTTP請求方法
Flask路由規(guī)則也允許設(shè)置對應(yīng)的請求方法,只有將配置上請求方法的路徑交給視圖函數(shù)處理執(zhí)行
@app.route('/post',methods=['GET','POST'] )
#限定了訪問的請求方式,只有g(shù)et和post能訪問
URL反向解析
正向解析:程序自動解析,根據(jù)@app.route()中的訪問路徑來匹配處理函數(shù)
反向解析:通過視圖處理函數(shù)的名稱自動生成視圖處理函數(shù)的訪問路徑
Flask中提供了url_for()函數(shù):用于反向解析url,
第一個參數(shù):指向函數(shù)名(通過@app.route()修飾的函數(shù)名稱),后續(xù)的參數(shù):對應(yīng)要構(gòu)建的url上的變量
@app.route('/'):
def index():
pass
@app.route('/show/<name>')
def show(name):
return "name:%s" % name
url_for('index'):#結(jié)果為 /
url_for('show',name='xxx')#結(jié)果為:/show/zsf