Flask 学习-24.用户注册(sha256_crypt对密码加密)

前言

用户注册的时候,密码需要加密保存,这里使用 passlib 库对密码进行hash。

环境准备

需用到passlib 库,使用pip安装

pip install passlib

passlib 库里面会用到2个方法

  • encrypt() - 生成新的值,返回密码哈希
  • verify() - 根据现有哈希验证密码.

User表

先设计注册表

from . import db
from passlib.hash import sha256_crypt



class Users(db.Model):
    __tablename__ = 'user'  # 数据库表名
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String(50), unique=True, nullable=False)
    password = db.Column(db.String(128), nullable=False)
    is_active = db.Column(db.Boolean, default=1)
    email = db.Column(db.String(64), nullable=True)

    def hash_password(self, password):
        """密码加密"""
        self.password = sha256_crypt.encrypt(password)

    def verify_password(self, password):
        """校验密码"""
        return sha256_crypt.verify(password, self.password)

同步到数据库

flask db migrate  # ⽣成迁移版本, 保存到迁移文件夹中
flask db upgrade  # 执行迁移

get_json() 获取请求的json参数

如果请求头部是Content-Type: application/json,那么可以用request.json() 获取到请求的参数,得到一个字典对象

get_json() 源码相关介绍

 def get_json(
        self, force: bool = False, silent: bool = False, cache: bool = True
    ) -> t.Optional[t.Any]:
        """Parse :attr:`data` as JSON.

        If the mimetype does not indicate JSON
        (:mimetype:`application/json`, see :attr:`is_json`), or parsing
        fails, :meth:`on_json_loading_failed` is called and
        its return value is used as the return value. By default this
        raises a 400 Bad Request error.

        :param force: Ignore the mimetype and always try to parse JSON.
        :param silent: Silence mimetype and parsing errors, and
            return ``None`` instead.
        :param cache: Store the parsed JSON to return for subsequent
            calls.

        .. versionchanged:: 2.1
            Raise a 400 error if the content type is incorrect.
        """

request 还有个 json 属性也可以获取到请求的json参数, json属性不需要加括号,如下

        data = request.json
        print(f'请求入参:{data}')

注册接口开发

开发 restful 风格接口

from apps import create_app, db
from flask import url_for, request, jsonify
from flask_restful import reqparse, abort, Api, Resource
from apps.models import Users
app = create_app()
api = Api(app)


class Register(Resource):

    def post(self):
        # 获取入参
        data = request.get_json()
        print(f'请求入参:{data}')
        username = data.get("username")
        password = data.get("password")
        if not username or not password:
            return jsonify({"code": 111, "msg": "账号或密码不能为空"})
        # 查询,判断是否已存在
        if Users.query.filter_by(username=username).first() is not None:
            print('existing user')
            return jsonify({"code": 222, "msg": "账号已存在"})
        user = Users(username=username)
        user.hash_password(password)
        db.session.add(user)
        db.session.commit()
        return jsonify({
            "code": 0,
            "msg": "success",
            "data": {"username": username}
        })


# 注册
api.add_resource(Register, '/api/v1/register')

if __name__ == '__main__':
    app.run()

测试接口

测试注册接口

POST http://127.0.0.1:5000/api/v1/register HTTP/1.1
User-Agent: Fiddler
Host: 127.0.0.1:5000
Content-Type: application/json
Content-Length: 54

{
    "username": "test",
    "password": "123456"
}

接口返回

HTTP/1.1 200 OK
Server: Werkzeug/2.2.2 Python/3.8.5
Date: Tue, 30 Aug 2022 06:50:58 GMT
Content-Type: application/json
Content-Length: 77
Connection: close

{
  "code": 0,
  "data": {
    "username": "test"
  },
  "msg": "success"
}

查看数据库

posted @ 2022-08-30 14:57  上海-悠悠  阅读(421)  评论(0编辑  收藏  举报