簡體   English   中英

Python - 在 Decorator 之后調用預定義的 Function

[英]Python - Call Pre-defined Function after Decorator

我正在構建一個直接的 Flask API。在 API 端點的每個裝飾器之后,我必須定義一個 function,它只是調用另一個 function 我在一個單獨的文件中。 這工作正常,但似乎是多余的。 我寧願直接調用預定義的 function,而不必在裝飾器之后將其包裝在另一個 function 中。 這可能嗎?

我目前擁有的:

import routes.Locations as Locations

# POST: /api/v1/locations
@app.route('/locations', methods=['GET'])
def LocationsRead ():
   return Locations.read()

Locations.read() function 看起來像這樣:

def read():
   return {
      'id': 1,
      'name': 'READ'
   }

我希望做什么:

import routes.Locations as Locations

# POST: /api/v1/locations
@app.route('/locations', methods=['GET'])
Locations.read()

裝飾器的@語法只是語法糖:

def LocationsRead():
   return Locations.read()

LocationsRead = app.route('/locations', methods=['GET'])(LocationsRead)

所以你可以這樣做:

LocationsRead = app.route('/locations', methods=['GET'])(Locations.read)

可以說,理解意圖需要更長的時間,而且它並不比您的原始代碼簡潔得多。

除了異常和記錄堆棧跟蹤之外,您還會丟失一級堆棧跟蹤。 這將很難確定在 flask 中將Locations.read添加為路由的位置和方式。堆棧跟蹤將從 flask 庫直接跳轉到routes.Locations:read 如果你想知道路由是如何配置的(例如 URL 是用什么參數化的或者它使用什么方法),那么你必須已經知道“裝飾”發生在哪個文件中。 如果你使用普通裝飾,你會得到一行指向包含@app.route('/locations', methods=['GET'])的文件。

也就是說,您獲得了值得商榷的好處,並有可能使調試變得更加困難。 堅持使用@裝飾器語法。

多虧了@Dunes 和@RodrigoRodrigues 的回答,我對它進行了更多研究,發現以下內容適用於有和沒有 arguments 傳遞的端點,例如 ID。 請參閱下面的代碼。

# GET: /api/v1/locations
app.route(basepath + '/locations', methods=['GET'])(Locations.read)
# GET: /api/v1/locations/{id}
app.route(basepath + '/locations/<int:id>', methods=['GET'])(Locations.read)
# POST: /api/v1/locations
app.route(basepath + '/locations', methods=['POST'])(Locations.create)
# PUT: /api/v1/locations/{id}
app.route(basepath + '/locations/<int:id>', methods=['PUT'])(Locations.update)
# DELETE: /api/v1/locations/{id}
app.route(basepath + '/locations/<int:id>', methods=['DELETE'])(Locations.delete)

現在,我懷疑這是標准做法,但如果有人希望減少路由聲明中的代碼量,這是一種方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM