flask restful mysql_使用Flask-Restful实现API接口

1. 代码结构:

73b99e97b69f

2. 具体代码

2.1 user.py

from ApiRESTful.extensions 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设置为私有属性,并且重命名

_password = db.Column('password', db.String(128))

# 定义一个属性,默认是读取的操作,这里报错,意思是不可读

@property

def password(self):

raise AttributeError('password is not readable attribute')

# 定义上面那个password属性的可写属性,这里默认换算成哈希值,然后保存下来

@password.setter

def password(self, password):

self._password = generate_password_hash(password)

# 校验传入的密码和哈希值是否是一对儿

def verify_password(self, password):

return check_password_hash(self._password, password)

def __repr__(self):

return "".format(self.username)

2.2 api_auth.py

Flask-Httpauth是用来验证用户的,但在这个部分中没有用到,之后会专门来写一个。

from flask_httpauth import HTTPBasicAuth

from flask import jsonify, app

from itsdangerous import TimedJSONWebSignatureSerializer as Serializer

from itsdangerous import SignatureExpired, BadSignature

from ApiRESTful.settings import DevelopConfig

from ApiRESTful.models.user import User

auth = HTTPBasicAuth()

@(FLASK)auth.error_handler

def unauthorized():

error_info = '{}'.format('Invalid credentials')

print('api.auth.unauthorized.error_info = ' + error_info)

response = jsonify({'error': error_info})

response.status_code = 403

print('api.auth.unauthorized.response = ' + str(response))

return response

def verify_password_for_token(username, password):

"

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值