码迷,mamicode.com
首页 > 其他好文 > 详细

在django中使用七牛云

时间:2020-02-07 21:00:00      阅读:109      评论:0      收藏:0      [点我收藏+]

标签:one   response   bsp   turn   view   boot   append   val   request   

一、配置环境

django 3.0.3 

qiniu 7.2.6

全部可以使用pip安装

二、在app的目录下创建qiniu_config.py文件,用于存放七牛云的相关配置信息

qiniu_config = {
    access_key: ‘‘,
    secret_key: ‘‘,
    bucket_name: ‘‘,
    domine: ‘‘,
}
#bucket_name:空间名
#domine:cdn加速域名

三、views.py

from django.shortcuts import render, HttpResponse
import qiniu
import json
from qiniu_app.qiniu_config import qiniu_config


# 七牛身份验证
def qiniu_auth():
    access_key = qiniu_config[access_key]
    secret_key = qiniu_config[secret_key]
    q = qiniu.Auth(access_key, secret_key)
    return q


# Create your views here.
# 将上传处理后的图片刷新到cdn节点,减少回源流量
def cdn_flush(key):
    auth = qiniu_auth()
    cdn_manager = qiniu.CdnManager(auth)
    domine = qiniu_config[domine]
    need_flush_url = domine + key
    # 需要刷新的文件链接
    urls = [
        need_flush_url,
    ]
    # URL刷新链接
    refresh_url_result = cdn_manager.refresh_urls(urls)
    return


# 进行上传的图片处理
def dealwith_img(request):
    q = qiniu_auth()
    key = request.GET.get(key)
    bucket_name = qiniu_config[bucket_name]
    # pipeline是使用的队列名称,不设置代表不使用私有队列,使用公有队列。
    # pipeline = ‘your_pipeline‘
    # 要进行的转换格式操作。
    fops = imageView2/0/format/webp/interlace/1
    # 可以对缩略后的文件进行使用saveas参数自定义命名,当然也可以不指定文件会默认命名并保存在当前空间
    saveas_key = qiniu.urlsafe_base64_encode(bucket_name + : + key)
    fops = fops + |saveas/ + saveas_key
    # pfop = qiniu.PersistentFop(q, bucket_name, pipeline)
    pfop = qiniu.PersistentFop(q, bucket_name)
    ops = []
    ops.append(fops)
    ret, info = pfop.execute(key, ops, 1)
    assert ret[persistentId] is not None
    cdn_flush(key)
    return HttpResponse(json.dumps(ok))


# 获取七牛上传的token
def qntoken(request):
    q = qiniu_auth()
    key = request.GET.get(key)
    bucket = qiniu_config[bucket_name]
    token = q.upload_token(bucket, key)
    return HttpResponse(json.dumps({token: token}))


def qiniu_test(request):
    return render(request, qiniu_test.html)

四、urls.py

from django.urls import path
from qiniu_app import views
urlpatterns = [
    path(qntoken/, views.qntoken, name="qntoken"),
    path(‘‘, views.qiniu_test, name="qiniu_test"),
    path(dealwith_img/, views.dealwith_img, name="dealwith_img"),
]

五、html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://unpkg.com/qiniu-js@2.5.5/dist/qiniu.min.js"></script>
</head>
<body>


<from>
    <input type="file" id="img" value="上传图片">
</from>
上传后的url:<span id="img_url"></span>


<script>// 上传完图片后做的事情
    function com_img(ret) {
        var img_name = ret[key];
        var domine = ; // cdn加速域名
        var img_url = domine + img_name; //合成访问的链接
        $(span#img_url).text(img_url);
        // 在后端处理上传的图片
        $.ajax({
            url: {% url dealwith_img %},
            type: GET,
            data: {key: img_name},
            dataType: json,
            error: function () {
                alert("处理失败")
            }
        })
    }

    $(#img).change(function () {
            var token = ‘‘;
            var file_img = $(#img).get(0).files[0];
            var key = (new Date()).getTime() + . + file_img.name.split(.)[1];
            $.ajax({
                url: {% url qntoken %},
                type: GET,
                data: {key: key},
                dataType: json,
                success: function (token_msg) {
                    token = token_msg[token];
                    console.log(token);
                    var putExtra = {
                        fname: key,
                        params: {},
                        mimeType: [image/png, image/jpeg]
                    };
                    var config = {
                        useCdnDomain: true,
                        retryCount: 6,
                        region: qiniu.region.z0
                    };
                    var observable = qiniu.upload(file_img, key, token, putExtra, config)
                    var subscription = observable.subscribe({error: up_err, complete: com_img}) // 上传开始
                }
            });
        }
    );

</script>
</body>
</html>

 

在django中使用七牛云

标签:one   response   bsp   turn   view   boot   append   val   request   

原文地址:https://www.cnblogs.com/xshan/p/12274249.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!