django 调用oss实现签名直传并回调上传,下载服务

1.配常量

# ACCESS_KEY_ID = ''
# ACCESS_KEY_SECRET = ''
# OSS_HOST = ''   #下载
# UPLOAD_OSS_HOST = ''   #上传
# CALLBACK_URL1 = '/file_data/file_upload'
# UPLOAD_DIR =''
# EXPIRE_TIME = 20000
# ENDPOINT = ""
# BUCKET = ""
AUTH_OBJ = oss2.Auth(ACCESS_KEY_ID, ACCESS_KEY_SECRET)
DOWN_BUCKECT_OBJ = oss2.Bucket(AUTH_OBJ, OSS_HOST, BUCKET)
UPLOAD_BUCKECT_OBJ = oss2.Bucket(AUTH_OBJ, UPLOAD_OSS_HOST, BUCKET)

2.上传定义回调参数

def get_token():
    now = int(time.time())
    expire_syncpoint = now + config.EXPIRE_TIME
    expire = get_iso_8601(expire_syncpoint)
    policy_dict = {}
    policy_dict['expiration'] = expire
    condition_array = []
    array_item = []
    array_item.append('starts-with')
    array_item.append('$key')
    array_item.append(config.UPLOAD_DIR)
    condition_array.append(array_item)
    policy_dict['conditions'] = condition_array
    policy = json.dumps(policy_dict).strip()
    policy_encode = base64.b64encode(policy.encode())
    h = hmac.new(config.ACCESS_KEY_SECRET.encode(), policy_encode, sha)
    sign_result = base64.encodebytes(h.digest()).strip()
    callback_dict = {}
    callback_dict['callbackUrl'] = config.CALLBACK_URL1
    callback_dict['callbackBody'] = 'file_name=${object}&size=${size}&ffile_id=${x:ffile_id}&user_id=${x:user_id}&raw_file_name=${x:raw_file_name}'
    callback_dict['callbackBodyType'] = 'application/x-www-form-urlencoded'
    callback_param = json.dumps(callback_dict).strip()
    base64_callback_body = base64.b64encode(callback_param.encode())
    token_dict = {}
    token_dict['accessid'] = config.ACCESS_KEY_ID
    token_dict['host'] = config.UPLOAD_OSS_HOST
    token_dict['policy'] = policy_encode.decode()
    token_dict['signature'] = sign_result.decode()
    token_dict['expire'] = expire_syncpoint
    token_dict['dir'] = config.UPLOAD_DIR
    token_dict['callback'] = base64_callback_body.decode()
    result = token_dict
    return result

3.上传视图中编写

class File_authentication(APIView):

    def post(self, request, *args, **kwargs):
        data_body = request.data
        file_name_list = data_body.get("file_name_list")
        ffile_id = data_body.get("ffile_id")
        user_id = data_body.get("user_id")
        timestamp = str(time.time())[:-8]
        file_name = f"{str(uuid.uuid4())[:13]}_{timestamp}"
        oss_token = ts.get_token()
        result = json.dumps(oss_token)
        headers = {"Access-Control-Allow-Methods": "POST", "Access-Control-Allow-Origin": "*",
                   "Content-Type": "text/html; charset=UTF-8"}
        result = ts.result_data(status.HTTP_200_OK,
                                {"oss_token": json.loads(result.encode("utf-8")), "params": {"file_name": file_name}},
                                "授权成功")
        return Response(result, headers=headers)

4.上传定义回调视图

class Oss_file_upload(APIView):

    def post(self, request, *args, **kwargs):
        user_id = request.POST.get("user_id")
        ffile_id = request.POST.get("ffile_id")
        raw_file_name = request.POST.get("raw_file_name")
        file_name, file_type = ts.output_filetype(raw_file_name)
        result = ts.result_data(status.HTTP_200_OK, None, "上传成功")
        return Response(result)

5.定义下载视图函数

class File_download(APIView):

    def get(self, request):
        user_id = request.GET.get("user_id")
        file_id = request.GET.get("file_id")
        file_version = request.GET.get("file_version")
        file_version_obj = models.xxx.objects.filter(file_info_id=file_id, file_version=file_version).first()
        if not file_version_obj:
            result = ts.result_data(status.HTTP_402_PAYMENT_REQUIRED, None, "ok")
            return Response(result)
        object_name = file_version_obj.xxx
        if not object_name:
            result = ts.result_data(status.HTTP_402_PAYMENT_REQUIRED, None, "ok")
            return Response(result)
        url = config.DOWN_BUCKECT_OBJ.sign_url('GET', object_name, 210, slash_safe=True)
        result = ts.result_data(status.HTTP_200_OK, {"download_auth_url": url}, "ok")
        return Response(result)

6.url编写

from django.urls import path
from bffile_data.views import *
from rest_framework.routers import SimpleRouter

routers = SimpleRouter()
urlpatterns = [
    path(r'file_upload', Oss_file_upload.as_view()),
    path(r'file_authent', File_authentication.as_view()),
    path(r'file_download', File_download.as_view()),
]
urlpatterns += routers.urls```

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值