PUT /exampleobject HTTP/1.1Host: examplebucket-1250000000.cos.ap-beijing.myqcloud.comDate: Fri, 21 Jun 2019 09:24:28 GMTContent-Type: image/jpegContent-Length: 13Content-MD5: ti4QvKtVqIJAvZxDbP/c+Q==Authorization: q-sign-algorithm=sha1&q-ak=AKID8A0fBVtYFrNm02oY1g1JQQF0c3JO****&q-sign-time=1561109068;1561116268&q-key-time=1561109068;1561116268&q-header-list=content-length;content-md5;content-type;date;host&q-url-param-list=&q-signature=998bfc8836fc205d09e455c14e3d7e623bd2****x-cos-meta-md5: b62e10bcab55a88240bd9c436cffdcf9Connection: close[Object Content]
POST /exampleobject?uploads HTTP/1.1Host: examplebucket-1250000000.cos.ap-beijing.myqcloud.comDate: Fri, 21 Jun 2019 09:45:12 GMTAuthorization: q-sign-algorithm=sha1&q-ak=AKID8A0fBVtYFrNm02oY1g1JQQF0c3JO****&q-sign-time=1561109068;1561116268&q-key-time=1561109068;1561116268&q-header-list=content-length;content-md5;content-type;date;host&q-url-param-list=&q-signature=998bfc8836fc205d09e455c14e3d7e623bd2****x-cos-meta-md5: b62e10bcab55a88240bd9c436cffdcf9
HTTP/1.1 200 OKContent-Type: application/octet-streamContent-Length: 13Connection: closeAccept-Ranges: bytesCache-Control: max-age=86400Content-Disposition: attachment; filename=example.jpgDate: Thu, 04 Jul 2019 11:33:00 GMTETag: "b62e10bcab55a88240bd9c436cffdcf9"Last-Modified: Thu, 04 Jul 2019 11:32:55 GMTServer: tencent-cosx-cos-request-id: NWQxZGUzZWNfNjI4NWQ2NF9lMWYyXzk1NjFj****x-cos-meta-md5: b62e10bcab55a88240bd9c436cffdcf9[Object Content]
# -*- coding=utf-8from qcloud_cos import CosConfigfrom qcloud_cos import CosS3Clientfrom qcloud_cos import CosServiceErrorfrom qcloud_cos import CosClientErrorimport sysimport osimport loggingimport hashliblogging.basicConfig(level=logging.INFO, stream=sys.stdout)# Configure user attributes, including SecretId, SecretKey, and region# APPID has been removed from the configuration. Please specify it using the `Bucket` parameter in the format of `BucketName-APPID`.secret_id = os.environ['COS_SECRET_ID'] # User `SecretId`. We recommend you use a sub-account key and follow the principle of least privilege to reduce risks. For information about how to obtain a sub-account key, visit https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1.secret_key = os.environ['COS_SECRET_KEY'] # User `SecretKey`. We recommend you use a sub-account key and follow the principle of least privilege to reduce risks. For information about how to obtain a sub-account key, visit https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1.region = 'ap-beijing' # Replace with your own region (which is Beijing in this sample)token = None # Temporary key token. For more information on how to generate and use a temporary key, visit https://www.tencentcloud.com/document/product/436/14048?from_cn_redirect=1.config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key, Token=token) # Get the configured objectclient = CosS3Client(config)
object_body = 'hello cos'# Get the MD5 checksum of the objectmd5 = hashlib.md5()md5.update(object_body)md5_str = md5.hexdigest()
# Upload the object using simple upload and enable MD5 verificationresponse = client.put_object(Bucket='examplebucket-1250000000', # Replace with your own bucket name. Here, examplebucket is a sample bucket, and 1250000000 is a sample APPIDBody='hello cos', # Content of the uploaded objectKey='example-object-1', # Replace with the key value of your uploaded objectEnableMD5=True, # Enable MD5 verification for uploadMetadata={ # Set the custom parameter and save the MD5 checksum of the object to the COS server as the parameter value'x-cos-meta-md5' : md5_str})print 'ETag: ' + response['ETag'] # Etag value of the object
# Download the objectresponse = client.get_object(Bucket='examplebucket-1250000000', # Replace with your own bucket name. Here, examplebucket is a sample bucket, and 1250000000 is a sample APPIDKey='example-object-1' # Key value of the download object)fp = response['Body'].get_raw_stream()download_object = fp.read() # Get the object contentprint "get object body: " + download_objectprint 'ETag: ' + response['ETag']print 'x-cos-meta-md5: ' + response['x-cos-meta-md5'] # Get the custom parameter "x-cos-meta-md5"
# Calculate the MD5 checksum of the downloaded objectmd5 = hashlib.md5()md5.update(download_object)md5_str = md5.hexdigest()print 'download object md5: ' + md5_str# Verify object consistency by checking the MD5 checksum of the downloaded object against that of the uploaded objectif md5_str == response['x-cos-meta-md5']:print 'MD5 check OK'else:print 'MD5 check FAIL'
OBJECT_PART_SIZE = 1024 * 1024 # Size of each simulated partOBJECT_TOTAL_SIZE = OBJECT_PART_SIZE * 1 + 123 # Total size of the objectobject_body = '1' * OBJECT_TOTAL_SIZE # Object content# Calculate the MD5 checksum of the entire object contentmd5 = hashlib.md5()md5.update(object_body)md5_str = md5.hexdigest()
# Initialize the multipart uploadresponse = client.create_multipart_upload(Bucket='examplebucket-1250000000', #Replace with your own bucket name and APPIDKey='exampleobject-2', # Replace with the key value of the uploaded objectStorageClass='STANDARD', # Storage class of the objectMetadata={'x-cos-meta-md5' : md5_str # Set the custom parameter to the MD5 checksum})#Get the UploadId of the multipart uploadupload_id = response['UploadId']
#Upload an object in parts where the size of each part is OBJECT_PART_SIZE except the last part which may be smallerpart_list = list()position = 0left_size = OBJECT_TOTAL_SIZEpart_number = 0while left_size > 0:part_number += 1if left_size >= OBJECT_PART_SIZE:body = object_body[position:position+OBJECT_PART_SIZE]else:body = object_body[position:]position += OBJECT_PART_SIZEleft_size -= OBJECT_PART_SIZE# Upload partsresponse = client.upload_part(Bucket='examplebucket-1250000000', #Replace with your own bucket name and APPIDKey='exampleobject-2', # Key value of the objectBody=body,PartNumber=part_number,UploadId=upload_id,EnableMD5=True # Enable part verification and the COS server will perform MD5 verification on each part)etag = response['ETag'] # ETag represents the MD5 checksum of each partpart_list.append({'ETag' : etag, 'PartNumber' : part_number})print etag + ', ' + str(part_number)
#Complete the multipart uploadresponse = client.complete_multipart_upload(Bucket='examplebucket-1250000000', # Replace with your own bucket name. Here, examplebucket is a sample bucket, and 1250000000 is a sample APPIDKey='exampleobject-2', # Key value of the objectUploadId=upload_id,MultipartUpload={ # Requires one-to-one correspondence between ETag and PartNumber for each part'Part' : part_list},)# ETag represents the unique tag value of the merged object, which is not the MD5 checksum of the object content and can only be used to verify the object's uniquenessprint "ETag: " + response['ETag']print "Location: " + response['Location'] #URLprint "Key: " + response['Key']
# Download the objectresponse = client.get_object(Bucket='examplebucket-1250000000', #Replace with your own bucket name and APPIDKey='exampleobject-2' # Key value of the object)print 'ETag: ' + response['ETag'] # The ETag of the object is not the MD5 checksum of the object contentprint 'x-cos-meta-md5: ' + response['x-cos-meta-md5'] # Get the custom parameter "x-cos-meta-md5"
# Calculate the MD5 checksum of the downloaded objectfp = response['Body'].get_raw_stream()DEFAULT_CHUNK_SIZE = 1024*1024md5 = hashlib.md5()chunk = fp.read(DEFAULT_CHUNK_SIZE)while chunk:md5.update(chunk)chunk = fp.read(DEFAULT_CHUNK_SIZE)md5_str = md5.hexdigest()print 'download object md5: ' + md5_str# Verify object consistency by checking the MD5 checksum of the downloaded object against that of the uploaded objectif md5_str == response['x-cos-meta-md5']:print 'MD5 check OK'else:print 'MD5 check FAIL'
Feedback