当前位置:网站首页>Forced login, seven cattle cloud upload pictures
Forced login, seven cattle cloud upload pictures
2022-07-27 08:30:00 【qishaoawei】
Force login jwt verification
Verification has been written in last blog jwt Function of
Then the project views In the catalog users.py In file
from flask import Blueprint, jsonify, g, request # Import blueprint
from flask_restful import Api, Resource, fields, marshal, reqparse
from models.model import UserModel2, db
from utils.QiniuTools import QiniuTool
from utils.jwtTools import JwtTools # Import build jwt Class
from utils.SmsTools import SmsTool # Import the class that generates the verification code
import random
# # url_prefix # Specify the prefix of all routes under the current blueprint
user_dp = Blueprint('user_dp', __name__, url_prefix='/users') # Instantiate blueprint objects
api = Api(user_dp) # Instantiate the blueprint collector # Instantiate a Api object Api Object is used to collect routes
# Define class view Inherited from Resource class , adopt Api To collect instantiated objects
class SmsView(Resource):
def post(self): # Get the verification code blueprint
...
@user_dp.before_request
def gz(): # Hook function Each request is executed once before it arrives
rep = reqparse.RequestParser()
rep.add_argument('token', location='headers')
args = rep.parse_args()
token = args['token']
payload = JwtTools().valid(token)
print(payload)
if not payload:
uid = 0
else:
uid = payload['uid']
g.uid = uid
def login(func): # Decorator
def warpper(*args, **kwargs):
print(' Detect login ')
if not g.uid: # If it is blank, it means that you have not logged in
return jsonify({
'code': 403,
'msg': ' The user is not logged in '
})
return func(*args, **kwargs)
return warpper
class UserView(Resource):
@login # Decorator
def get(self): # Test success
uid = g.uid
user_info = UserModel2.query.get(uid)
print('user_info:',user_info)
return jsonify({
'code': 200,
'msg': ' User information obtained successfully ',
'data': {
'username': user_info.username,
'img': user_info.img
}
})
def post(self):
...
api.add_resource(UserView, '/user') # The full address is /users/user

Seven cattle cloud upload pictures
First, create a qiniu cloud account , Then enter the personal center and write down your secret key 
Then enter the space management in the object storage to create a space 
CDN Test domain name 
After uploading the picture, you can domain name + You can view the picture by its name
The backend configuration
stay settings In the catalog secret.py Continue to add
class SecretConfig():
RL_ACC_ID='8aaf07088185853e01*************' #ACCOUNT SID( Master account ID)
RL_ACC_TOKEN='8ac934ad5ddf44a4**************' #AUTH TOKEN( Account authorization token )
RL_APP_ID='8aaf07088185853e*****************' #AppID( Default )
RL_TID='1' # SMS template ID
RDS_HOST='127.0.0.1' #redis database host
RDS_PORT=6379 #redis Port number
RDS_PASSWORD='*********' #redis password
QINIU_AK='Gs9_LCLxZ9RnNYijO-Gnx******************' #AK
QINIU_SK='KQwHB4cBqEOcxd3jlZM99****************' #sk
QINIU_BUCKET_NAME='p7h2111a' # Seven cattle cloud space
stay utils Create... In the directory QiniuTools.py file
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_BUCKET_NAME')
def upload(self, localfilepath, newfilename):
''' Seven cattle cloud upload pictures :param localfilepath: Local image address :param newfilename: Name after uploading :return: ''' # Space name # Name after uploading # The period of validity
token = self.q.upload_token(self.bucket_name, newfilename, 3600)
# Generated token # Name after uploading # Local image address
res = put_file(token, newfilename, localfilepath, version='v2')
print(res)
if res[0]['key']==newfilename:
return newfilename
else:
return False
if __name__ == '__main__': # You can test it now
from app import app
with app.app_context():
QiniuTool().upload('./../static/ Pillow .jpg',' Pillow .jpg')
Implement in view
from flask import Blueprint, jsonify, g, request # Import blueprint
from flask_restful import Api, Resource, fields, marshal, reqparse
from models.model import UserModel2, db
from utils.QiniuTools import QiniuTool
from utils.jwtTools import JwtTools # Import build jwt Class
from utils.SmsTools import SmsTool # Import the class that generates the verification code
import random
# # url_prefix # Specify the prefix of all routes under the current blueprint
user_dp = Blueprint('user_dp', __name__, url_prefix='/users') # Instantiate blueprint objects
api = Api(user_dp) # Instantiate the blueprint collector # Instantiate a Api object Api Object is used to collect routes
class UploadView(Resource):
@login
def post(self):
img = request.files.get("img") # To upload pictures
ext = img.filename.split(".")[-1] # according to . Split and take out the rear part
now_time = datetime.strftime(datetime.now(), "%Y%m%d%H%M%S") # Date:
new_name = "%s%s.%s" % (now_time, random.randint(100000, 999999), ext) # Add random numbers in the middle of splicing
save_path = "static/%s" % new_name # Insert the generated name
img.save(save_path)
# thus , Upload pictures to local
# Then it reached seven cattle cloud
res = QiniuTool().upload(save_path, save_path)
if not res:
return jsonify({
"code": 400,
"msg": " File upload failed "
})
# Save the uploaded file name into the database
user_info = UserModel2.query.get(g.uid)
user_info.img = res
db.session.commit()
return jsonify({
"code": 200,
"msg": ' File upload succeeded ',
"data": {
"key": res
}
})
### Another way
# key=' Pillow .jpg'
# ak = 'Gs9_LCLxZ9RnNYijO-G********************'
# sk = 'KQwHB4cBqEOcxd3j**********************'
# bucket = 'p7h2111a'
# q=Auth(ak,sk)
# token=q.upload_token(bucket,key,3600)
# res=put_file(token,key,'./static/ Pillow .jpg',version='v2')
# if res[0]['key']==key:
# return jsonify({
# 'code':200,
# 'msh':' Upload successful '
# })
# return jsonify({
# 'code': 400,
# 'msh': ' Upload failed '
# })
api.add_resource(UploadView, '/upl') # The full address is /users/upl

边栏推荐
- Realization of background channel group management function
- docker 安装mysql后进入容器内部发现登录不了mysql
- Interviewer: what is scaffolding? Why do you need scaffolding? What are the commonly used scaffolds?
- 2022-07-26 group 4 abstract classes and interfaces
- Help send some recruitment. If you are interested, you can have a look
- Breadth first search
- All in one 1319 - queue for water
- 说透缓存一致性与内存屏障
- [NPUCTF2020]ReadlezPHP 1
- Realize SKU management in the background
猜你喜欢

信息化项目风险控制与应用

情人节,我用字符画出了一个对象!

It's better to be full than delicious; It's better to be drunk than drunk

Use of "PHP Basics" Boolean

Solution to the program design of the sequence structure of one book (Chapter 1)

I drew a Gu ailing with characters!

What is the real HTAP? (1) Background article

Node installation and debugging

Introduction to depth first search (DFS)

All in one 1353 -- expression bracket matching (stack)
随机推荐
Software test interview questions (key points)
Minio 安装与使用
2022-07-26 group 4 abstract classes and interfaces
[geek challenge 2019] finalsql 1
"PHP Basics" PHP statements and statement blocks
Risk control and application of informatization project
Plato farm is expected to further expand its ecosystem through elephant swap
One book 1201 Fibonacci sequence
Leetcode54. Spiral matrix
[MRCTF2020]Ezpop 1
Realize SKU management in the background
pytorch_demo1
Massive data Xiao Feng: jointly build and govern opengauss root community and share a thriving new ecosystem
idea远程调试
The response of the database interface is very slow
Redis configuration file download
带宽 与 货币
Dirsearch[directory scanning tool]
Apache SSI remote command execution vulnerability
Idea remote debugging