from tos.models2 import CloudFunctionConfiguration, Filter, FilterKey, FilterRule
# Retrieve AKSK information from environment variables.
ak = os.getenv('TOS_ACCESS_KEY')
sk = os.getenv('TOS_SECRET_KEY')
# Fill in "your endpoint" and "your region" with the corresponding Endpoint of the region where your Bucket is located. Taking the example of North China 2 (Beijing), fill in "your endpoint" with tos-cn-beijing.volces.com and "your region" with cn-beijing.
endpoint = "your endpoint"
bucket_name = "bucket-test"
cloudFunction = 'your cloud function'
# Create a TosClientV2 object to perform operations on buckets and objects.
client = tos.TosClientV2(ak, sk, endpoint, region)
config = CloudFunctionConfiguration(
events=['tos:ObjectCreated:Put', 'tos:ObjectCreated:Post'],
# Set up the prefix information for the matching object.
FilterRule(name='prefix', value='your prefix'),
# Set up the suffix information to be matched with the target objects.
FilterRule(name='suffix', value='your suffix'),
cloud_function=cloudFunction
out = client.put_bucket_notification(bucket_name, [config])
except tos.exceptions.TosClientError as e:
# Operation failed, catch client error, usually caused by invalid request parameters or network issues
print('fail with client error, message:{}, cause: {}'.format(e.message, e.cause))
except tos.exceptions.TosServerError as e:
# Operation failed, catch server error, detailed error information can be obtained from the response
print('fail with server error, code: {}'.format(e.code))
# request id can be used to locate specific issues, it is strongly recommended to save it in the log.
print('error with request id: {}'.format(e.request_id))
print('error with message: {}'.format(e.message))
print('error with http code: {}'.format(e.status_code))
print('error with ec: {}'.format(e.ec))
print('error with request url: {}'.format(e.request_url))
print('fail with unknown error: {}'.format(e))