2014-03-13 3 views
0

플라스크 앱이 있습니다. 때때로, (단지 점을 입증하기 위해, 테스트되지 않은 코드) 매우 관련있다 그래서 같은 경로의 일련 건너하는 것이 일반적 일 수 있습니다 지금플라스크에서 이벤트를 처리하여 특정 상황으로 전달하기 전에

@app.route('/stats/charts/count/<attribute>', methods=['GET']) 
def count_attribute(attribute): 
    counter = collections.Counter() 
    for x in csv_mod.data: 
    counter[attribute] += 1 
    return counter 

@app.route('/stats/charts/filter/<attribute>/<value>', methods=['GET']) 
def filter_attribute(attribute, value): 
    filtered = [] 
    for entry in csv_mod.data: 
    if getattr(entry, attribute) != value: 
     filtered.append(entry) 
    return filtered 

을의이 방법도 말할 수 있도록하는 그들이 할 수있는 데이터를 분할하는 쿼리 매개 변수를 입력하십시오. 예를 들면, 그들은 요청 또는 무엇인가 03에 넣습니다. /stats/charts 응용 프로그램 경로 중 하나를 방문하기 전에 그들이 방문하는 경우, 내가 명시 적으로 지금 /stats/charts/

@app.route('/stats/charts/*', methods=['GET']) # any route with this base 
def cut_data(): 
    month = request.args.get('month', None) 
    if month is None: 
    #propagate to the specific approute 
    else: 
    # cut data and then go to the specific approute 

에서 모든 방법에서이 방법을 실행하는 진술없이 approute을하기 전에이 데이터를 잘라 "게이트 키퍼"방법을 싶습니다 요청시 :site:/stats/charts/count/crows/03으로 변경하면 "실제"승인 절차로 진행하기 전에 데이터를 올바르게자를 수 있습니다. 일련의 메소드에서 일반적인 메소드를 추가 할 수있는 방법이 있습니까? 가장 좋은 방법은 무엇일까요?

답변

2

데코레이터로 만들 수 있습니다. 뷰는 기능이며, 데코레이터는 함수에 추가 인수를 추가 할 수 있습니다

@app.route('/stats/charts/count/<attribute>', methods=['GET']) 
@cut_data 
def count_attribute(attribute, data=None): 
    counter = collections.Counter() 
    for x in data: 
     counter[attribute] += 1 
    return counter 

@app.route('/stats/charts/filter/<attribute>/<value>', methods=['GET']) 
@cut_data 
def filter_attribute(attribute, value, data=None): 
    filtered = [] 
    for entry in data: 
     if getattr(entry, attribute) != value: 
      filtered.append(entry) 
    return filtered 

와 래퍼가 술병에 의해 호출되며 실제보기를 호출 할 수 있습니다

from functools import wraps 

def cut_data(func): 
    @wraps(func) 
    def wrapper(*args, **kw): 
     month = request.args.get('month', None) 
     if month is None: 
      # redirect to same endpoint with new query parameter 
      return redirect(request.endpoint, month='some month', **request.view_args) 

     # cut data 
     data = some_magic(csv_mod.data, month) 
     # call actual view function 
     return func(data=data, *args, **kw) 

    return wrapper 

다음 경로로 사용 기능은 추가 키워드 매개 변수 data과 함께 해당 월의 데이터가 미리 잘라져 있습니다.

관련 문제