当前位置:网站首页>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')
边栏推荐
- Vi和Vim文本编辑器
- Browser browser cache
- 【HCIA安全】NAT网络地址转换
- contenteditable 元素的placeholder
- Remember the idea of solving the problem of invalid bound statement xxxxx once
- Cfdiv1+2-pathwalks- (tree array + linear DP)
- Devsecops, speed and security
- 华为发布2025十大趋势:5G、机器人、AI等上榜
- 【Flutter -- GetX】弹框 - Dialog、Snackbar、BottomSheet
- JS click the picture to print the image
猜你喜欢

七、微信小程序运行报错:Error: AppID 不合法,invalid appid

SPI configuration
![[download materials of harmoniyos topics] HDD Hangzhou station · offline salon focuses on application innovation to show the ecological charm of Hongmeng](/img/62/9e2ff0dc2c8b049fd32ad56334a0c0.jpg)
[download materials of harmoniyos topics] HDD Hangzhou station · offline salon focuses on application innovation to show the ecological charm of Hongmeng

基于Hough变换的直线检测(Matlab)

How to use multiple languages in a project?

FreeRTOS个人笔记-软件定时器

如何在一个项目中使用多种不同的语言?

CMake 的使用

安全浏览器“隐身”模式可以查看历史记录吗?

Devops has been practiced for many years. What is the most painful thing?
随机推荐
六、微信小程序发布流程
golang版本管理gvm
Live broadcast appointment award | senior consultant xuyanfei: how does efficiency measurement help efficient and sophisticated outsourcing management
伟创力回应“扣押华为物料”事件:深感遗憾,期待继续合作!
基于memcache的缓存机制的6个指令
js中join方法
七、微信小程序运行报错:Error: AppID 不合法,invalid appid
Summary of common interview questions of computer composition principle, including answers
Mobile phone \ landline call forwarding setting method
(C language) a brief introduction to define
小米1亿像素摄像头揭秘:1/1.3英寸COMS传感器、分辨率12032×9024
Is it safe for Huishang futures to open an account? What should Huishang futures pay attention to when opening an account?
力扣每日一题-第43天-168. Excel表列名称
织梦文档关键词维护不管用
Smooth scroll to element
[HCIA security] bidirectional nat
Number() VS parseInt()
JS click the picture to print the image
Object. getOwnPropertyNames() VS Object.keys()
Type assertion in typescript