当前位置:网站首页>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')
边栏推荐
- Niuke brush questions - MySQL series
- event.preventDefault VS return false
- Japan approves the export of EUV photoresist to South Korea, and the crisis of Samsung and SK Hynix may be alleviated
- 七、微信小程序运行报错:Error: AppID 不合法,invalid appid
- [download materials of harmoniyos topics] HDD Hangzhou station · offline salon focuses on application innovation to show the ecological charm of Hongmeng
- 美国再次发难:禁止承包商采购这5家中国公司的设备与技术
- ROS2节点通信实现零拷贝
- 2022年简历石沉大海,别投了,软件测试岗位饱和了....
- ROS2获取当前系统时间的方法
- Object. getOwnPropertyNames() VS Object.keys()
猜你喜欢
![[hero planet July training leetcode problem solving daily] 26th and check the collection](/img/f1/e63b1f35b883274ca077cbd2ab4c24.png)
[hero planet July training leetcode problem solving daily] 26th and check the collection
![[hcie security] dual computer hot standby - primary and standby backup](/img/3b/392aabd9915a3f0997cf7a72240d63.png)
[hcie security] dual computer hot standby - primary and standby backup

golang版本管理gvm

1-《PyTorch深度学习实践》-线性模型
HTTP cache browser cache that rabbits can understand

一些意想不到的bug记录

Registration conditions for information system project managers in the second half of 2022 (soft examination advanced)

DeepFake捏脸真假难辨,汤姆·克鲁斯比本人还像本人!

js中join方法

《暑假每日一题》Week 7:7.18 - 7.24
随机推荐
记一次invalid bound statement xxxxxx 问题解决思路
分布式 session 的4个解决方案
:active vs :focus
五、小程序报错:message:Error: 系统错误,错误码:80058,desc of scope.userLocation is empty
MySQL -count: the difference between count (1), count (*), and count (column name)
Live broadcast appointment award | senior consultant xuyanfei: how does efficiency measurement help efficient and sophisticated outsourcing management
Uncover the secrets of Xiaomi 100million pixel camera: 1/1.3 inch COMS sensor, resolution 12032 × nine thousand and twenty-four
Calculation formula of retained earnings rate
CFdiv1+2-Pathwalks-(树状数组+线性dp)
Object. getOwnPropertyNames() VS Object.keys()
拼多多获得搜索词推荐 API
event.preventDefault VS return false
Difference between redis hash and string
三星发布1.08亿像素图像传感器ISOCELL Bright HMX,小米将首发
Filtering and distortion
按关键字搜索易贝商品 API
Why does it system need observability?
虾皮shopee根据关键词取商品列表 API
商汤科技发布人脸识别一体机SensePass Pro
Sort the table by clicking on the header