Skip to content

Commit 391ed97

Browse files
committed
上传文件时,可以添加校验参数强制校验key和hash
1 parent a5022fe commit 391ed97

File tree

2 files changed

+20
-3
lines changed

2 files changed

+20
-3
lines changed

qiniu/exceptions.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: UTF-8 -*-
3+
# Xiang Wang @ 2019-09-17 15:25:42
4+
5+
6+
class QiniuException(Exception):
7+
pass
8+
9+
10+
class UploadException(QiniuException):
11+
pass

qiniu/services/storage/uploader.py

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,8 @@
44
import time
55

66
from qiniu import config
7-
from qiniu.utils import urlsafe_base64_encode, crc32, file_crc32, _file_iter, rfc_from_timestamp
7+
from qiniu.exceptions import UploadException
8+
from qiniu.utils import urlsafe_base64_encode, crc32, file_crc32, _file_iter, rfc_from_timestamp, etag
89
from qiniu import http
910
from .upload_progress_recorder import UploadProgressRecorder
1011

@@ -44,7 +45,8 @@ def put_data(
4445

4546
def put_file(up_token, key, file_path, params=None,
4647
mime_type='application/octet-stream', check_crc=False,
47-
progress_handler=None, upload_progress_recorder=None, keep_last_modified=False):
48+
progress_handler=None, upload_progress_recorder=None,
49+
keep_last_modified=False, raise_exception=False):
4850
"""上传文件到七牛
4951
5052
Args:
@@ -53,9 +55,10 @@ def put_file(up_token, key, file_path, params=None,
5355
file_path: 上传文件的路径
5456
params: 自定义变量,规格参考 http://developer.qiniu.com/docs/v6/api/overview/up/response/vars.html#xvar
5557
mime_type: 上传数据的mimeType
56-
check_crc: 是否校验crc32
58+
check_crc: 是否校验crc32, 已弃用
5759
progress_handler: 上传进度
5860
upload_progress_recorder: 记录上传进度,用于断点续传
61+
raise_exception: 上传后自动校验key和hash, 如果不一致就报错
5962
6063
Returns:
6164
一个dict变量,类似 {"hash": "<Hash string>", "key": "<Key string>"}
@@ -77,6 +80,9 @@ def put_file(up_token, key, file_path, params=None,
7780
ret, info = _form_put(up_token, key, input_stream, params, mime_type,
7881
crc, progress_handler, file_name,
7982
modify_time=modify_time, keep_last_modified=keep_last_modified)
83+
if raise_exception is True:
84+
if (ret["key"] != key) or (ret["hash"] != etag(file_path)):
85+
raise UploadException("数据校验不正确")
8086
return ret, info
8187

8288

0 commit comments

Comments
 (0)