1》 安装 七牛sdk
pip install qiniu
2》 settings.py
INSTALLED_APPS[
*****,
qiniu
*****,
]
3》
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020-12-09 21:46
# @Author : lyw
# @Site :
# @File : qiniuupload.py
# @Software: PyCharm
import datetime
import os
import random
import time
from time import timezone
import os.path
from apps.exchange.models import TokenInfo, TokenInfoNewDescription
import sys
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(os.path.join(BASE_DIR, 'apps'))
sys.path.append(BASE_DIR)
os.environ["DJANGO_SETTINGS_MODULE"] = "lyw.settings"
import django
django.setup()
# 七牛云的sdk 调用
from qiniu import Auth, put_file, etag
import qiniu.config
# 为了安全 ,把access_key, secret_key 存入数据库,建议做响应的 安全处理,比如 加 slate
from **** import ThirdPartyKey # 存密钥的表
from ***** import QiNiuUploadLog #上传的log
class QiNiuUpload():
def __init__(self):
# 为安全性 要从数据库读 并进行 保密处理
keyList = self.get_key()
self.AK = keyList.access_key
self.SK = keyList.secret_key
self.BuketName = 'coinxiaobao'
def get_key(self):
try:
key_list = ThirdPartyKey.objects.filter(status=2,key_type=1)
return key_list[0]
except:
return []
def qiniu_upload_image(self,folder, localfile, save_file_name=''):
"""
Image upload
:param folder: Simulate folder path
:param localfile: Locally uploaded files
:param save_file_name: It is generated randomly without passing the file name
:return:
"""
q = Auth(self.AK, self.SK)
bucket_name = self.BuketName
if save_file_name == '':
fileName = str(localfile).split('.')
signtime = datetime.datetime.now().strftime('%Y%m%d%H%M%S%f')
key = folder + str(signtime)+"."+str(fileName[1])
else:
key = folder+save_file_name
token = q.upload_token(bucket_name, key, 36000000000)
ret, info = put_file(token, key, localfile)
assert ret['key'] == key
assert ret['hash'] == etag(localfile)
def qiniu_upload_image_save(self,localfile):
"""
Image upload
:param folder: Simulate folder path
:param localfile: Locally uploaded files
:param save_file_name: It is generated randomly without passing the file name
:return:
"""
# You need to fill in your access key and secret key
# Building authentication object
q = Auth(self.AK, self.SK)
# Space to upload
bucket_name = self.BuketName
# File name saved after upload
key = str(localfile).replace('static/','') # 个人逻辑处理需求
# Generate upload token, and you can specify the expiration time, etc
token = q.upload_token(bucket_name, key, 3600) # 这历史 密钥的存活日期,
# Local path to upload file
ret, info = put_file(token, key, localfile)
assert ret['key'] == key
assert ret['hash'] == etag(localfile)
if info.status_code:
return key
else:
return str(info)
def get_filelist(self,t=1):
"""
Read folder file
:param t: 1 Test 2 official upload
:return:
"""
# Indicates the folder being traversed
for s in ['static/article','static/media','static/upload','static/articlecrawler']:
rootdir = s
# Three parameters: Return 1. Parent directory 2. Names of all folders (excluding paths) 3. Names of all files
i = 1
for parent, dirnames, filenames in os.walk(rootdir):
for filename in filenames:
file_name = os.path.join(parent, filename)
suffix = str(file_name).split('.') # 这里获取后缀名
try:
if str(suffix[1]) in ['jpg','jpeg','png','ico','js']: # 这里检查文件名
new_file = str(file_name).replace('static/','') # 这里要保存的新文件名, 个人需求保持原文件名
findImage = QiNiuUploadLog.objects.filter(image_name=str(new_file)).first()
if findImage:
continue
res = self.qiniu_upload_image_save(str(file_name))
QiNiuUploadLog.objects.create(image_name=str(new_file),logs=str(res))
i += 1
else:
continue
except:
continue
if t == 1:
break
4 》 调用
if __name__ == '__main__':
print(QiNiuUpload().get_filelist(2))