2017-02-09 2 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의 장식 자

요구 사항은 cost_id 등 TYPE_ID, OBJECT_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 오류가 발생하고이 아니라 같은 URL에 전달 된 API 매개 변수를 검증하는 장식을 작성하는 것입니다 나는 아무것도 없어?

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