|
| 1 | +import argparse |
| 2 | +import base64 |
| 3 | +import hashlib |
| 4 | +import hmac |
| 5 | +import json |
| 6 | +import random |
| 7 | +import requests |
| 8 | +from datetime import datetime, timedelta |
| 9 | +import alibabacloud_oss_v2 as oss |
| 10 | + |
| 11 | +parser = argparse.ArgumentParser(description="post object sample") |
| 12 | +parser.add_argument('--region', help='The region in which the bucket is located.', required=True) |
| 13 | +parser.add_argument('--bucket', help='The name of the bucket.', required=True) |
| 14 | +parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS') |
| 15 | +parser.add_argument('--key', help='The name of the object.', required=True) |
| 16 | + |
| 17 | + |
| 18 | +def main(): |
| 19 | + content = "hi oss" |
| 20 | + product = "oss" |
| 21 | + |
| 22 | + args = parser.parse_args() |
| 23 | + region = args.region |
| 24 | + bucket_name = args.bucket |
| 25 | + object_name = args.key |
| 26 | + |
| 27 | + # Loading credentials values from the environment variables |
| 28 | + credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider() |
| 29 | + credential = credentials_provider.get_credentials() |
| 30 | + access_key_id = credential.access_key_id |
| 31 | + access_key_secret = credential.access_key_secret |
| 32 | + |
| 33 | + utc_time = datetime.utcnow() |
| 34 | + date = utc_time.strftime("%Y%m%d") |
| 35 | + expiration = utc_time + timedelta(hours=1) |
| 36 | + policy_map = { |
| 37 | + "expiration": expiration.strftime("%Y-%m-%dT%H:%M:%S.000Z"), |
| 38 | + "conditions": [ |
| 39 | + {"bucket": bucket_name}, |
| 40 | + {"x-oss-signature-version": "OSS4-HMAC-SHA256"}, |
| 41 | + {"x-oss-credential": f"{access_key_id}/{date}/{region}/{product}/aliyun_v4_request"}, |
| 42 | + {"x-oss-date": utc_time.strftime("%Y%m%dT%H%M%SZ")}, |
| 43 | + ["content-length-range", 1, 1024] |
| 44 | + ] |
| 45 | + } |
| 46 | + policy = json.dumps(policy_map) |
| 47 | + string_to_sign = base64.b64encode(policy.encode()).decode() |
| 48 | + |
| 49 | + def build_post_body(field_dict, boundary): |
| 50 | + post_body = '' |
| 51 | + |
| 52 | + # Encoding Form Fields |
| 53 | + for k, v in field_dict.items(): |
| 54 | + if k != 'content' and k != 'content-type': |
| 55 | + post_body += '''--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}\r\n'''.format(boundary, k, v) |
| 56 | + |
| 57 | + # The content of the uploaded file must be the last form field |
| 58 | + post_body += '''--{0}\r\nContent-Disposition: form-data; name=\"file\"\r\n\r\n{1}'''.format( |
| 59 | + boundary, field_dict['content']) |
| 60 | + |
| 61 | + # Add a form field terminator |
| 62 | + post_body += '\r\n--{0}--\r\n'.format(boundary) |
| 63 | + |
| 64 | + return post_body.encode('utf-8') |
| 65 | + |
| 66 | + signing_key = "aliyun_v4" + access_key_secret |
| 67 | + h1 = hmac.new(signing_key.encode(), date.encode(), hashlib.sha256) |
| 68 | + h1_key = h1.digest() |
| 69 | + h2 = hmac.new(h1_key, region.encode(), hashlib.sha256) |
| 70 | + h2_key = h2.digest() |
| 71 | + h3 = hmac.new(h2_key, product.encode(), hashlib.sha256) |
| 72 | + h3_key = h3.digest() |
| 73 | + h4 = hmac.new(h3_key, "aliyun_v4_request".encode(), hashlib.sha256) |
| 74 | + h4_key = h4.digest() |
| 75 | + |
| 76 | + h = hmac.new(h4_key, string_to_sign.encode(), hashlib.sha256) |
| 77 | + signature = h.hexdigest() |
| 78 | + |
| 79 | + field_dict = {} |
| 80 | + field_dict['key'] = object_name |
| 81 | + field_dict['policy'] = string_to_sign |
| 82 | + field_dict['x-oss-signature-version'] = "OSS4-HMAC-SHA256" |
| 83 | + field_dict['x-oss-credential'] = f"{access_key_id}/{date}/{region}/{product}/aliyun_v4_request" |
| 84 | + field_dict['x-oss-date'] = f"{utc_time.strftime('%Y%m%dT%H%M%SZ')}" |
| 85 | + field_dict['x-oss-signature'] = signature |
| 86 | + field_dict['content'] = content |
| 87 | + |
| 88 | + # The boundary string of the form field is usually a random string |
| 89 | + boundary = ''.join(random.choice('0123456789') for _ in range(11)) |
| 90 | + # Send POST request |
| 91 | + body = build_post_body(field_dict, boundary) |
| 92 | + |
| 93 | + url = f"http://{bucket_name}.oss-{region}.aliyuncs.com" |
| 94 | + headers = { |
| 95 | + "Content-Type": f"multipart/form-data; boundary={boundary}", |
| 96 | + } |
| 97 | + response = requests.post(url, data=body, headers=headers) |
| 98 | + |
| 99 | + if response.status_code // 100 != 2: |
| 100 | + print(f"Post Object Fail, status code: {response.status_code}, reason: {response.reason}") |
| 101 | + else: |
| 102 | + print(f"post object done, status code: {response.status_code}, request id: {response.headers.get('X-Oss-Request-Id')}") |
| 103 | + |
| 104 | + |
| 105 | +if __name__ == "__main__": |
| 106 | + main() |
0 commit comments