Flask return redirect()调用不重定向我们

2024-04-25 07:42:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个flask站点,我使用flask的内置开发服务器(本地机器)在本地运行。你知道吗

在提供页面之前,我正在运行一个自定义的安全评估函数,以确保用户有权访问该页面。如果用户无权访问该页面,我将尝试将用户重定向回主页。此工作流中的所有操作都按预期进行,但重定向除外。你知道吗

即使“重定向”调用仍在执行,用户仍被服务于页面,就好像他们完全有权一样。很可能我使用了错误的重定向函数--请告诉我。你知道吗

以下是烧瓶站点设置:

from flask import Flask, render_template, request, url_for, redirect, Markup, session, abort

def security(page_name):
    # Direct not logged in users to the login form
    if not session.get('logged_in'):
        return render_template('login.html')
    else:
        try:
            # Update user's permissions
            permissions_list = login_helpers.get_user_permissions_by_id(user_id)
            session['permissions'] = permissions_list

            if requested_page_abbreviation not in session['permissions']:
                # User does not have access -- bounce user back to home

                # I see this appear in the console
                print('Not authorized')

                # This must get executed, but the user does not get directed back home -- instead the resulting page loads as if the user has permissions
                return redirect('/home')

                # This does not execute
                # If I replace this line above the "return redirect('/home')" call, the expected "Unauthorized" page results and the 401 HTTP code is returned
                abort(401)


        except KeyError:

            # User has not yet had permissions set -- bounce user back to home to login
            return redirect(url_for('home'))

@app.route('/', methods=['GET','POST'])
def home():
    return render_template('home.html')

@app.route('/test_page', methods=['POST'])
def test_page():

    security_check('TEST')

    return render_template('test_page.html')

Tags: the用户inpermissionshomereturnsessionpage
2条回答

我有类似的程序,但我不是从安全检查助手方法重定向。你知道吗

我要做的是: 我有一个方法可以检查安全性并根据凭据返回true/false。得到安全检查结果后,我从路由定义方法重定向。没有来自助手方法的重定向。你知道吗

我的代码示例如下,它对我有效:

@app.route("/", methods=['GET', 'POST'])
def mymethod():
    secure = sec()
    if(secure):
        return "Secure page"
    else:
        return redirect('/login')

@app.route("/login", methods=['GET', 'POST'])
def login():
    return "login page"

# Do not redirect from your helper method
def sec():
    secured = False
    # Your security logic and code
    if secured:
        return True
    else:
        return False

你可以注意到我的安全检查只是检查有效性,并告诉我怎么做。您可以根据您的路线要求从路线中删除GET或POST,我只是将两者都放在那里。你知道吗

嗨,我想你应该考虑使用->;request hooks

相关问题 更多 >

    热门问题