Python利用裝飾器實(shí)現(xiàn)類似于flask路由
1.例子1
def f1():
print(1111)
def f2():
print(2222)
if __name__ == '__main__':
print(33)
打印結(jié)果:
33
在例子1中,f1() 與f2() 都沒有被調(diào)用,只執(zhí)行了print(33)
f1與f2,是沒有被調(diào)用的,但是如果f1 和 f2 上面有注解,就會被調(diào)用執(zhí)行。
2.python 利用裝飾器實(shí)現(xiàn)類似于flask路由
注釋類 Grass
# -*- coding:utf-8 -*-
# @Author: 喵醬
# @time: 2023 - 02 -21
# @File: grass.py
from types import FunctionType
class Grass(object):
# 字典,key 是 用戶輸入的路由
# value,是調(diào)用對應(yīng)的函數(shù)
url_map = {}
def router(self,url):
def decorator(f: FunctionType):
self.add_url_to_map(url,f)
# return f
return decorator
# f 指的是一個函數(shù)
def add_url_to_map(self,url,f):
self.url_map[url] = f
def run(self):
while True:
url = input("請輸入URL: ")
try:
print(self.url_map[url]())
except Exception as e:
print(404)
print(e)
運(yùn)行入口
# -*- coding:utf-8 -*-
# @Author: 喵醬
# @time: 2023 - 02 -21
# @File: blog.py
from grass import Grass
app = Grass()
@app.router("/home")
def home():
print("歡迎來到首頁")
return "首頁"
@app.router("/index")
def index():
print("歡迎來到列表頁")
return "列表頁"
if __name__ == '__main__':
app.run()
運(yùn)行app.run()
然后輸入 :
/home
/index
/mine

分析實(shí)現(xiàn)邏輯:
當(dāng)運(yùn)行app.run() 時,代碼運(yùn)行邏輯是
1、先執(zhí)行1 實(shí)例化Grass對象
2、裝飾器@app.router("/home") 運(yùn)行
3、裝飾器@app.router("/index") 運(yùn)行
4、最后才是app.run() 運(yùn)行

裝飾器@app.router("/home") 運(yùn)行邏輯

裝飾器@app.router("/home"),運(yùn)行
@app.router("/home") 對應(yīng) def router(self,url):
1、“/home” 傳給 def router(self,url),url =“/home”
2、@app.router("/home"),運(yùn)行得到 decorator函數(shù)
3、然后將home函數(shù)作為參數(shù),傳遞給decorator函數(shù)
4、self.add_url_to_map(url,f)
將 url(“/home”) 與 home 函數(shù)組成 字典。
在字典中,字符串 /home 對應(yīng)home 函數(shù)
以上就是Python利用裝飾器實(shí)現(xiàn)類似于flask路由的詳細(xì)內(nèi)容,更多關(guān)于Python裝飾器實(shí)現(xiàn)flask路由的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
使用python+whoosh實(shí)現(xiàn)全文檢索
今天小編就為大家分享一篇使用python+whoosh實(shí)現(xiàn)全文檢索,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-12-12
Python自動化測試pytest中fixtureAPI簡單說明
這篇文章主要為大家介紹了Python自動化測試pytest中fixtureAPI的簡單說明,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步2021-10-10
python使用socket 先讀取長度,在讀取報文內(nèi)容示例
這篇文章主要介紹了python使用socket 先讀取長度,在讀取報文內(nèi)容,涉及Python socket通信報文操作相關(guān)使用技巧,需要的朋友可以參考下2019-09-09
pytorch人工智能之torch.gather算子用法示例
這篇文章主要介紹了pytorch人工智能之torch.gather算子用法示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-09-09
Python cookbook(數(shù)據(jù)結(jié)構(gòu)與算法)同時對數(shù)據(jù)做轉(zhuǎn)換和換算處理操作示例
這篇文章主要介紹了Python cookbook(數(shù)據(jù)結(jié)構(gòu)與算法)同時對數(shù)據(jù)做轉(zhuǎn)換和換算處理操作,涉及Python使用生成器表達(dá)式進(jìn)行數(shù)據(jù)處理的相關(guān)操作技巧,需要的朋友可以參考下2018-03-03

