Python的Flask路由實(shí)現(xiàn)實(shí)例代碼
路由簡(jiǎn)介
- 路由定義
處理url和函數(shù)之間綁定關(guān)系的程序
- 路由作用
路由控制訪問(wèn)的路徑 ,路徑能訪問(wèn)到什么是由后端來(lái)控制的
路由實(shí)現(xiàn)
裝飾器添加路由表實(shí)現(xiàn)路由
- 采用裝飾器添加路由功能在程序運(yùn)行時(shí),自動(dòng)添加路由表
- Flask即采用這種模式
函數(shù)裝飾器方式添加路由映射表
# 路由映射表
path_map = {}
def route(url, **kwargs):
def decorator(f):
path_map[url] = f
return f
return decorator
@route('/')
def hello():
return 'hello'
@route('/index')
def index():
return 'index'
print(path_map)
>{'/': <function hello at 0x7fa103cfee50>, '/index': <function index at 0x7fa103cfedc0>}類(lèi)裝飾器方式添加路由映射表
# 路由裝飾器
class WsgiApp(object):
def __init__(self):
# 定義路由表
self.routes = {}
def route(self, path=None):
def decorator(func):
self.routes[path] = func
return func
return decorator
def __call__(self, environ, start_response):
path = environ.get('PATH_INFO')
if path is None or path not in self.routes.keys():
status = "400 Not Found"
header = [('Content-Type', 'text/plain; charset=utf-8')]
start_response(status, header)
return [b'Page Not Found']
else:
status = "200 OK"
header = [('Content-Type', 'text/plain; charset=utf-8')]
start_response(status, header)
resp = self.routes.get(path)
if resp is None:
status = "400 Not Found"
header = [('Content-Type', 'text/plain; charset=utf-8')]
start_response(status, header)
return [b'Page Not Found']
else:
return [resp().encode()]
app = WsgiApp()
# 視圖函數(shù)
@app.route('/')
def hello():
return 'hello'
@app.route('/login')
def login():
return 'login'
@app.route('/change')
def change():
return 'update pwd'
if __name__ == '__main__':
# 啟動(dòng)服務(wù)
from wsgiref.simple_server import make_server
server = make_server('127.0.0.1', 8888, app)
server.serve_forever()集中管理路由表實(shí)現(xiàn)路由
手動(dòng)添加路由映射表來(lái) 集中管理 路由。
- Django等大型項(xiàng)目一般采用這種方式。
- 使用時(shí)自己去添加路由映射表和對(duì)應(yīng)的視圖函數(shù)
from wsgiref.simple_server import make_server
def hello():
return 'hello'
def login():
return 'login'
def change():
return 'update pwd'
# 路由表
path_dict = {'/': hello,
'/login': login,
'/change': change
}
def app(environ, start_response):
path = environ.get('PATH_INFO')
if path is None or path not in path_dict.keys():
status = "400 Not Found"
header = [('Content-Type', 'text/plain; charset=utf-8')]
start_response(status, header)
return [b'Page Not Found']
else:
status = "200 OK"
header = [('Content-Type', 'text/plain; charset=utf-8')]
start_response(status, header)
resp = path_dict.get(path)
if resp is None:
status = "400 Not Found"
header = [('Content-Type', 'text/plain; charset=utf-8')]
start_response(status, header)
return [b'Page Not Found']
else:
return [resp().encode()]
if __name__ == '__main__':
server = make_server('127.0.0.1', 8888, app)
server.serve_forever()flask路由實(shí)現(xiàn)
在啟動(dòng)程序時(shí),python解釋器會(huì)從上到下對(duì)代碼進(jìn)行解釋?zhuān)?dāng)遇到裝飾器時(shí),會(huì)執(zhí)行,并把函數(shù)對(duì)應(yīng)的路由以字典的形式進(jìn)行存儲(chǔ),當(dāng)請(qǐng)求到來(lái)時(shí),即可根據(jù)路由查找對(duì)應(yīng)要執(zhí)行的函數(shù)方法
url_map = {
# '/index': index
}
def route(option):
def inner(func,*args, **kwargs):
# return func(*args, **kwargs)
url_map[option['path']] = func
return inner
@route({'path': '/index'})
def index(request):
pass- 這里的url_map作為存儲(chǔ)維護(hù)路由函數(shù)對(duì)應(yīng)關(guān)系的映射空間
- 當(dāng)python解釋器從上到下解釋到@route這一行時(shí),會(huì)自動(dòng)執(zhí)行route({‘path’: ‘/index’}),將inner作為返回值,此時(shí)@route({‘path’: ‘/index’})等同于@inner并裝飾index函數(shù)
- 繼續(xù)執(zhí)行index=inner(index),url_map即存儲(chǔ)’/index’路由對(duì)應(yīng)的index函數(shù)
到此這篇關(guān)于Python的Flask路由實(shí)現(xiàn)實(shí)例代碼的文章就介紹到這了,更多相關(guān)Flask路由實(shí)現(xiàn)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python實(shí)現(xiàn)自動(dòng)化批量調(diào)整Word樣式
在日常工作中,處理大量的Word文檔是一個(gè)常見(jiàn)的任務(wù),尤其是需要批量修改文檔的樣式時(shí),本文為大家介紹了如何使用Python實(shí)現(xiàn)自動(dòng)化批量調(diào)整Word樣式,需要的可以參考下2024-12-12
一文詳解PyQt5中實(shí)現(xiàn)不規(guī)則窗口的顯示
這篇文章主要為大家詳細(xì)介紹了Python?PyQt5中實(shí)現(xiàn)不規(guī)則窗口的顯示的相關(guān)資料,文中的示例代碼講解詳細(xì),具有一定的借鑒價(jià)值,需要的可以參考一下2022-12-12
pandas之分組統(tǒng)計(jì)列聯(lián)表pd.crosstab()問(wèn)題
這篇文章主要介紹了pandas之分組統(tǒng)計(jì)列聯(lián)表pd.crosstab()問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-09-09
Python IDE PyCharm的基本快捷鍵和配置簡(jiǎn)介
這篇文章主要介紹了Python IDE PyCharm的基本快捷鍵和配置簡(jiǎn)介,PyCharm為一個(gè)收費(fèi)的軟件,需要的朋友可以參考下2015-11-11
在python中利用最小二乘擬合二次拋物線函數(shù)的方法
今天小編就為大家分享一篇在python中利用最小二乘擬合二次拋物線函數(shù)的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-12-12
python判斷文件是否存在,不存在就創(chuàng)建一個(gè)的實(shí)例
今天小編就為大家分享一篇python判斷文件是否存在,不存在就創(chuàng)建一個(gè)的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-02-02
Python開(kāi)啟線程,在函數(shù)中開(kāi)線程的實(shí)例
今天小編就為大家分享一篇Python開(kāi)啟線程,在函數(shù)中開(kāi)線程的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-02-02

