当前位置:网站首页>Flask对token的解码&挂载&装饰器&七牛云上传
Flask对token的解码&挂载&装饰器&七牛云上传
2022-07-26 20:48:00 【du fei】
创建一个utils/JwtTools.py文件夹
import jwt
class JwtTool():
def valid(self, token):
secret_key = current_app.config.get('SECRET_KEY')
try:
time.sleep(2)
payload = jwt.decode(token, secret_key, algorithms='HS256')
print(payload)
return payload
except Exception as e:
print(e)
return False
写入登录逻辑
# 请求前挂载
@user_bp.before_request
def gz():
req = reqparse.RequestParser()
req.add_argument('token', default='', location='headers')
args = req.parse_args()
token = args['token']
payload = JwtTool().valid(token)
print('========', payload)
if not payload:
uid = 0
else:
uid = payload['id']
g.uid = uid
# 装饰器
def login(func):
def warpper(*args, **kwargs):
print('检测登录')
if not g.uid:
return jsonify({
'code': 403, 'msg': '用户未登记'})
return func(*args, **kwargs)
return warpper
class UserView(Resource):
@login
def get(self):
user_info = UserModel.query.get(g.uid)
return jsonify({
'code': 200,
'msg': '用户信息获取成功',
'data': {
'username': user_info.username,
'img': user_info.img
}
})
api.add_resource(UserView, '/user')
一个简单上传图片的逻辑
class UploadView(Resource):
def post(self):
key = '1.jpg'
ak = 'qIpsogKsnioK63SvhCDMp*************OGOW4_'
sk = 'Gmg0YLb5QKzQYxAH2Dspi**************U43L5'
q = Auth(ak, sk)
bucket = 'h2111p7123'
token = q.upload_token(bucket, key, 3600)
res = put_file(token, key, './static/1.jpg', version='v2')
if res[0]['key'] == key:
return jsonify({
'code': 200, 'msg': '上传成功'})
return jsonify({
'code': 400, 'msg': '上传失败'})
api.add_resource(UploadView, '/upload')
封装七牛云上传方法
- 创建一个utils/QiniuTooks.py文件写入代码
from qiniu import Auth, put_file
from flask import current_app
class QiniuTool():
def __init__(self):
ak = current_app.config.get('QINIU_AK')
sk = current_app.config.get('QINIU_SK')
self.q = Auth(ak, sk)
self.bucket_name = current_app.config.get('QINIU_BUCHET_NAME')
def upload(self, localfilepath, newfilename):
""" 上传图片 :param localfilepath: 图片路径 :param newfilename: 上传后的图片名 :return: """
token = self.q.upload_token(self.bucket_name, newfilename, 3600)
ser = put_file(token, newfilename, localfilepath, version='v2')
if ser[0]['key'] == newfilename:
return newfilename
return False
if __name__ == '__main__':
from app import app
with app.app_context():
QiniuTool().upload('./../static/1.jpg', 'static/img/1.jpg')
- 在视图中调用
from datetime import datetime
from utils.QiniuTools import QiniuTool
class UploadView(Resource):
def post(self):
# 获取需要上传的文件
img = request.files.get('img')
# 获取图片的后缀名
ext = img.filename.split('.')[-1]
# 获取时间戳并拼接
now_time = datetime.strftime(datetime.now(), '%Y%m%d%H%M%S')
new_name = f'{
now_time + str(random.randint(1000,9999))}.{
ext}'
# print(new_name)
# 拼接路由保存到本地
save_path = f'static/{
new_name}'
img.save(save_path)
# 上传到七牛云
res = QiniuTool().upload(save_path, save_path)
if not res:
return jsonify({
'code': 400, 'msg': '上传失败'})
# 保存到数据库
user_info = UserModel.query.get(g.uid)
user_info.img = save_path
db.session.commit()
return jsonify({
'code': 200, 'msg': '上传成功', 'data': save_path})
api.add_resource(UploadView, '/upload')
边栏推荐
猜你喜欢
随机推荐
按图搜索义乌购商品(拍立淘) API
Uncover the secrets of Xiaomi 100million pixel camera: 1/1.3 inch COMS sensor, resolution 12032 × nine thousand and twenty-four
Cfdiv1+2-pathwalks- (tree array + linear DP)
Zoom the text to fit inside the element
Basic use of livedatade
美国再次发难:禁止承包商采购这5家中国公司的设备与技术
Summary of common interview questions of operating system, including answers
Custom annotation (I)
Props with type Object/Array must...
【HCIE安全】双机热备-主备备份
Ros2 node communication realizes zero copy
Number() VS parseInt()
Multivariable time series prediction using LSTM -- problem summary
2022年简历石沉大海,别投了,软件测试岗位饱和了....
encodeURI VS encodeURIComponent
CONDA reports an error: json.decoder.jsondecodeerror:
【Flutter -- GetX】弹框 - Dialog、Snackbar、BottomSheet
DeepFake捏脸真假难辨,汤姆·克鲁斯比本人还像本人!
TypeScript中的类型断言
Set the template of core configuration file in idea




![[hero planet July training leetcode problem solving daily] 26th and check the collection](/img/f1/e63b1f35b883274ca077cbd2ab4c24.png)
![[HCIA security] user authentication](/img/6f/0ab6287eac36a4647dc2a0646ba969.png)


