flask搭建平台实战教程二:快速实现用户注册和登录

这一篇主要实现用户注册和登录

编写接口并设置URL

根目录添加api文件夹,添加auth.py注册auth蓝图为根路径

from flask import Blueprint, jsonify

authbp = Blueprint('auth',__name__,url_prefix="")

@authbp.route("/register",methods=['POST'])
def register():
    return jsonify({
            "code": 0,
            "msg": "注册成功"
        })

在app.py加入auth蓝图

......
app.register_blueprint(authbp)

然后编写注册逻辑,需要数据库添加对象,父类InfoCrud可以加入一些通用方法

    @classmethod
    def getall(cls, **kwargs):
        return cls.query.filter_by(**kwargs).all()

    @classmethod
    def getone(cls, id):
        return cls.query.get(id)

    @classmethod
    def add(cls, data):
        obj = cls(**data)
        db.session.add(obj)
        db.session.commit()
        return obj

    @classmethod
    def edit(cls, data):
        sql = update(cls).values(**data).where(cls.id == data['id'])
        db.session.execute(sql)
        db.session.commit()

    @classmethod
    def remove(cls, id):
        db.session.delete(cls.query.get(id))
        db.session.commit()

    @classmethod
    def exist(cls, **kwargs):
        return (cls.query.filter_by(**kwargs).count()) > 0

api/auth.py编写注册代码,这里使用flask_restful校验请求字段,密码用generate_password_hash进行加密

from flask import Blueprint, jsonify
from werkzeug.security import generate_password_hash
from models.user import User

authbp = Blueprint('auth',__name__,url_prefix="")

@authbp.route("/register",methods=['POST'])
def register():
    args = request.json
    if User.exist(username=args['username']):
        return jsonify(code=400,msg="用户已存在")
    args.update({'password': generate_password_hash(args['password'], salt_length=8)})
    User.add(args)
    return jsonify(
{
"code": 0,
"msg": "success"
}
)

group.py编写添加分组接口

from flask import Blueprint, jsonify
from models.group import Group

groupbp = Blueprint('group',__name__,url_prefix="/group")

@groupbp.route("/add",methods=['POST'])
def add():
    args = request.json
    if Group.exist(name=args['name']):
        return jsonify(code=400,msg="用户已存在")
    Group.add(args)
    return jsonify(
{
"code": 0,
"msg": "success"
}
)

app.py

......
app.register_blueprint(groupbp)

新建testapi.py测试接口,也可以使用api工具进行测试

from app import app

client = app.test_client()

def test_add_user():
    with app.app_context():
        r = client.post("/register",json={"username":"a","password":"111111"})
        print(r.text)

def test_add_group():
    with app.app_context():
        r = client.post("/group/add",json={"name":"管理员","info":"管理员"})
        print(r.text)

if __name__ == '__main__':
    test_add_group()
    test_add_user()

 

编写登录接口,使用flask_jwt_extended.create_access_token创建access_token

from flask_jwt_extended import create_access_token
from werkzeug.security import generate_password_hash, check_password_hash
from flask_restful import reqparse
@authbp.route("/login",methods=['POST'])
def login():
    parser = reqparse.RequestParser()
    parser.add_argument("username", type=str, required=True, help="username is required")
    parser.add_argument('password', required=True, type=str, help='password is required')
    args = parser.parse_args()
    user = User.query.filter_by(username=args['username']).first()
    if user is None or user.delete_time is not None:
        return jsonify(code=400,msg="用户不存在")
    ispass = check_password_hash(user.password, args['password'])
    if not ispass:
        return jsonify(code=400,msg="密码错误")
    access_token = create_access_token(identity=user.id)
    return jsonify(code=0,msg="登录成功",data={
            'userid': user.id,
            'access_token': access_token,
            'nickname': user.nickname,
            'username': user.username
        })

根目录添加auth.py,编写初始化JWTManager,以及校验用户是否登录的装饰器给后续接口做权限验证

from functools import wraps
from flask import jsonify
from flask_jwt_extended import verify_jwt_in_request, JWTManager

jwt = JWTManager()

def login_required(fn):
    @wraps(fn)
    def wrapper(*args,**kwargs):
        verify_jwt_in_request()
        return fn(*args,**kwargs)
    return wrapper

@jwt.unauthorized_loader
def unauthorized_loader_callback(e):
    return jsonify(code=10000,msg="认证失败,请检查请求头或者重新登陆")

jwt初始化app

app = Flask(__name__)
...
from auth import jwt
jwt.init_app(app)

接口登录成功

这样用户的注册和登录基本实现,下一步编写登录后其它数据的增删改查,并实现登录权限校验以及为用户指定权限。

posted @ 2022-10-16 19:01  紧肛胡撸娃  阅读(988)  评论(1编辑  收藏  举报