我对我的 Python-Flask 应用程序中的重定向有疑问:http: //jordanirvine.pythonanywhere.com/ 作为一名新开发人员,我一直在使用这个应用程序取得稳步进展,但最近我在某些方面遇到了麻烦。如果您使用“用户名”和“密码”作为用户名和密码登录应用程序,然后单击“添加成员”按钮,您会看到一切正常,并且您可以轻松添加成员,但是,如果您在“添加成员”网页上并决定返回顶部的“搜索成员”或“主页”页面而不按提交,则会将您退出当前会话。有人可以帮我理解为什么会这样这样做吗?我希望用户在这些转换期间保持登录状态,因为这可能会经常发生。
这是主页链接:
@app.route('/home/<defSess>')
@app.route('/home/', defaults={'defSess': None})
def home(defSess):
if defSess is None:
session.clear()
return render_template('home.html')
else:
defSess = defSess
with sql.connect(databases) as connection:
connection.execute("CREATE TABLE IF NOT EXISTS dataBaseNames(name varchar(30) DEFAULT NULL)")
return render_template('home.html', defSess=defSess)
这是会员搜索链接:
#memberSearch (Dashboard)
@app.route('/memberSearch/', defaults={'defSess': None})
@app.route('/memberSearch/<defSess>')
@is_logged_in
def memberSearch(defSess):
if defSess is None:
session.clear()
flash('Unauthorized, Please login', 'danger')
return render_template('login.html')
else:
defSess = defSess
createTables(defSess)
with sql.connect(defSess) as connection:
connection.row_factory = sql.Row
cur = connection.execute("SELECT * from members m join visits v
where v.breakfastDate = (select max(visits.breakfastDate) from visits
where visits.clientId = m.clientId) UNION select * from members m left
join visits v on m.clientId = v.clientId where breakfastDate is NULL")
members = build_dict_list(cur)
if members:
return render_template('memberSearch.html', members=members, defSess=defSess)
else:
msg = 'No members Found'
return render_template('memberSearch.html', msg=msg, defSess=defSess)
这是 add_member 代码:
# Add member
@app.route('/add_member/<defSess>', methods=['GET', 'POST'])
def add_member(defSess):
form = MemberForm(request.form)
if request.method == 'POST' and form.validate():
with sql.connect(defSess) as connection:
name = form.name.data
author = defSess
connection.execute("INSERT INTO members(name, author)
VALUES(?,?)",[name,author],)
flash('Member Created', 'success')
return redirect(url_for('memberSearch', defSess=defSess))
return render_template('add_member.html', form=form)
其他一些功能和代码:
注销代码:
@app.route('/logout/')
@is_logged_in
def logout():
session.clear
flash('You are now logged out', 'success')
session['logged_in'] = False
return redirect(url_for('login'))
检查用户是否登录:
def is_logged_in(f):
@wraps(f)
def wrap(*args, **kwargs):
if 'logged_in' in session:
return f(*args, **kwargs)
else:
flash('Unauthorized, Please login', 'danger')
return redirect(url_for('login'))
return wrap
如果您需要更多代码,包括 HTML 代码,请告诉我,否则我们将不胜感激!另外,我意识到可能有一种更有效的方法来编写这个应用程序,但我缺乏经验,这是我第一次尝试应用程序。无论如何,提前谢谢!