溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Python怎么用裝飾器實(shí)現(xiàn)類似于flask路由

發(fā)布時(shí)間:2023-02-28 11:58:26 來源:億速云 閱讀:129 作者:iii 欄目:開發(fā)技術(shù)

這篇文章主要介紹“Python怎么用裝飾器實(shí)現(xiàn)類似于flask路由”,在日常操作中,相信很多人在Python怎么用裝飾器實(shí)現(xiàn)類似于flask路由問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”Python怎么用裝飾器實(shí)現(xiàn)類似于flask路由”的疑惑有所幫助!接下來,請跟著小編一起來學(xué)習(xí)吧!

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 指的是一個(gè)函數(shù)
    def add_url_to_map(self,url,f):
        self.url_map[url] = f
 
    def run(self):
        while True:
            url = input("請輸入U(xiǎn)RL: ")
            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

Python怎么用裝飾器實(shí)現(xiàn)類似于flask路由

分析實(shí)現(xiàn)邏輯:

當(dāng)運(yùn)行app.run() 時(shí),代碼運(yùn)行邏輯是

1、先執(zhí)行1 實(shí)例化Grass對象

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

3、裝飾器@app.router("/index") 運(yùn)行

4、最后才是app.run() 運(yùn)行

Python怎么用裝飾器實(shí)現(xiàn)類似于flask路由

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

Python怎么用裝飾器實(shí)現(xiàn)類似于flask路由

裝飾器@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ù)

到此,關(guān)于“Python怎么用裝飾器實(shí)現(xiàn)類似于flask路由”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識,請繼續(xù)關(guān)注億速云網(wǎng)站,小編會繼續(xù)努力為大家?guī)砀鄬?shí)用的文章!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI