Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
552 views
in Technique[技术] by (71.8m points)

python - flask before request - add exception for specific route

In the before_request() function (below), I want to redirect the user to /login if they are not yet logged in. Is there a special variable that will give me the current URL that will work as the below example does?

@app.before_request
def before_request():
    # the variable current_url does not exist
    # but i want something that works like it
    if (not 'logged_in' in session) and (current_url != '/login'):
        return redirect(url_for('login'))

I need to check that the current URL is /login, because if I don't the server goes into an infinite loop.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are a couple of properties on the request object you can check, documented here, request.path is probably what you want. Can I suggest request.endpoint though, so you'll be covered should you decide to route your view to another url, or multiple urls

@app.before_request
def before_request():
    if 'logged_in' not in session and request.endpoint != 'login':
        return redirect(url_for('login'))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...