flask框架:使用自带的加密方法对密码加密

使用的包

Werkzeug

加密代码:

from werkzeug.security import generate_password_hash,check_password_hash

def set_password(password):
    '''
    :param password: 带加密的密码,如123456
    :return: 加密的密码:pbkdf2:sha256:150000$0koyI6Eb$cff6e1b193381f5891fc1cf7b87b1b4dab33869aa5490a7f935579e47c7666cf
    '''
    password = generate_password_hash(password)
    return password
def check_password(password,pwhash):
    '''
    :param password: 字符串密码,如123456
    :param pwhash: 加密后的密码,存在用户表中的hash值
    :return: Ture or False
    '''
    return check_password_hash(password=password,pwhash=pwhash)

视图使用:注册用户

from flask.views import MethodView
from flask import jsonify
from flask import request,g
from ext import db


#模型类
from . import models
#公共资源
from util.public import set_password,check_password
class RegisterView(MethodView):
    def post(self):
        name = request.form.get('name')
        account = request.form.get('account')
        password = request.form.get('password')
        gender = request.form.get('gender')
        age = request.form.get('age')
        if not name:
            return jsonify({'code':400,'msg':'没有携带姓名'})
        if not account:
            return jsonify({'code':400,'msg':'没有携带账户'})
        if not password:
            return jsonify({'code':400,'msg':'没有携带密码'})
        if not gender:
            return jsonify({'code':400,'msg':'没有携带性别'})
        if not age:
            return jsonify({'code':400,'msg':'没有携带年龄'})
        password = set_password(password)
        obj = models.UserModel.query.filter_by(account=account).first()
        if obj:
            return jsonify({'code':400,'msg':'该账户已经在数据库中存在了'})
        else:
            obj = models.UserModel()
            obj.name=name
            obj.account=account
            obj.gender=gender
            obj.age=age
            obj.password=password
            db.session.add(obj)
            db.session.commit()
            return jsonify({'code':200,'msg':f'创建用户:{name} 成功'})

视图使用:登录

from flask.views import MethodView
from flask import jsonify
from flask import request,g
from ext import db


#模型类
from . import models
#公共资源
from util.public import set_password,check_password

class LoginView(MethodView):
    def post(self):
        print('登录成功')
        account = request.form.get('account')
        password = request.form.get('password')
        obj = models.UserModel.query.filter_by(account=account).first()
        if check_password(password=password,pwhash=obj.password):
            token = jwt_encode_token(obj.id)
            response = jsonify({'code':200,'msg':'登录成功','token':token})
            response.set_cookie('token',token)
            return response
        else:
            return jsonify({'code':400,'msg':'用户名或密码错误'})

 

你可能感兴趣的:(flask,python,后端)