8000 minio-py/minio/api.py at master · Moonjong-Shin/minio-py · GitHub
[go: up one dir, main page]

Skip to content

Latest commit

 

History

History
2832 lines (2517 loc) · 101 KB

api.py

File metadata and controls

2832 lines (2517 loc) · 101 KB
# -*- coding: utf-8 -*-
# MinIO Python Library for Amazon S3 Compatible Cloud Storage, (C)
# 2015, 2016, 2017 MinIO, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# pylint: disable=too-many-lines,disable=too-many-branches,too-many-statements
# pylint: disable=too-many-arguments
"""
Simple Storage Service (aka S3) client to perform bucket and object operations.
"""
from __future__ import absolute_import
import itertools
import os
import platform
from datetime import timedelta
from threading import Thread
from urllib.parse import urlunsplit
from xml.etree import ElementTree as ET
import certifi
import urllib3
from urllib3._collections import HTTPHeaderDict
from . import __title__, __version__, time
from .commonconfig import COPY, REPLACE, ComposeSource, CopySource, Tags
from .credentials import StaticProvider
from .datatypes import (CompleteMultipartUploadResult, EventIterable,
ListAllMyBucketsResult, ListMultipartUploadsResult,
ListPartsResult, Object, Part, PostPolicy,
parse_copy_object, parse_list_objects)
from .deleteobjects import DeleteError, DeleteRequest, DeleteResult
from .error import InvalidResponseError, S3Error, ServerError
from .helpers import (MAX_MULTIPART_COUNT, MAX_MULTIPART_OBJECT_SIZE,
MAX_PART_SIZE, MIN_PART_SIZE, BaseURL, ObjectWriteResult,
ThreadPool, check_bucket_name, check_non_empty_string,
check_sse, check_ssec, genheaders, get_part_info,
headers_to_strings, is_valid_policy_type, makedirs,
md5sum_hash, read_part_data, sha256_hash)
from .legalhold import LegalHold
from .lifecycleconfig import LifecycleConfig
from .notificationconfig import NotificationConfig
from .objectlockconfig import ObjectLockConfig
from .replicationconfig import ReplicationConfig
from .retention import Retention
from .select import SelectObjectReader, SelectRequest
from .signer import presign_v4, sign_v4_s3
from .sse import SseCustomerKey
from .sseconfig import SSEConfig
from .tagging import Tagging
from .versioningconfig import VersioningConfig
from .xml import Element, SubElement, findtext, getbytes, marshal, unmarshal
_DEFAULT_USER_AGENT = (
f"MinIO ({platform.system()}; {platform.machine()}) "
f"{__title__}/{__version__}"
)
class Minio: # pylint: disable=too-many-public-methods
"""
Simple Storage Service (aka S3) client to perform bucket and object
operations.
:param endpoint: Hostname of a S3 service.
:param access_key: Access key (aka user ID) of your account in S3 service.
:param secret_key: Secret Key (aka password) of your account in S3 service.
:param session_token: Session token of your account in S3 service.
:param secure: Flag to indicate to use secure (TLS) connection to S3
service or not.
:param region: Region name of buckets in S3 service.
:param http_client: Customized HTTP client.
:param credentials: Credentials provider of your account in S3 service.
:return: :class:`Minio <Minio>` object
Example::
# Create client with anonymous access.
client = Minio("play.min.io")
# Create client with access and secret key.
client = Minio("s3.amazonaws.com", "ACCESS-KEY", "SECRET-KEY")
# Create client with access key and secret key with specific region.
client = Minio(
"play.minio.io:9000",
access_key="Q3AM3UQ867SPQQA43P2F",
secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG",
region="my-region",
)
**NOTE on concurrent usage:** `Minio` object is thread safe when using
the Python `threading` library. Specifically, it is **NOT** safe to share
it between multiple processes, for example when using
`multiprocessing.Pool`. The solution is simply to create a new `Minio`
object in each process, and not share it between processes.
"""
# pylint: disable=too-many-function-args
def __init__(self, endpoint, access_key=None,
secret_key=None,
session_token=None,
secure=True,
region=None,
http_client=None,
credentials=None):
# Validate http client has correct base class.
if http_client and not isinstance(
http_client,
urllib3.poolmanager.PoolManager):
raise ValueError(
"HTTP client should be instance of "
"`urllib3.poolmanager.PoolManager`"
)
self._region_map = {}
self._base_url = BaseURL(
("https://" if secure else "http://") + endpoint,
region,
)
self._user_agent = _DEFAULT_USER_AGENT
self._trace_stream = None
if access_key:
credentials = StaticProvider(access_key, secret_key, session_token)
self._provider = credentials
# Load CA certificates from SSL_CERT_FILE file if set
timeout = timedelta(minutes=5).seconds
self._http = http_client or urllib3.PoolManager(
timeout=urllib3.util.Timeout(connect=timeout, read=timeout),
maxsize=10,
cert_reqs='CERT_REQUIRED',
ca_certs=os.environ.get('SSL_CERT_FILE') or certifi.where(),
retries=urllib3.Retry(
total=5,
backoff_factor=0.2,
status_forcelist=[500, 502, 503, 504]
)
)
def __del__(self):
self._http.clear()
def _handle_redirect_response(
self, method, bucket_name, response, retry=False,
):
"""
Handle redirect response indicates whether retry HEAD request
on failure.
"""
code, message = {
301: ("PermanentRedirect", "Moved Permanently"),
307: ("Redirect", "Temporary redirect"),
400: ("BadRequest", "Bad request"),
}.get(response.status, (None, None))
region = response.getheader("x-amz-bucket-region")
if message and region:
message += "; use region " + region
if (
retry and region and method == "HEAD" and bucket_name and
self._region_map.get(bucket_name)
):
code, message = ("RetryHead", None)
return code, message
def _build_headers(self, host, headers, body, creds):
"""Build headers with given parameters."""
headers = headers or {}
md5sum_added = headers.get("Content-MD5")
headers["Host"] = host
headers["User-Agent"] = self._user_agent
sha256 = None
md5sum = None
if body:
headers["Content-Length"] = str(len(body))
if creds:
if self._base_url.is_https:
sha256 = "UNSIGNED-PAYLOAD"
md5sum = None if md5sum_added else md5sum_hash(body)
else:
sha256 = sha256_hash(body)
else:
md5sum = None if md5sum_added else md5sum_hash(body)
if md5sum:
headers["Content-MD5"] = md5sum
if sha256:
headers["x-amz-content-sha256"] = sha256
if creds and creds.session_token:
headers["X-Amz-Security-Token"] = creds.session_token
date = time.utcnow()
headers["x-amz-date"] = time.to_amz_date(date)
return headers, date
def _url_open( # pylint: disable=too-many-branches
self,
method,
region,
bucket_name=None,
object_name=None,
body=None,
headers=None,
query_params=None,
preload_content=True,
no_body_trace=False,
):
"""Execute HTTP request."""
creds = self._provider.retrieve() if self._provider else None
url = self._base_url.build(
method,
region,
bucket_name=bucket_name,
object_name=object_name,
query_params=query_params,
)
headers, date = self._build_headers(url.netloc, headers, body, creds)
if creds:
headers = sign_v4_s3(
method,
url,
region,
headers,
creds,
headers.get("x-amz-content-sha256"),
date,
)
if self._trace_stream:
self._trace_stream.write("---------START-HTTP---------\n")
query = ("?" + url.query) if url.query else ""
self._trace_stream.write(f"{method} {url.path}{query} HTTP/1.1\n")
self._trace_stream.write(
headers_to_strings(headers, titled_key=True),
)
self._trace_stream.write("\n")
if not no_body_trace and body is not None:
self._trace_stream.write("\n")
self._trace_stream.write(
body.decode() if isinstance(body, bytes) else str(body),
)
self._trace_stream.write("\n")
self._trace_stream.write("\n")
http_headers = HTTPHeaderDict()
for key, value in (headers or {}).items():
if isinstance(value, (list, tuple)):
_ = [http_headers.add(key, val) for val in value]
else:
http_headers.add(key, value)
response = self._http.urlopen(
method,
urlunsplit(url),
body=body,
headers=http_headers,
preload_content=preload_content,
)
if self._trace_stream:
self._trace_stream.write(f"HTTP/1.1 {response.status}\n")
self._trace_stream.write(
headers_to_strings(response.getheaders()),
)
self._trace_stream.write("\n")
if response.status in [200, 204, 206]:
if self._trace_stream:
if preload_content:
self._trace_stream.write("\n")
self._trace_stream.write(response.data.decode())
self._trace_stream.write("\n")
self._trace_stream.write("----------END-HTTP----------\n")
return response
response.read(cache_content=True)
if not preload_content:
response.release_conn()
if self._trace_stream and method != "HEAD" and response.data:
self._trace_stream.write(response.data.decode())
self._trace_stream.write("\n")
if (
method != "HEAD" and
"application/xml" not in response.getheader(
"content-type", "",
).split(";")
):
if self._trace_stream:
self._trace_stream.write("----------END-HTTP----------\n")
if response.status == 304 and not response.data:
raise ServerError(
f"server failed with HTTP status code {response.status}",
response.status,
)
raise InvalidResponseError(
response.status,
response.getheader("content-type"),
response.data.decode() if response.data else None,
)
if not response.data and method != "HEAD":
if self._trace_stream:
self._trace_stream.write("----------END-HTTP----------\n")
raise InvalidResponseError(
response.status,
response.getheader("content-type"),
None,
)
response_error = S3Error.fromxml(response) if response.data else None
if self._trace_stream:
self._trace_stream.write("----------END-HTTP----------\n")
error_map = {
301: lambda: self._handle_redirect_response(
method, bucket_name, response, True,
),
307: lambda: self._handle_redirect_response(
method, bucket_name, response, True,
),
400: lambda: self._handle_redirect_response(
method, bucket_name, response, True,
),
403: lambda: ("AccessDenied", "Access denied"),
404: lambda: (
("NoSuchKey", "Object does not exist")
if object_name
else ("NoSuchBucket", "Bucket does not exist")
if bucket_name
else ("ResourceNotFound", "Request resource not found")
),
405: lambda: (
"MethodNotAllowed",
"The specified method is not allowed against this resource",
),
409: lambda: (
("NoSuchBucket", "Bucket does not exist")
if bucket_name
else ("ResourceConflict", "Request resource conflicts"),
),
501: lambda: (
"MethodNotAllowed",
"The specified method is not allowed against this resource",
),
}
if not response_error:
func = error_map.get(response.status)
code, message = func() if func else (None, None)
if not code:
raise ServerError(
f"server failed with HTTP status code {response.status}",
response.status,
)
response_error = S3Error(
code,
message,
url.path,
response.getheader("x-amz-request-id"),
response.getheader("x-amz-id-2"),
response,
bucket_name=bucket_name,
object_name=object_name,
)
if response_error.code in ["NoSuchBucket", "RetryHead"]:
self._region_map.pop(bucket_name, None)
raise response_error
def _execute(
self,
method,
bucket_name=None,
object_name=None,
body=None,
headers=None,
query_params=None,
preload_content=True,
no_body_trace=False,
):
"""Execute HTTP request."""
region = self._get_region(bucket_name, None)
try:
return self._url_open(
method,
region,
bucket_name=bucket_name,
object_name=object_name,
body=body,
headers=headers,
query_params=query_params,
preload_content=preload_content,
no_body_trace=no_body_trace,
)
except S3Error as exc:
if exc.code != "RetryHead":
raise
# Retry only once on RetryHead error.
try:
return self._url_open(
method,
region,
bucket_name=bucket_name,
object_name=object_name,
body=body,
headers=headers,
query_params=query_params,
preload_content=preload_content,
no_body_trace=no_body_trace,
)
except S3Error as exc:
if exc.code != "RetryHead":
raise
code, message = self._handle_redirect_response(
method, bucket_name, exc.response,
)
raise exc.copy(code, message)
def _get_region(self, bucket_name, region):
"""
Return region of given bucket either from region cache or set in
constructor.
"""
if region:
# Error out if region does not match with region passed via
# constructor.
if self._base_url.region and self._base_url.region != region:
raise ValueError(
f"region must be {self._base_url.region}, "
f"but passed {region}"
)
return region
if self._base_url.region:
return self._base_url.region
if not bucket_name or 10BC8 not self._provider:
return "us-east-1"
region = self._region_map.get(bucket_name)
if region:
return region
# Execute GetBucketLocation REST API to get region of the bucket.
response = self._url_open(
"GET",
"us-east-1",
bucket_name=bucket_name,
query_params={"location": ""},
)
element = ET.fromstring(response.data.decode())
if not element.text:
region = "us-east-1"
elif element.text == "EU":
region = "eu-west-1"
else:
region = element.text
self._region_map[bucket_name] = region
return region
def set_app_info(self, app_name, app_version):
"""
Set your application name and version to user agent header.
:param app_name: Application name.
:param app_version: Application version.
Example::
client.set_app_info('my_app', '1.0.2')
"""
if not (app_name and app_version):
raise ValueError("Application name/version cannot be empty.")
self._user_agent = f"{_DEFAULT_USER_AGENT} {app_name}/{app_version}"
def trace_on(self, stream):
"""
Enable http trace.
:param stream: Stream for writing HTTP call tracing.
"""
if not stream:
raise ValueError('Input stream for trace output is invalid.')
# Save new output stream.
self._trace_stream = stream
def trace_off(self):
"""
Disable HTTP trace.
"""
self._trace_stream = None
def enable_accelerate_endpoint(self):
"""Enables accelerate endpoint for Amazon S3 endpoint."""
self._base_url.accelerate_host_flag = True
def disable_accelerate_endpoint(self):
"""Disables accelerate endpoint for Amazon S3 endpoint."""
self._base_url.accelerate_host_flag = False
def enable_dualstack_endpoint(self):
"""Enables dualstack endpoint for Amazon S3 endpoint."""
self._base_url.dualstack_host_flag = True
def disable_dualstack_endpoint(self):
"""Disables dualstack endpoint for Amazon S3 endpoint."""
self._base_url.dualstack_host_flag = False
def enable_virtual_style_endpoint(self):
"""Enables virtual style endpoint."""
self._base_url.virtual_style_flag = True
def disable_virtual_style_endpoint(self):
"""Disables virtual style endpoint."""
self._base_url.virtual_style_flag = False
def select_object_content(self, bucket_name, object_name, request):
"""
Select content of an object by SQL expression.
:param bucket_name: Name of the bucket.
:param object_name: Object name in the bucket.
:param request: :class:`SelectRequest <SelectRequest>` object.
:return: A reader contains requested records and progress information.
Example::
with client.select_object_content(
"my-bucket",
"my-object.csv",
SelectRequest(
"select * from S3Object",
CSVInputSerialization(),
CSVOutputSerialization(),
request_progress=True,
),
) as result:
for data in result.stream():
print(data.decode())
print(result.stats())
"""
check_bucket_name(bucket_name)
check_non_empty_string(object_name)
if not isinstance(request, SelectRequest):
raise ValueError("request must be SelectRequest type")
body = marshal(request)
response = self._execute(
"POST",
bucket_name=bucket_name,
object_name=object_name,
body=body,
headers={"Content-MD5": md5sum_hash(body)},
query_params={"select": "", "select-type": "2"},
preload_content=False,
)
return SelectObjectReader(response)
def make_bucket(self, bucket_name, location=None, object_lock=False):
"""
Create a bucket with region and object lock.
:param bucket_name: Name of the bucket.
:param location: Region in which the bucket will be created.
:param object_lock: Flag to set object-lock feature.
Examples::
# Create bucket.
client.make_bucket("my-bucket")
# Create bucket on specific region.
client.make_bucket("my-bucket", "us-west-1")
# Create bucket with object-lock feature on specific region.
client.make_bucket("my-bucket", "eu-west-2", object_lock=True)
"""
check_bucket_name(bucket_name, True)
if self._base_url.region:
# Error out if region does not match with region passed via
# constructor.
if location and self._base_url.region != location:
raise ValueError(
f"region must be {self._base_url.region}, "
f"but passed {location}"
)
location = self._base_url.region or location or "us-east-1"
headers = (
{"x-amz-bucket-object-lock-enabled": "true"}
if object_lock else None
)
body = None
if location != "us-east-1":
element = Element("CreateBucketConfiguration")
SubElement(element, "LocationConstraint", location)
body = getbytes(element)
self._url_open(
"PUT",
location,
bucket_name=bucket_name,
body=body,
headers=headers,
)
self._region_map[bucket_name] = location
def list_buckets(self):
"""
List information of all accessible buckets.
:return: List of :class:`Bucket <Bucket>` object.
Example::
buckets = client.list_buckets()
for bucket in buckets:
print(bucket.name, bucket.creation_date)
"""
response = self._execute("GET")
result = unmarshal(ListAllMyBucketsResult, response.data.decode())
return result.buckets
def bucket_exists(self, bucket_name):
"""
Check if a bucket exists.
:param bucket_name: Name of the bucket.
:return: True if the bucket exists.
Example::
if client.bucket_exists("my-bucket"):
print("my-bucket exists")
else:
print("my-bucket does not exist")
"""
check_bucket_name(bucket_name)
try:
self._execute("HEAD", bucket_name)
return True
except S3Error as exc:
if exc.code != "NoSuchBucket":
raise
return False
def remove_bucket(self, bucket_name):
"""
Remove an empty bucket.
:param bucket_name: Name of the bucket.
Example::
client.remove_bucket("my-bucket")
"""
check_bucket_name(bucket_name)
self._execute("DELETE", bucket_name)
self._region_map.pop(bucket_name, None)
def get_bucket_policy(self, bucket_name):
"""
Get bucket policy configuration of a bucket.
:param bucket_name: Name of the bucket.
:return: Bucket policy configuration as JSON string.
Example::
policy = client.get_bucket_policy("my-bucket")
"""
check_bucket_name(bucket_name)
response = self._execute(
"GET", bucket_name, query_params={"policy": ""},
)
return response.data.decode()
def delete_bucket_policy(self, bucket_name):
"""
Delete bucket policy configuration of a bucket.
:param bucket_name: Name of the bucket.
Example::
client.delete_bucket_policy("my-bucket")
"""
check_bucket_name(bucket_name)
self._execute("DELETE", bucket_name, query_params={"policy": ""})
def set_bucket_policy(self, bucket_name, policy):
"""
Set bucket policy configuration to a bucket.
:param bucket_name: Name of the bucket.
:param policy: Bucket policy configuration as JSON string.
Example::
client.set_bucket_policy("my-bucket", policy)
"""
check_bucket_name(bucket_name)
is_valid_policy_type(policy)
self._execute(
"PUT",
bucket_name,
body=policy,
headers={"Content-MD5": md5sum_hash(policy)},
query_params={"policy": ""},
)
def get_bucket_notification(self, bucket_name):
"""
Get notification configuration of a bucket.
:param bucket_name: Name of the bucket.
:return: :class:`NotificationConfig <NotificationConfig>` object.
Example::
config = client.get_bucket_notification("my-bucket")
"""
check_bucket_name(bucket_name)
response = self._execute(
"GET", bucket_name, query_params={"notification": ""},
)
return unmarshal(NotificationConfig, response.data.decode())
def set_bucket_notification(self, bucket_name, config):
"""
Set notification configuration of a bucket.
:param bucket_name: Name of the bucket.
:param config: class:`NotificationConfig <NotificationConfig>` object.
Example::
config = NotificationConfig(
queue_config_list=[
QueueConfig(
"QUEUE-ARN-OF-THIS-BUCKET",
["s3:ObjectCreated:*"],
config_id="1",
prefix_filter_rule=PrefixFilterRule("abc"),
),
],
)
client.set_bucket_notification("my-bucket", config)
"""
check_bucket_name(bucket_name)
if not isinstance(config, NotificationConfig):
raise ValueError("config must be NotificationConfig type")
body = marshal(config)
self._execute(
"PUT",
bucket_name,
body=body,
headers={"Content-MD5": md5sum_hash(body)},
query_params={"notification": ""},
)
def delete_bucket_notification(self, bucket_name):
"""
Delete notification configuration of a bucket. On success, S3 service
stops notification of events previously set of the bucket.
:param bucket_name: Name of the bucket.
Example::
client.delete_bucket_notification("my-bucket")
"""
self.set_bucket_notification(bucket_name, NotificationConfig())
def set_bucket_encryption(self, bucket_name, config):
"""
Set encryption configuration of a bucket.
:param bucket_name: Name of the bucket.
:param config: :class:`SSEConfig <SSEConfig>` object.
Example::
client.set_bucket_encryption(
"my-bucket", SSEConfig(Rule.new_sse_s3_rule()),
)
"""
check_bucket_name(bucket_name)
if not isinstance(config, SSEConfig):
raise ValueError("config must be SSEConfig type")
body = marshal(config)
self._execute(
"PUT",
bucket_name,
body=body,
headers={"Content-MD5": md5sum_hash(body)},
query_params={"encryption": ""},
)
def get_bucket_encryption(self, bucket_name):
"""
Get encryption configuration of a bucket.
:param bucket_name: Name of the bucket.
:return: :class:`SSEConfig <SSEConfig>` object.
Example::
config = client.get_bucket_encryption("my-bucket")
"""
check_bucket_name(bucket_name)
try:
response = self._execute(
"GET",
bucket_name,
query_params={"encryption": ""},
)
return unmarshal(SSEConfig, response.data.decode())
except S3Error as exc:
if exc.code != "ServerSideEncryptionConfigurationNotFoundError":
raise
return None
def delete_bucket_encryption(self, bucket_name):
"""
Delete encryption configuration of a bucket.
:param bucket_name: Name of the bucket.
Example::
client.delete_bucket_encryption("my-bucket")
"""
check_bucket_name(bucket_name)
try:
self._execute(
"DELETE",
bucket_name,
query_params={"encryption": ""},
)
except S3Error as exc:
if exc.code != "ServerSideEncryptionConfigurationNotFoundError":
raise
def listen_bucket_notification(self, bucket_name, prefix='', suffix='',
events=('s3:ObjectCreated:*',
's3:ObjectRemoved:*',
's3:ObjectAccessed:*')):
"""
Listen events of object prefix and suffix of a bucket. Caller should
iterate returned iterator to read new events.
:param bucket_name: Name of the bucket.
:param prefix: Listen events of object starts with prefix.
:param suffix: Listen events of object ends with suffix.
:param events: Events to listen.
:return: Iterator of event records as :dict:.
Example::
with client.listen_bucket_notification(
"my-bucket",
prefix="my-prefix/",
events=["s3:ObjectCreated:*", "s3:ObjectRemoved:*"],
) as events:
for event in events:
print(event)
"""
check_bucket_name(bucket_name)
if self._base_url.is_aws_host:
raise ValueError(
"ListenBucketNotification API is not supported in Amazon S3",
)
return EventIterable(
lambda: self._execute(
"GET",
bucket_name,
query_params={
"prefix": prefix or "",
"suffix": suffix or "",
"events": events,
},
preload_content=False,
),
)
def set_bucket_versioning(self, bucket_name, config):
"""
Set versioning configuration to a bucket.
:param bucket_name: Name of the bucket.
:param config: :class:`VersioningConfig <VersioningConfig>`.
Example::
client.set_bucket_versioning(
"my-bucket", VersioningConfig(ENABLED),
)
"""
check_bucket_name(bucket_name)
if not isinstance(config, VersioningConfig):
raise ValueError("config must be VersioningConfig type")
body = marshal(config)
self._execute(
"PUT",
bucket_name,
body=body,
headers={"Content-MD5": md5sum_hash(body)},
query_params={"versioning": ""},
)
def get_bucket_versioning(self, bucket_name):
"""
Get versioning configuration of a bucket.
:param bucket_name: Name of the bucket.
:return: :class:`VersioningConfig <VersioningConfig>`.
Example::
config = client.get_bucket_versioning("my-bucket")
print(config.status)
"""
check_bucket_name(bucket_name)
response = self._execute(
"GET",
bucket_name,
query_params={"versioning": ""},
)
return unmarshal(VersioningConfig, response.data.decode())
def fput_object(self, bucket_name, object_name, file_path,
content_type="application/octet-stream",
metadata=None, sse=None, progress=None,
part_size=0, num_parallel_uploads=3,
tags=None, retention=None, legal_hold=False):
"""
Uploads data from a file to an object in a bucket.
:param bucket_name: Name of the bucket.
:param object_name: Object name in the bucket.
:param file_path: Name of file to upload.
:param content_type: Content type of the object.
:param metadata: Any additional metadata to be uploaded along
with your PUT request.
:param sse: Server-side encryption.
:param progress: A progress object
:param part_size: Multipart part size
:param num_parallel_uploads: Number of parallel uploads.
:param tags: :class:`Tags` for the object.
:param retention: :class:`Retention` configuration object.
:param legal_hold: Flag to set legal hold for the object.
:return: :class:`ObjectWriteResult` object.
Example::
# Upload data.
result = client.fput_object(
"my-bucket", "my-object", "my-filename",
)
# Upload data with metadata.
result = client.fput_object(
"my-bucket", "my-object", "my-filename",
metadata={"My-Project": "one"},
)
# Upload data with tags, retention and legal-hold.
date = datetime.utcnow().replace(
hour=0, minute=0, second=0, microsecond=0,
) + timedelta(days=30)
tags = Tags(for_object=True)
tags["User"] = "jsmith"
result = client.fput_object(
"my-bucket", "my-object", "my-filename",
tags=tags,
retention=Retention(GOVERNANCE, date),
legal_hold=True,
)
"""
file_size = os.stat(file_path).st_size
with open(file_path, "rb") as file_data:
return self.put_object(
bucket_name, object_name, file_data, file_size,
content_type=content_type,
metadata=metadata, sse=sse, progress=progress,
part_size=part_size, num_parallel_uploads=num_parallel_uploads,
tags=tags, retention=retention, legal_hold=legal_hold,
)
def fget_object(self, bucket_name, object_name, file_path,
request_headers=None, ssec=None, version_id=None,
extra_query_params=None, tmp_file_path=None, progress=None):
"""
0