import mysqlconnectorfrom flask import Flask render_template request redirect url_forapp = Flask__name__# Connect to MySQL databasemydb = mysqlconnectorconnect host=localhost user=root passwo
您可以通过以下步骤来实现登录成功后跳转至首页并隐藏登录和注册按钮,右上角显示用户名,用户可以修改:
- 在登录成功的处理函数
success()中,获取登录用户的用户名,并将其作为参数传递给首页的渲染模板。
@app.route('/success')
def success():
username = request.form['username']
return render_template('index.html', username=username)
- 在首页的渲染模板
index.html中,使用模板语言来判断是否显示登录和注册按钮。
{% if username %}
<div>欢迎回来,{{ username }}</div>
<a href="#">修改密码</a>
{% else %}
<a href="{{ url_for('login') }}">登录</a>
<a href="{{ url_for('register') }}">注册</a>
{% endif %}
- 创建一个新的路由
/modify_password,用于处理用户修改密码的请求。
@app.route('/modify_password', methods=['GET', 'POST'])
def modify_password():
if request.method == 'POST':
# 获取新密码并更新到数据库中
new_password = request.form['new_password']
# 更新数据库中的密码
mycursor.execute("UPDATE users SET password = %s WHERE username = %s", (new_password, username))
mydb.commit()
return 'Password updated successfully'
return render_template('modify_password.html')
- 在首页的渲染模板
index.html中,添加一个修改密码的链接。
<a href="{{ url_for('modify_password') }}">修改密码</a>
这样,登录成功后,用户可以看到右上角显示的用户名,并且可以点击链接来修改密码
原文地址: https://www.cveoy.top/t/topic/hWrW 著作权归作者所有。请勿转载和采集!