Cargue un solo archivo en OSS mediante el método de carga simple del Python SDK V2.
Notas de uso
El código de ejemplo de este tema usa el ID de región China (Hangzhou) cn-hangzhou y un endpoint público. Para acceder a OSS desde otros servicios de Alibaba Cloud en la misma región, use un endpoint interno. Para ver la correspondencia entre regiones y endpoints, consulte OSS regions and endpoints.
Permisos
De forma predeterminada, una cuenta de Alibaba Cloud tiene permisos completos. Los usuarios o roles de RAM bajo una cuenta de Alibaba Cloud carecen de permisos por defecto. La cuenta de Alibaba Cloud o el administrador de la cuenta debe otorgar los permisos de operación mediante RAM policies o Bucket Policy.
|
API |
Action |
Descripción |
|
PutObject |
|
Carga un objeto. |
|
|
Obligatorio si especifica etiquetas de objeto mediante el encabezado |
|
|
|
Obligatorio si el encabezado |
|
|
|
Definición del método
put_object(request: PutObjectRequest, **kwargs) → PutObjectResult
Parámetros de solicitud
|
Parámetro |
Tipo |
Descripción |
|
request |
PutObjectRequest |
Los parámetros de la solicitud, que incluyen la ACL del objeto, la opción para prohibir la sobrescritura (ForbidOverwrite) y los metadatos personalizados (Metadata). PutObjectRequest |
Valores de retorno
|
Tipo |
Descripción |
|
PutObjectResult |
El valor de retorno. PutObjectResult |
Para ver la definición completa del método, consulte put_object.
Carga de un archivo local
Si ya existe un objeto con el mismo nombre en el bucket y usted cuenta con los permisos necesarios, el nuevo objeto sobrescribirá al existente.
Parámetros comunes:
|
Parámetro |
Descripción |
|
bucket_name |
El nombre del bucket. Convenciones de nomenclatura para buckets:
|
|
object_name |
La ruta completa del objeto, sin incluir el nombre del bucket. Convenciones de nomenclatura para objetos:
|
Use put_object_from_file para cargar un archivo local en el bucket de destino.
import argparse
import alibabacloud_oss_v2 as oss
# Create a command-line argument parser.
parser = argparse.ArgumentParser(description="put object from file sample")
# Add the --region command-line argument, which specifies the region where the bucket is located. This argument is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Add the --bucket command-line argument, which specifies the name of the bucket. This argument is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# Add the --endpoint command-line argument, which specifies the domain name that other services can use to access OSS. This argument is optional.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
# Add the --key command-line argument, which specifies the name of the object. This argument is required.
parser.add_argument('--key', help='The name of the object.', required=True)
# Add the --file_path command-line argument, which specifies the path of the local file to upload. This argument is required.
parser.add_argument('--file_path', help='The path of Upload file.', required=True)
def main():
# Parse the command-line arguments.
args = parser.parse_args()
# Load credentials from environment variables for identity verification.
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# Load the default configurations of the software development kit (SDK) and set the credentials provider.
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
# Set the region in the configuration.
cfg.region = args.region
# If the endpoint argument is provided, set the endpoint in the configuration.
if args.endpoint is not None:
cfg.endpoint = args.endpoint
# Create an OSS client using the specified configurations.
client = oss.Client(cfg)
# Execute the request to upload the object directly from a file.
# Specify the bucket name, object name, and local file path.
result = client.put_object_from_file(
oss.PutObjectRequest(
bucket=args.bucket, # The name of the bucket.
key=args.key # The name of the object.
),
args.file_path # The path of the local file.
)
# Print the result information of the request, including the status code, request ID, Content-MD5, ETag, 64-bit cyclic redundancy check (CRC64) hash, version ID, and server response time.
print(f'status code: {result.status_code},'
f' request id: {result.request_id},'
f' content md5: {result.content_md5},'
f' etag: {result.etag},'
f' hash crc64: {result.hash_crc64},'
f' version id: {result.version_id},'
f' server time: {result.headers.get("x-oss-server-time")},'
)
# The script entry point. The main function is called when the file is run directly.
if __name__ == "__main__":
main()
Cuando use put_object para cargar un archivo local, abra el archivo en modo 'rb'. Esto garantiza que se cargue el flujo de bytes original en lugar del contenido de texto, lo cual evita fallos de CRC.
import argparse
import alibabacloud_oss_v2 as oss
# Create a command-line argument parser.
parser = argparse.ArgumentParser(description="put object from file sample")
# Add the --region command-line argument, which specifies the region where the bucket is located. This argument is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Add the --bucket command-line argument, which specifies the name of the bucket. This argument is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# Add the --endpoint command-line argument, which specifies the domain name that other services can use to access OSS. This argument is optional.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
# Add the --key command-line argument, which specifies the name of the object. This argument is required.
parser.add_argument('--key', help='The name of the object.', required=True)
def main():
# Parse the command-line arguments.
args = parser.parse_args()
# Load credentials from environment variables for identity verification.
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# Load the default configurations of the SDK and set the credentials provider.
cfg = oss.config.load_default()
cfg.credentials_provider = credentials_provider
# Set the region in the configuration.
cfg.region = args.region
# If the endpoint argument is provided, set the endpoint in the configuration.
if args.endpoint is not None:
cfg.endpoint = args.endpoint
# Create an OSS client using the specified configurations.
client = oss.Client(cfg)
# Execute the request to upload the object directly from a local file.
# Specify the bucket name, object name, and local file path.
with open('your-test-file.md', 'rb') as f:
result = client.put_object(
oss.PutObjectRequest(
bucket=args.bucket, # The name of the bucket.
key=args.key, # The name of the object.
body=f.read() # Read the file content.
)
)
# Print the result information of the request, including the status code, request ID, Content-MD5, ETag, CRC64 hash, version ID, and server response time.
print(f'status code: {result.status_code},'
f' request id: {result.request_id},'
f' content md5: {result.content_md5},'
f' etag: {result.etag},'
f' hash crc64: {result.hash_crc64},'
f' version id: {result.version_id},'
f' server time: {result.headers.get("x-oss-server-time")},'
)
# The script entry point. The main function is called when the file is run directly.
if __name__ == "__main__":
main()
Ejemplos
Carga de una cadena
Carga de una matriz de bytes
Carga de un flujo de red
Carga con callback
Carga con barra de progreso
Referencias
Para ver el código de ejemplo completo, consulte put_object.py.