当前位置:网站首页>Flag decodes token, mounts token, decorator, and seven cattle cloud upload
Flag decodes token, mounts token, decorator, and seven cattle cloud upload
2022-07-26 21:40:00 【du fei】
Create a utils/JwtTools.py Folder
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
Write login logic
# Mount before request
@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
# Decorator
def login(func):
def warpper(*args, **kwargs):
print(' Detect login ')
if not g.uid:
return jsonify({
'code': 403, 'msg': ' User not registered '})
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': ' User information obtained successfully ',
'data': {
'username': user_info.username,
'img': user_info.img
}
})
api.add_resource(UserView, '/user')
A simple logic of uploading pictures
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': ' Upload successful '})
return jsonify({
'code': 400, 'msg': ' Upload failed '})
api.add_resource(UploadView, '/upload')
Package seven cattle cloud upload method
- Create a utils/QiniuTooks.py File write code
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):
""" To upload pictures :param localfilepath: Picture path :param newfilename: The name of the uploaded picture :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')
- Called in the view
from datetime import datetime
from utils.QiniuTools import QiniuTool
class UploadView(Resource):
def post(self):
# Get the files that need to be uploaded
img = request.files.get('img')
# Get the suffix of the picture
ext = img.filename.split('.')[-1]
# Get the timestamp and splice
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)
# The splicing route is saved locally
save_path = f'static/{
new_name}'
img.save(save_path)
# Upload to qiniuyun
res = QiniuTool().upload(save_path, save_path)
if not res:
return jsonify({
'code': 400, 'msg': ' Upload failed '})
# Save to database
user_info = UserModel.query.get(g.uid)
user_info.img = save_path
db.session.commit()
return jsonify({
'code': 200, 'msg': ' Upload successful ', 'data': save_path})
api.add_resource(UploadView, '/upload')
边栏推荐
- Zoom the text to fit inside the element
- 安全浏览器“隐身”模式可以查看历史记录吗?
- 单机部署flink,创建oracle19c rac的连接表时报错 ORA-12505,有哪位大佬帮忙
- (C language) a brief introduction to define
- Get the direction of text selection
- Smooth scroll to element
- Object.getOwnPropertyNames() VS Object.keys()
- 《暑假每日一题》Week 7:7.18 - 7.24
- 6、 Wechat applet release process
- 调整表格列的大小
猜你喜欢

FreeRTOS personal notes - Events

Selenium自动化测试面试题全家桶

FreeRTOS个人笔记-事件

Alkbh1

Vi和Vim文本编辑器

What are the characteristics of low code tools? The two development tracks of low code that can be seen by discerning people!

CMake 的使用

Deepfake pinches his face. It's hard to tell whether it's true or false. Tom Cruise is more like himself than himself!
![[HCIA security] NAT network address translation](/img/10/3b4d011963e00229d73a7435ce8c4b.png)
[HCIA security] NAT network address translation

Flash source code outline
随机推荐
encodeURI VS encodeURIComponent
Test cases should never be used casually, recording the thinking caused by the exception of a test case
Object.getOwnPropertyNames() VS Object.keys()
伟创力回应“扣押华为物料”事件:深感遗憾,期待继续合作!
浏览器主页被篡改怎么办,主页被篡改恢复方法
Redis hash和string的区别
ECCV 2022 | complete four tracking tasks at the same time! Unicorn: towards the unification of target tracking
Huawei released the top ten trends in 2025: 5g, robot, AI, etc
TCP的粘包拆包问题解决方案
2022年简历石沉大海,别投了,软件测试岗位饱和了....
在上传之前预览图像
Smooth scroll to element
js中join方法
Sort the table by clicking on the header
7、 Wechat applet running error: error: illegal appid, invalid appid
FreeRTOS个人笔记-事件
word-break: break-all VS word-wrap: break-word
攻防世界----ics-07
如何在一个项目中使用多种不同的语言?
Alkbh1