Home >Backend Development >Python Tutorial >Introduction to the method of quoting hashed passwords in Flask (with code)
This article brings you an introduction to the method of quoting hashed passwords in Flask (with code), which has certain reference. Value, friends in need can refer to it, I hope it will be helpful to you.
Password Hash:
A messy string formed by one-time encryption of the password. This encryption process is considered irreversible, that is to say, it is believed that it is impossible to restore the original password from the hash string. (This sentence is a more official explanation).
To put it in plain English: When we register an account and password, we need to use Password Hash to encrypt the password we registered. Then when we log in, a decryption process will be performed to match the password we entered.
Use in Flask:
1. Guide package
# 导包 from werkzeug.security import generate_password_hash,check_password_hash
Among them: generate_password_hash is to generate the password; check_password_hash is the password verification
2. When registering an account, use generate_password_hash
<span style="font-size: 15px;">@admin_blue.route('add_user') defadd_user():<br/># Adminuser是数据库中一张表的名字 , user:注册的账号 pass_hash: 注册的密码,此时注册的密码的是 123 add_user=Adminuser(user='admin',<span style="color: #ff0000;"><strong>pass_hash=generate_password_hash('123')</strong></span>) db.session.add(add_user) return'OK'</span>
The password we registered at this time is "123". When we use generate_password_hash to encrypt "123", the database will become:
3. Now that we have completed the registration, it is our turn to log in. When we log in, when entering the password, we need to use check_password_hash to decrypt and then verify. Password
# 登录 @admin_blue.route('/login',methods=['get','post']) def login(): if request.method=='POST': username=request.form.get('username') password=request.form.get('password') if not all([username,password]): flash('请输入账号和密码') else: sqluser=Adminuser.query.filter(Adminuser.user==username).first() if not sqluser: flash('账号不正确') else: a=check_password_hash(sqluser.pass_hash,password) print(a) if a: session['admin_username']=username return redirect(url_for('admin.index')) else: flash('密码不正确') return render_template('admin/login.html')
In short, the key point is: generate_password_hash is to generate the password; check_password_hash is the password verification, and the other codes are the simplest registration and login in Flask.
The above is the detailed content of Introduction to the method of quoting hashed passwords in Flask (with code). For more information, please follow other related articles on the PHP Chinese website!