Téléchargez un fichier unique vers OSS en utilisant la méthode de téléchargement simple du SDK Python V2.
Remarques sur l'utilisation
L'exemple de code présenté dans cette rubrique utilise l'ID de région Chine (Hangzhou) cn-hangzhou et un endpoint public. Pour accéder à OSS depuis d'autres services Alibaba Cloud situés dans la même région, utilisez un endpoint interne. Pour connaître les correspondances entre les régions et les endpoints, consultez Régions et endpoints OSS.
Autorisations
Par défaut, un compte Alibaba Cloud dispose de toutes les autorisations. Les utilisateurs RAM ou les rôles RAM associés à un compte Alibaba Cloud ne disposent d'aucune autorisation par défaut. Le compte Alibaba Cloud ou l'administrateur du compte doit accorder les autorisations d'opération via des politiques RAM ou une Bucket Policy.
|
API |
Action |
Description |
|
PutObject |
|
Télécharge un objet. |
|
|
Requis si vous spécifiez des tags d'objet à l'aide de l'en-tête |
|
|
|
Requis si l'en-tête |
|
|
|
Définition de la méthode
put_object(request: PutObjectRequest, **kwargs) → PutObjectResult
Paramètres de la requête
|
Paramètre |
Type |
Description |
|
request |
PutObjectRequest |
Les paramètres de la requête, incluant l'ACL de l'objet, l'interdiction d'écrasement (ForbidOverwrite), et les métadonnées personnalisées (Metadata). PutObjectRequest |
Valeurs de retour
|
Type |
Description |
|
PutObjectResult |
La valeur de retour. PutObjectResult |
Pour la définition complète de la méthode, consultez put_object.
Télécharger un fichier local
Si un objet portant le même nom existe déjà dans le bucket et que vous disposez des autorisations requises, le nouvel objet écrase l'existant.
Paramètres courants :
|
Paramètre |
Description |
|
bucket_name |
Le nom du bucket. Conventions de nommage des buckets :
|
|
object_name |
Le chemin complet de l'objet, hors nom du bucket. Conventions de nommage des objets :
|
Utilisez put_object_from_file pour télécharger un fichier local vers le bucket de destination.
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()
Lorsque vous utilisez put_object pour télécharger un fichier local, ouvrez le fichier en mode 'rb' . Cela garantit que le flux d'octets original est téléchargé plutôt que le contenu textuel, évitant ainsi les échecs de vérification 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()
Exemples
Télécharger une chaîne
Télécharger un tableau d'octets
Télécharger un flux réseau
Télécharger avec callback
Télécharger avec barre de progression
Références
Pour obtenir l'exemple de code complet, consultez put_object.py.