python 七牛云图片上传 demo

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))

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值