您好,登錄后才能下訂單哦!
本文實(shí)例講述了flask框架路由常用定義方式。分享給大家供大家參考,具體如下:
路由的各種定義方式
請(qǐng)求方式限定
使用 methods 參數(shù)指定可接受的請(qǐng)求方式,可以是多種
@app.route('/',methods=['GET']) def hello(): return '<h2>hello world</h2>'
路由查找方式
同一路由指向兩個(gè)不同的函數(shù),在匹配過程中,至上而下依次匹配
@app.route('/') def hello(): return '<h2>hello world</h2>' @app.route('/') def hello_2017(): return '<h2>hello 2017</h2>'
所以上面路由 / 輸出的結(jié)果為 hello 函數(shù)的結(jié)果
給路由傳參示例
有時(shí)我們需要將同一類URL映射到同一個(gè)視圖函數(shù)處理,比如:使用同一個(gè)視圖函數(shù) 來顯示不同用戶的個(gè)人信息。
路由傳遞的參數(shù)默認(rèn)當(dāng)做string處理,這里指定int,尖括號(hào)中的內(nèi)容是動(dòng)態(tài)的,也可不指定類型
@app.route('/user/<int:id>') def hello_itheima(id): return 'hello itcast %d' %id
重定向redirect示例
from flask import redirect @app.route('/') def hello_itheima(): return redirect('http://www.itcast.cn')
返回JSON
from flask import Flask,json @app.route('/json') def do_json(): hello = {"name":"stranger", "say":"hello"} return json.dumps(hello)
返回狀態(tài)碼示例
在 Python 中返回狀態(tài)碼有兩種方式實(shí)現(xiàn):
- 直接return
- 可以自定義返回狀態(tài)碼,可以實(shí)現(xiàn)不符合http協(xié)議的狀態(tài)碼,例如:error=666,errmsg='查詢數(shù)據(jù)庫(kù)異常',其作用是為了實(shí)現(xiàn)前后端數(shù)據(jù)交互的方便
- abort方法
- 只會(huì)拋出符合http協(xié)議的異常狀態(tài)碼,用于手動(dòng)拋出異常
@app.route('/') def hello_itheima(): return 'hello itcast',666
正則路由示例
在web開發(fā)中,可能會(huì)出現(xiàn)限制用戶訪問規(guī)則的場(chǎng)景,那么這個(gè)時(shí)候就需要用到正則匹配,限制訪問,優(yōu)化訪問
導(dǎo)入轉(zhuǎn)換器包
from werkzeug.routing import BaseConverter
自定義轉(zhuǎn)換器并實(shí)現(xiàn)
# 自定義轉(zhuǎn)換器 class Regex_url(BaseConverter): def __init__(self,url_map,*args): super(Regex_url,self).__init__(url_map) self.regex = args[0] app = Flask(__name__) # 將自定義轉(zhuǎn)換器類添加到轉(zhuǎn)換器字典中 app.url_map.converters['re'] = Regex_url @app.route('/user/<re("[a-z]{3}"):id>') def hello_itheima(id): return 'hello %s' %id
自帶幾種轉(zhuǎn)換器
DEFAULT_CONVERTERS = { 'default': UnicodeConverter, 'string': UnicodeConverter, 'any': AnyConverter, 'path': PathConverter, 'int': IntegerConverter, 'float': FloatConverter, 'uuid': UUIDConverter, }
希望本文所述對(duì)大家基于flask框架的Python程序設(shè)計(jì)有所幫助。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。