我想用python flask和MySQL做一个简单的登录页面。网页本身是用html、bootstrap 4和css制作的。我按照教程做了一个登录页面,但现在我想添加一个删除账户的方法。
这是一个登录后可见的个人资料页面(它显示了你的用户名,密码和电子邮件)。数据库表(称为accounts)有一个主键id。在/中的部分是我试图添加的代码,以创建一个删除按钮。请帮我解决我的删除账户按钮.
@app.route('/pythonlogin/profile', methods = ['GET'])
def profile():
# Check if user is loggedin
if 'loggedin' in session:
# We need all the account info for the user so we can display it on the profile page
cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cursor.execute('SELECT * FROM accounts WHERE id = %s', (session['id'],))
account = cursor.fetchone()
# Show the profile page with account info
return render_template('profile.html', account=account)
# User is not loggedin redirect to login page
///if request.method == 'GET':
id = session['id']
mycursor = mysql.cursor()
sql = ('DELETE from accounts WHERE id = 4;')
# return redirect(url_for('logout)')
mycursor.execute(sql)
mysql.connection.commit()///
return redirect(url_for('login'))
下面是html部分,名为file.html。
{% extends 'layout.html' %}
{% block title %}Profile{% endblock %}
{% block content %}
<h2>Profile Page</h2>
<div>
<p>Your account details are below:</p>
<table>
<tr>
<td>Username:</td>
<td>{{ account['username'] }}</td>
</tr>
<tr>
<td>Password:</td>
<td>{{ account['password'] }}</td>
</tr>
<tr>
<td>Email:</td>
<td>{{ account['email'] }}</td>
</tr>
<tr>
<form action="{{ url_for('logout') }}">
<td>
<button type="submit" class="btn btn-danger">Delete Account</button>
</td>
</form>
</tr>
</table>
</div>
{% endblock %}
在提供的代码中,我可以看到一些错误(逻辑)
return render_template('profile.html', account=account)
不会被执行<form action="{{ url_for('logout') }}">
而且最好用POST方式做表单。