Python Flask return redirect()调用不重定向用户
我有一个flask站点,使用flask的内置开发服务器(本地机器)在本地运行 在我提供页面之前,我正在运行一个自定义的安全评估函数,以确保用户有权访问该页面。如果用户无权访问该页面,我将尝试将用户重定向回主页。此工作流中的所有内容都按预期进行,但重定向除外 即使“重定向”调用仍在执行,用户仍被服务于页面,就好像他们完全有权一样。很可能我使用的重定向功能不正确--请告诉我 以下是烧瓶站点设置:Python Flask return redirect()调用不重定向用户,python,flask,Python,Flask,我有一个flask站点,使用flask的内置开发服务器(本地机器)在本地运行 在我提供页面之前,我正在运行一个自定义的安全评估函数,以确保用户有权访问该页面。如果用户无权访问该页面,我将尝试将用户重定向回主页。此工作流中的所有内容都按预期进行,但重定向除外 即使“重定向”调用仍在执行,用户仍被服务于页面,就好像他们完全有权一样。很可能我使用的重定向功能不正确--请告诉我 以下是烧瓶站点设置: from flask import Flask, render_template, request, u
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')
我有类似的程序,但我不是从安全检查助手方法重定向 我正在做的是: 我有一个方法可以检查安全性并根据凭据返回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,我把两者都放在那里。 < P>嗨,我认为你应该考虑使用->/P>这是个诀窍。我不能100%确定原因,但如果redirect()调用不是@app.route()函数的一部分,Flask似乎不尊重它。我不确定这是否是总结正在发生的事情的正确方法,但从观察者的角度来看,这正是正在发生的事情。我重新构造了调用,以便在test_page()函数中执行重定向(在调用安全模块之后)。这将有点麻烦,因为我将不得不在每个页面中写入相同的逻辑,而不是在授权失败时使用pythonic单一函数重定向,但嘿,它可以工作!谢谢!