password.strip()怎么使用,具体代码
时间: 2024-02-06 10:12:33 浏览: 17
`strip()` 方法可以去掉字符串开头和结尾的空格、制表符、换行符等空白字符。在上面的代码中,可以将 `user['password'][0:-1]` 替换为 `password.strip()`。具体代码如下:
```
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form['username']
password = request.form['password'].strip() # 去掉密码字符串末尾的空白字符
# 查询用户是否存在
cur = mysql.connection.cursor()
cur.execute("SELECT * FROM users WHERE username = %s", (username,))
user = cur.fetchone()
cur.close()
if user:
columns = [column[0] for column in cur.description]
user = dict(zip(columns, user))
if user['password'] == password: # 比较密码时不需要去掉换行符
session['username'] = username
logging.info('Login success, redirect to home page.')
return redirect(url_for('home'))
else:
return render_template('login.html', error='Incorrect Password')
else:
return render_template('login.html', error='User Not Found')
else:
return render_template('login.html')
```
在这个代码中,使用了 `password.strip()` 方法来去掉密码字符串末尾的空白字符,并且在比较密码时不需要再去掉换行符。