2017-09-09 2 views
0

は現在、私はこのコードに私のフラスコアプリでPython:これをより汎用的にする方法 - おそらくデコレータを使用しますか?

@app.route("/protect1") 
def protect1(): 
    if not session.get('logged_in'): 
     session['next'] = "/protect1" 
     return render_template('login.html') 
    else: 
     return "This is the first protected page protect1" 

@app.route("/protect2") 
def protect2(): 
    if not session.get('logged_in'): 
     session['next'] = "/protect2" 
     return render_template('login.html') 
    else: 
     return "This is the second protected page protect2" 

、すべての作業罰金を持っています。 if/elseの組み合わせごとに各機能(表示)を繰り返す必要があるだけでいいわけではありません。

私はこのpseude・コードのように、いくつかの一般的な方法を持っていることを好むだろう。ここ

@checklogin 
@app.route("/protect1") 
def protect1(): 
    return "This is the first protected page protect1" 

@checklogin 
@app.route("/protect2") 
def protect2(): 
    return "This is the second protected page protect2" 

1つの課題は、@checkloginデコレータはapp.routeパス(例:「/ protect1を」知る必要があるだろうということです)セッション['次の]を正しく設定できるようにする必要があります。このパラメータをデコレータに渡す方法、特に最初にそれを見つける方法はわかりません。つまり、protect1()関数は@ app.routeで装飾されており、そのapp.routeデコレータにどのパラメータ( "/ protect1")が渡されているかを知っていますか?

+0

これまでに試したことをお見せできますか? –

+0

[ビューのデコレータ](http://flask.pocoo.org/docs/0.11/patterns/viewdecorators/) – myaut

+0

私はこれまで見てきましたが、何も書かれていません。 protect1())はデコレータ(app.route()に渡されたパラメータの値を知ることができます。つまり、値が "/ protect1"であることがわかります)... – Happysmithers

答えて

2

デコレータはパスをrequestにルックアップできます。ロードされたURL(request.urlとして入手可能)またはrequest.endpoint attributeを使用して、次のいずれか

from functools import wraps 
from flask import request, session 

def checklogin(f): 
    @wraps(f) 
    def wrapper(*args, **kwargs): 
     if not session.get('logged_in'): 
      session['next'] = request.url 
      return render_template('login.html') 
     return f(*args, **kwargs) 
    return wrapper 

はデコレータにapp.route()デコレータを場所を行いますか、それはルートのハンドラとして登録されていないでしょう。

@app.route("/protect1") 
@checklogin 
def protect1(): 
    return "This is the first protected page protect1" 
関連する問題