Flask之输出字段

1. 首先我们创建一个User类
from app import db
from werkzeug.security import generate_password_hash, check_password_hash


class User(db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), unique=True, index=True)
    password_hash = db.Column(db.String(128))

    # 定义一个属性,默认是读取的操作,这里报错,意思是不可读
    @property
    def password(self):
        raise AttributeError('password is not readable attribute')

    # 定义上面那个password属性的可写属性,这里默认换算成哈希值,然后保存下来
    @password.setter
    def password(self, password):
        self.password_hash = generate_password_hash(password)

    # 校验传入的密码和哈希值是否是一对儿
    def verify_password(self, password):
        return check_password_hash(self.password_hash, password)

    def __repr__(self):
        return "".format(self.username)
2. 我们使用marshal_with来将输出的内容格式化
from flask_restful import Api, Resource, reqparse, fields, marshal_with
from app.api_1_0 import api_1_0
from app.models.user import User

api_user = Api(api_1_0)


class PasswordItem(fields.Raw):
    def format(self, value):
        return value


resource_fields = {
    'id': fields.String,
    'username': fields.String,
    'password_hash': fields.String
}


class UserGetApi(Resource):
    @marshal_with(resource_fields, envelope='users')
    def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument('username', type=str, required=True, help="username cannot be blank!", location='args')
        args = parser.parse_args()
        username = args.get('username')
        parser.remove_argument('username')
        u = User.query.filter_by(username=username).all()
        return u


api_user.add_resource(UserGetApi, '/userget', endpoint='userget')

3. 验证输出结果
[root@test01 ~]# curl -H "Content-Type:application/json" -X GET http://192.168.1.59/api/userget?username=liuxin
{
    "users": [
        {
            "id": "1",
            "username": "liuxin",
            "password_hash": "pbkdf2:sha256:50000$PZLgoIbb$abf79799520658a7bd2b0a82e6f279ed209fa2f94017d68d288c758421a46102"
        }
    ]
}

你可能感兴趣的:(Flask之输出字段)