2017-02-09 87 views
0
#========================================== 
# Current API 
#========================================== 

@blueprint.route('/list/<int:type_id>/', methods=["GET"]) 
@blueprint.route('/list/<int:type_id>/<int:object_id>', methods=["GET"]) 
@blueprint.route('/list/<int:type_id>/<int:object_id>/<int:cost_id>', methods=["GET"]) 
@login_required 
def get_list(type_id, object_id=None, cost_id=None): 
    # Do something 
    pass 

我們在我們的Flask項目中使用藍圖進行API分組。這裏裝飾者在Python-Flask

現在的要求是寫這驗證在URL中傳遞的API參數,如TYPE_ID,OBJECT_ID,cost_id等

#========================================== 
# New Requested feature in API 
#========================================== 
from functools import wraps 

def request_validator(): 
""" 
This function will validates requests and it's parameters if necessary 
""" 

    def wrap(f): 
     @wraps(f) 
     def wrapped(self, *args, **kwargs): 

      # TODO -- Here I want to validate before actual handler 
      # 1) type_id, 
      # 2) object_id, 
      # 3) cost_id 
      # And allow handler to process only if validation passes Here 

      if type_id not in [ 1,2,3,4,5 ]: 
       return internal_server_error(errormsg="Invalid Type ID") 

     return f(self, *args, **kwargs) 
    return wrapped 
return wrap 


@blueprint.route('/list/<int:type_id>/', methods=["GET"]) 
@blueprint.route('/list/<int:type_id>/<int:object_id>', methods=["GET"]) 
@blueprint.route('/list/<int:type_id>/<int:object_id>/<int:cost_id>', methods=["GET"]) 
@login_required 
@request_validator 
def get_list(type_id, object_id=None, cost_id=None): 
    # Do something 
    pass 

但我正在逐漸beow錯誤,無法運行應用程序,是一個裝飾我錯過了什麼?

TypeError: request_validator() takes 0 positional arguments but 1 was given 

回答

1

您的request_validator裝飾者應該接受函數作爲參數。當你寫:

@request_validator 
def get_list(): 
    pass 

它的含義一樣:

def get_list(): 
    pass 
get_list = request_validator(get_list) 

所以你的裝飾應該是這樣的(有點不是在你的榜樣簡單):

def request_validator(f): 
    @wraps(f) 
    def wrapped(*args, **kwargs): 
     if type_id not in [ 1,2,3,4,5 ]: 
      return internal_server_error(errormsg="Invalid Type ID") 
     return f(*args, **kwargs) 
    return wrapped