python 七牛云上传下载图片并存储到数据库

首先找到自己的AK 和SK 在个人的密钥管理里面

bucket_domain 为自己的外链域名key则是你存储的图片名字

# 设置存储空间名称
bucket_name = "空间名称"
# 构建鉴权对象  用于上传和下载
auth = qiniu.Auth(access_key, secret_key)

这是下载方式

# -*- coding: utf-8 -*-
# flake8: noqa
import requests

from qiniu import Auth

#AK、SK可在控制台的个人中心里面获取
access_key = 'AK'
secret_key = 'SK'

q = Auth(access_key, secret_key)

#有两种方式构造base_url的形式
base_url = 'http://%s/%s' % (bucket_domain, key)

#或者直接输入url的方式下载
base_url = 'http://domain/key'

#可以设置token过期时间
private_url = q.private_download_url(base_url, expires=3600)

print(private_url)
r = requests.get(private_url)
assert r.status_code == 200

以下是我的代码示例

这个函数使用在我中途添加图片到数据库中

ret['key'] 为存储在七牛云中的名称

private_url 就为网上在线图片时私有外部链接有token时限

如 [GET] http://<domain>/<key>?e=<deadline>&token=<downloadToken>

如果是公有空间链接  直接为http://<domain>/<key>


import qiniu
access_key = "xxx"

secret_key = "xxx"

# 构建鉴权对象
auth = qiniu.Auth(access_key, secret_key)

# 设置存储空间名称
bucket_name = "xxxx"

@action(methods=['post'], detail=True, url_path='img')
    def upload_image_to_qiniu(self,request,pk):
        # 获取上传的文件
        image_file = request.FILES.get("image")
        bucket_domain = 'xxxxx.clouddn.com'
        if image_file:
            # 读取文件内容
            image_data = image_file.read()

            # 构建上传用的 Token
            token = auth.upload_token(bucket_name)

            # 上传文件数据
            ret, info = qiniu.put_data(token, None, image_data)


            if ret is not None and "key" in ret:
                image_key = ret["key"]
                instance = TTopic.objects.get(article_id=pk)
                instance.img =image_key
                instance.save()
                print(image_key)
                base_url = 'http://%s/%s' % (bucket_domain, image_key)
                private_url = auth.private_download_url(base_url, expires=3600)
                return Response({"private_url": private_url})
            else:
                return Response({"error": "Image upload failed"})
        else:
            return Response({"error": "No image file found in the request"})

更多功能可通过七牛云文档自行查看

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值