问题描述
我正在将Flask和Blueprint模块一起使用。在我的应用程序中,我尝试使用LDAP成功登录(page/home
)后将页面重定向到user/login
,但是重定向将永久进行,而不会引发任何错误。
我尝试了redirect(url_for('page.home'))
,redirect(url_for('page/home.html'))
的几个不同变体。但是,每个命令都不会重定向。我不确定自己在做什么错。请帮助。
文件夹结构:
user / views.py:
from flask import Flask,Blueprint,request,render_template,redirect,url_for,session
from ldap3 import Server,Connection,ALL,NTLM
from snakeeyes.blueprints.page.views import page
import config.settings as p
user = Blueprint('user',__name__,template_folder='templates')
user.secret_key = 'dev key'
# @user.route('/')
# @user.route('/login')
# def login():
# return render_template('user/login.html')
def connect_ldap(username,password):
if not username or not password:
return False
# try:
# from ldap3 import Server,NTLM
# except ImportError as importException:
# print("LDAP3 import not found,run 'sudo pip install ldap3 && sudo pip3 install ldap3'")
# print(importException)
# return False
# define the server
server = Server('us01ds',port=389,get_info=ALL)
# define the connection
user = 'uid=%s,ou=people,ou=users,dc=global,dc=COMPANY,dc=com' % username
conn = Connection(server,user,password,auto_bind=True)
# perform the Bind operation
if not conn.bind():
print('error in bind',conn.result)
return False
else:
return True
@user.route('/',methods=['GET','POST'])
@user.route('/login/','POST'])
def login():
# global username
# username = None
# If POST,redirect to dashboard
if request.method == 'POST':
username = request.form['username'].encode('utf8').decode("utf-8")
password = request.form['password'].encode('utf8').decode("utf-8")
# Try to login using ldap
test = connect_ldap(username,password)
# Invalid credentials
if not test:
return render_template(
'login.html',isinvalid='is-invalid',error='Username or Password is incorrect'
)
else:
# session['user_id'] = request.form['username']
print('redict to home page')
return redirect(url_for('page.home'))
# If GET,render the login page
else:
return render_template('user/login.html')
page / views.py:
from flask import Blueprint,render_template
page = Blueprint('page',template_folder='templates')
@page.route('/home')
def home():
return render_template('page/home.html')
@page.route('/terms')
def terms():
return render_template('page/terms.html')
@page.route('/privacy')
def privacy():
return render_template('page/privacy.html')
解决方法
我找到了解决此问题的方法。
为了更好地促进使用HTTPS URL的URL的生成
方案,此补丁添加了一个考虑到此特定目的的参数。至
为此,我们显式传递参数_scheme='https'
,然后设置
我们的url_scheme
实例的MapAdapter
属性。
重要的是,必须设置_external=True
才能使其正常工作。
因此,如果不这样做,则会引发ValueError
。
所以,我只替换return redirect(url_for('page.home'))
=> return redirect(url_for('page.home',_external=True,_scheme='https'))
参考:https://github.com/pallets/flask/commit/b5069d07a24a3c3a54fb056aa6f4076a0e7088c7