Se recomienda utilizar OSS Python SDK V2, ya que rediseña la autenticación, los reintentos y el manejo de errores. Además, incorpora paginadores, administradores de transferencia e interfaces similares a archivos.
Inicio rápido
Siga estos pasos para comenzar a trabajar con OSS Python SDK V1.
Preparar el entorno
Instalar Python
OSS Python SDK V1 es compatible con Python 2.6, 2.7, 3.3, 3.4, 3.5, 3.6, 3.7, 3.8 o versiones posteriores.
Al instalar el SDK de Python en un entorno Windows, asegúrese de que la versión de Visual C++ sea 15.0 o posterior.
Instalar python-devel
OSS Python SDK V1 utiliza la biblioteca crcmod para las sumas de comprobación CRC. Su extensión en C requiere el encabezado Python.h de python-devel. Sin este componente, el SDK recurre a una validación CRC en Python puro, lo cual reduce significativamente la velocidad de las cargas y descargas.
Windows
En Windows, la instalación predeterminada de Python incluye los archivos de encabezado necesarios. No es necesario instalar python-devel por separado.
macOS
En macOS, la instalación predeterminada de Python incluye los archivos de encabezado necesarios. No es necesario instalar python-devel por separado.
CentOS
Para instalar python-devel, ejecute el siguiente comando.
yum install python-devel
RHEL
Para instalar python-devel, ejecute el siguiente comando.
yum install python-devel
Fedora
Para instalar python-devel, ejecute el siguiente comando.
yum install python-devel
Debian
Para instalar python-devel, ejecute el siguiente comando.
apt-get install python-dev
Ubuntu
Para instalar python-devel, ejecute el siguiente comando.
apt-get install python-dev
Instalar el SDK
Instale el SDK mediante uno de los siguientes métodos. Utilice la versión más reciente para garantizar la compatibilidad con los ejemplos de código.
Instalar con pip
Instale pip. Este gestor se instala de forma predeterminada con Python 2.7.9 o posterior, así como con Python 3.4 o posterior.
-
Para instalar la versión más reciente del SDK, ejecute el siguiente comando.
pip install oss2
Instalar desde el código fuente
-
Descargue la versión más reciente del SDK desde GitHub, descomprima el paquete y vaya al directorio correspondiente. Asegúrese de que el directorio contenga el archivo setup.py.
Si necesita descargar una versión anterior de OSS Python SDK V1, consulte el historial de versiones.
-
Para instalar el SDK, ejecute el siguiente comando.
python setup.py install
Configurar las credenciales de acceso
Configure las credenciales de acceso con el par de AccessKey de un usuario de RAM.
En la consola de RAM, cree un usuario de RAM con un Permanent AccessKey Pair. Guarde el par de AccessKey y otorgue al usuario el permiso
AliyunOSSFullAccess.-
Utilice el par de AccessKey del usuario de RAM para configurar las variables de entorno.
Linux
-
Ejecute los siguientes comandos en la interfaz de línea de comandos para agregar la configuración de las variables de entorno al archivo
~/.bashrc.echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc -
Ejecute el siguiente comando para aplicar los cambios.
source ~/.bashrc -
Ejecute los siguientes comandos para comprobar que las variables de entorno estén configuradas correctamente.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
macOS
-
Ejecute el siguiente comando en la terminal para consultar el tipo de shell predeterminado.
echo $SHELL -
Realice las siguientes operaciones según el tipo de shell predeterminado.
Zsh
-
Ejecute los siguientes comandos para agregar la configuración de las variables de entorno al archivo
~/.zshrc.echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc -
Ejecute el siguiente comando para aplicar los cambios.
source ~/.zshrc -
Ejecute los siguientes comandos para comprobar que las variables de entorno estén configuradas correctamente.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
Bash
-
Ejecute los siguientes comandos para agregar la configuración de las variables de entorno al archivo
~/.bash_profile.echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bash_profile echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bash_profile -
Ejecute el siguiente comando para aplicar los cambios.
source ~/.bash_profile -
Ejecute los siguientes comandos para comprobar que las variables de entorno estén configuradas correctamente.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
-
Windows
CMD
-
Ejecute los siguientes comandos en CMD.
setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID" setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET" -
Ejecute los siguientes comandos para comprobar que las variables de entorno estén configuradas correctamente.
echo %OSS_ACCESS_KEY_ID% echo %OSS_ACCESS_KEY_SECRET%
PowerShell
-
Ejecute los siguientes comandos en PowerShell.
[Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_ID", "YOUR_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User) [Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", "YOUR_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User) -
Ejecute los siguientes comandos para comprobar que las variables de entorno estén configuradas correctamente.
[Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User) [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
-
Inicializar el cliente
La mayoría de las operaciones con OSS Python SDK V1 utilizan las clases oss2.Service y oss2.Bucket.
La clase
oss2.Servicelista los buckets. No admite el acceso mediante nombres de dominio personalizados.La clase
oss2.Bucketcarga, descarga y elimina archivos, además de configurar diversos ajustes del bucket.
Debido a un cambio de directiva orientado a mejorar el cumplimiento normativo y la seguridad, a partir del 20 de marzo de 2025, los nuevos usuarios de OSS deben use a custom domain name (CNAME) para ejecutar operaciones de API de datos en buckets de OSS ubicados en regiones de China continental. Los endpoints públicos predeterminados están restringidos para estas operaciones. Consulte el anuncio oficial para ver la lista completa de las operaciones afectadas. Si accede a sus datos mediante HTTPS, debe bind a valid SSL Certificate a su dominio personalizado. Esto es obligatorio para acceder a la consola de OSS, ya que esta exige el uso de HTTPS.
Inicializar una instancia de bucket
Antes de ejecutar el código de ejemplo, reemplace los marcadores de posición como<region-id>con su region and endpoint real, por ejemplo,ap-southeast-1.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Sample code for initializing a client with OSS Python SDK V1
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
def main():
# Load access credentials from environment variables. You must set the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# Set the OSS service region.
region = "<region-id>"
# Set the endpoint.
endpoint = "<endpoint>"
# Set the bucket name.
bucket_name = "example-bucket"
# Initialize an OSS Bucket instance.
bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region)
# List files in the bucket.
print("=== List files in the bucket ===")
try:
# Use the list_objects method to list files.
result = bucket.list_objects()
# Iterate through the file list and print only the file names.
for obj in result.object_list:
print(obj.key)
# Print statistics.
print(f"\nTotal files listed: {len(result.object_list)}")
if result.is_truncated:
print("Note: The result is truncated. More files are available.")
except oss2.exceptions.OssError as e:
print(f"OSS error: {e}")
raise
except Exception as e:
print(f"An error occurred: {e}")
raise
if __name__ == "__main__":
# Entry point of the program.
try:
main()
except Exception as e:
print(f"An error occurred during execution: {e}")
raise
Inicializar una instancia de servicio
Antes de ejecutar el código de ejemplo, reemplace los marcadores de posición como<region-id>con su region and endpoint real, por ejemplo,ap-southeast-1.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Sample code for initializing a Service instance with OSS Python SDK V1
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
def main():
# Load access credentials from environment variables. You must set the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# Set the OSS service region.
region = "<region-id>"
# Set the endpoint.
endpoint = "<endpoint>"
# Initialize an OSS Service instance.
service = oss2.Service(auth, endpoint, region=region)
# List all buckets.
print("=== List all buckets ===")
try:
# Use BucketIterator to list buckets.
buckets = [b.name for b in oss2.BucketIterator(service)]
# Iterate through the bucket list and print only the bucket names.
for bucket in buckets:
print(bucket)
# Print statistics.
print(f"\nTotal buckets listed: {len(buckets)}")
except oss2.exceptions.OssError as e:
print(f"OSS error: {e}")
raise
except Exception as e:
print(f"An error occurred: {e}")
raise
if __name__ == "__main__":
# Entry point of the program.
try:
main()
except Exception as e:
print(f"An error occurred during execution: {e}")
raise
Configuración del cliente
Al inicializar el cliente de OSS, puede personalizar parámetros como el endpoint, el tiempo de espera y el tamaño del pool de conexiones.
Usar un nombre de dominio interno
Para acceder a OSS a través de una red interna, utilice el nombre de dominio interno como endpoint.
Reemplace el marcador de posición<region-id>en el código con su region real, por ejemplo,ap-southeast-1.
endpoint = "oss-<region-id>-internal.aliyuncs.com"
# Initialize an OSS bucket instance.
bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region)
Usar un nombre de dominio personalizado
Para utilizar un nombre de dominio personalizado, establezca el endpoint con su dominio y habilite is_cname=True.
Asigne su nombre de dominio personalizado al bucket antes de usarlo. Access OSS by Using Custom Domain Names .
# Set the custom domain name.
endpoint = "http://example.com"
# Initialize an OSS bucket instance.
bucket = oss2.Bucket(auth, endpoint, bucket_name, is_cname=True, region=region)
Control del tiempo de espera
Establezca el parámetro connect_timeout (en segundos) al inicializar el cliente. El valor predeterminado es 60 segundos.
# Initialize an OSS bucket instance.
bucket = oss2.Bucket(auth, endpoint, bucket_name, connect_timeout=30, region=region)
Tamaño del pool de conexiones
Ajuste el tamaño del pool de conexiones con el parámetro pool_size del objeto session.
# Set the connection pool size. The default value is 10.
session = oss2.Session(pool_size=20)
# Initialize an OSS bucket instance.
bucket = oss2.Bucket(auth, endpoint, bucket_name, session=session, region=region)
Versión de TLS
Para especificar una versión de TLS, cree una sesión mediante un SSLAdapter personalizado.
El SDK de Python 2.18.1 y las versiones posteriores permiten especificar la versión de TLS.
import ssl
from requests.adapters import HTTPAdapter
# Define a custom adapter to specify the TLS version.
class SSLAdapter(HTTPAdapter):
def init_poolmanager(self, *args, **http_client_config):
# Specify TLS 1.2.
http_client_config["ssl_version"] = ssl.PROTOCOL_TLSv1_2
return super(SSLAdapter, self).init_poolmanager(*args, **http_client_config)
# Create a session by using SSLAdapter.
session = oss2.Session(adapter=SSLAdapter())
# Initialize an OSS bucket instance.
bucket = oss2.Bucket(auth, endpoint, bucket_name, session=session, region=region)
Deshabilitar la comprobación CRC
Para deshabilitar la comprobación de integridad de datos CRC, configure el parámetro enable_crc=False.
Mantenga habilitada la comprobación CRC. Si la deshabilita, OSS no podrá garantizar la integridad de los datos durante las cargas y descargas.
# Initialize an OSS bucket instance.
bucket = oss2.Bucket(auth, endpoint, bucket_name, enable_crc=False, region=region)
Versión de firma
Las firmas V1 de Alibaba Cloud Object Storage dejarán de estar disponibles según el siguiente calendario. Se recomienda upgrade to V4 signature lo antes posible para evitar que sus servicios se vean afectados.
A partir del 1 de marzo de 2025, los nuevos usuarios no podrán utilizar la firma V1.
A partir del 1 de septiembre de 2025, se eliminará gradualmente la compatibilidad y el mantenimiento de la firma V1, por lo que no será posible crear nuevos buckets que la utilicen.
El siguiente ejemplo inicializa un cliente con la firma V1. Para conocer cómo inicializar con la firma V4, consulte Initialize a Client.
Antes de ejecutar el código de ejemplo, reemplace los marcadores de posición como <endpoint> con su region and endpoint real, por ejemplo, https://oss-ap-southeast-1.aliyuncs.com .
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# OSS Python SDK V1 client initialization sample code
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
def main():
# Load access credentials from environment variables. You must set the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables.
auth = oss2.ProviderAuth(EnvironmentVariableCredentialsProvider())
# Set the endpoint.
endpoint = "<endpoint>"
# Set the bucket name.
bucket_name = "example-bucket"
# Initialize an OSS bucket instance.
bucket = oss2.Bucket(auth, endpoint, bucket_name)
# List files in the bucket.
print("=== List files in the bucket ===")
try:
# List files by using the list_objects() method.
result = bucket.list_objects()
# Iterate through the object list and print each object's key.
for obj in result.object_list:
print(obj.key)
# Print statistics.
print(f"\nTotal files listed: {len(result.object_list)}")
if result.is_truncated:
print("Note: The result is truncated. More files are available.")
except oss2.exceptions.OssError as e:
print(f"OSS error: {e}")
raise
except Exception as e:
print(f"An error occurred: {e}")
raise
if __name__ == "__main__":
# Program entry point.
try:
main()
except Exception as e:
print(f"An error occurred while running the program: {e}")
raise
Nombre de aplicación personalizado
Establezca el parámetro app_name para agregar un identificador personalizado al encabezado User-Agent. El valor predeterminado es una cadena vacía.
El nombre de la aplicación se transmite como un valor de encabezado HTTP y debe cumplir con los estándares HTTP.
# Initialize an OSS bucket instance.
bucket = oss2.Bucket(auth, endpoint, bucket_name, app_name="client_test", region=region)
Código de ejemplo
OSS Python SDK V1 proporciona ejemplos de código para la gestión de buckets, las operaciones con objetos, el control de acceso y la transferencia cifrada. Úselos como referencia o intégralos en su aplicación.
|
Código de ejemplo en GitHub |
Código de ejemplo en la documentación |
Consultar información de endpoints
Consulte la información de los endpoints de todas las regiones disponibles o de una región específica. Esta incluye los endpoints públicos (IPv4), internos y de aceleración de transferencia.
Python SDK 2.18.0 y versiones posteriores permiten consultar la información de los endpoints.
Antes de ejecutar el código de ejemplo, reemplace los marcadores de posición como<region-id>por su valor real de region and endpoint , por ejemplo,ap-southeast-1.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Sample code for querying endpoint information using the OSS Python SDK
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
def main():
print("=== Querying endpoint information for all supported regions ===\n")
# Obtain access credentials from environment variables. You must set the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# Specify the endpoint for the region where your bucket is located.
endpoint = "<endpoint>"
# Specify the region that corresponds to the endpoint. This parameter is required when you use Signature V4.
region = "<region-id>"
# Initialize an OSS Service instance.
service = oss2.Service(auth, endpoint, region=region)
try:
# Query endpoint information for all supported regions.
result = service.describe_regions()
# Iterate through the region information.
for r in result.regions:
print(f"Region: {r.region}")
print(f" Public (IPv4) Endpoint: {r.internet_endpoint}")
print(f" Internal (Classic Network or VPC) Endpoint: {r.internal_endpoint}")
print(f" Transfer Acceleration Endpoint: {r.accelerate_endpoint}")
print("-" * 80)
# Print statistics.
print(f"\nFound endpoint information for {len(result.regions)} regions.")
except oss2.exceptions.OssError as e:
print(f"OSS error: {e}")
raise
except Exception as e:
print(f"An error occurred: {e}")
raise
if __name__ == "__main__":
# Entry point of the program.
try:
main()
except Exception as e:
print(f"An error occurred during execution: {e}")
raise
Para consultar la información del endpoint de una región específica, especifique el identificador de región de OSS en el método describe_regions.
result = service.describe_regions("oss-<region-id>")
Configuración de credenciales
OSS admite varios métodos para inicializar credenciales. Elija uno según sus requisitos de autenticación.
Debe usar la versión 0.3.5 o posterior de alibabacloud-credentials. Si utiliza una versión anterior, se producirá un error.
AK de usuario de RAM
Este método es adecuado para entornos seguros y estables que requieren acceso prolongado a OSS sin rotar las credenciales con frecuencia. Inicialice el proveedor de credenciales con el AccessKey (AK) de un usuario de RAM. Esta opción exige mantener el AK de forma manual, lo cual introduce riesgos de seguridad.
Una cuenta de Alibaba Cloud tiene todos los permisos sobre todos los recursos. Si su AK se filtra, el sistema queda expuesto. En su lugar, utilice el AK de un usuario de RAM con los permisos mínimos obligatorios.
Para crear un AK para un usuario de RAM, consulte Create an AccessKey. El AccessKey ID y el AccessKey Secret solo se muestran en el momento de la creación. Si los olvida, cree uno nuevo.
Variables de entorno
-
Configure las variables de entorno mediante el Access Key (AK) de un usuario de RAM.
Linux
-
Ejecute los siguientes comandos en la interfaz de línea de comandos para agregar la configuración de las variables de entorno al archivo
~/.bashrc.echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bashrc echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bashrc -
Ejecute el siguiente comando para aplicar los cambios.
source ~/.bashrc -
Ejecute los siguientes comandos para comprobar que las variables de entorno están configuradas.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
macOS
-
Ejecute el siguiente comando en la terminal para consultar el tipo de shell predeterminado.
echo $SHELL -
Realice las siguientes operaciones según el tipo de shell predeterminado.
Zsh
-
Ejecute los siguientes comandos para agregar la configuración de las variables de entorno al archivo
~/.zshrc.echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.zshrc echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.zshrc -
Ejecute el siguiente comando para aplicar los cambios.
source ~/.zshrc -
Ejecute los siguientes comandos para comprobar que las variables de entorno están configuradas.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
Bash
-
Ejecute los siguientes comandos para agregar la configuración de las variables de entorno al archivo
~/.bash_profile.echo "export OSS_ACCESS_KEY_ID='YOUR_ACCESS_KEY_ID'" >> ~/.bash_profile echo "export OSS_ACCESS_KEY_SECRET='YOUR_ACCESS_KEY_SECRET'" >> ~/.bash_profile -
Ejecute el siguiente comando para aplicar los cambios.
source ~/.bash_profile -
Ejecute los siguientes comandos para comprobar que las variables de entorno están configuradas.
echo $OSS_ACCESS_KEY_ID echo $OSS_ACCESS_KEY_SECRET
-
Windows
CMD
-
Ejecute los siguientes comandos en CMD.
setx OSS_ACCESS_KEY_ID "YOUR_ACCESS_KEY_ID" setx OSS_ACCESS_KEY_SECRET "YOUR_ACCESS_KEY_SECRET" -
Ejecute los siguientes comandos para comprobar que las variables de entorno están configuradas.
echo %OSS_ACCESS_KEY_ID% echo %OSS_ACCESS_KEY_SECRET%
PowerShell
-
Ejecute los siguientes comandos en PowerShell.
[Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_ID", "YOUR_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User) [Environment]::SetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", "YOUR_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User) -
Ejecute los siguientes comandos para comprobar que las variables de entorno están configuradas.
[Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_ID", [EnvironmentVariableTarget]::User) [Environment]::GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET", [EnvironmentVariableTarget]::User)
-
Reinicie o actualice su IDE, CLI y otros entornos de ejecución después de modificar las variables de entorno para cargar los nuevos valores.
-
Utilice las variables de entorno para proporcionar las credenciales.
Antes de ejecutar el código de ejemplo, reemplace los marcadores de posición como
<region-id>por el valor real de region and endpoint . Por ejemplo, reemplace<region-id>porap-southeast-1.#!/usr/bin/env python3 # -*- coding: utf-8 -*- # OSS Python SDK V1: Sample code for client initialization import oss2 from oss2.credentials import EnvironmentVariableCredentialsProvider def main(): # Load access credentials from environment variables. You must set OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET. auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider()) # Set the OSS service region. region = "<region-id>" # Set the endpoint. endpoint = "<endpoint>" # Set the bucket name. bucket_name = "example-bucket-hz" # Initialize an OSS Bucket instance. bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region) # List objects in the bucket. print("=== List objects in the bucket ===") try: # Use the list_objects method to list objects. result = bucket.list_objects() # Iterate through the object list and print only the object keys. for obj in result.object_list: print(obj.key) # Print statistics. print(f"\nTotal objects listed: {len(result.object_list)}") if result.is_truncated: print("Note: The result is truncated. More objects are not listed.") except oss2.exceptions.OssError as e: print(f"OSS error: {e}") raise except Exception as e: print(f"An error occurred: {e}") raise if __name__ == "__main__": # Entry point of the program. try: main() except Exception as e: print(f"An error occurred during execution: {e}") raise
Credenciales estáticas
El siguiente código de ejemplo muestra cómo codificar de forma fija las credenciales en su aplicación.
No inserte credenciales directamente en las aplicaciones de un entorno de producción. Este método es únicamente para fines de prueba.
Antes de ejecutar el código de ejemplo, reemplace los marcadores de posición como<region-id>por el valor real de region and endpoint . Por ejemplo, reemplace<region-id>porap-southeast-1.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# OSS Python SDK V1: Sample code for client initialization
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
def main():
# Specify the AccessKey ID and AccessKey Secret of a RAM user.
access_key_id = 'yourAccessKeyID'
access_key_secret = 'yourAccessKeySecret'
# Configure access credentials using the Access Key (AK) of the RAM user.
auth = oss2.AuthV4(access_key_id, access_key_secret)
# Set the OSS service region.
region = "<region-id>"
# Set the endpoint.
endpoint = "<endpoint>"
# Set the bucket name.
bucket_name = "example-bucket-hz"
# Initialize an OSS Bucket instance.
bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region)
# List objects in the bucket.
print("=== List objects in the bucket ===")
try:
# Use the list_objects method to list objects.
result = bucket.list_objects()
# Iterate through the object list and print only the object keys.
for obj in result.object_list:
print(obj.key)
# Print statistics.
print(f"\nTotal objects listed: {len(result.object_list)}")
if result.is_truncated:
print("Note: The result is truncated. More objects are not listed.")
except oss2.exceptions.OssError as e:
print(f"OSS error: {e}")
raise
except Exception as e:
print(f"An error occurred: {e}")
raise
if __name__ == "__main__":
# Entry point of the program.
try:
main()
except Exception as e:
print(f"An error occurred during execution: {e}")
raise
Credenciales temporales de STS
Este método es adecuado para aplicaciones que necesitan acceso temporal a OSS. Inicialice el proveedor de credenciales con credenciales temporales (AccessKey ID, AccessKey Secret y token de seguridad) obtenidas de STS. Debe actualizar manualmente el token de STS antes de que caduque.
Para obtener credenciales de acceso temporales mediante una llamada a una API, consulte AssumeRole - Obtain temporary security credentials for a RAM role.
Para obtener credenciales de acceso temporales con un SDK, consulte Use temporary credentials provided by STS to access OSS.
Al generar un token de STS, debe establecer un tiempo de caducidad. Una vez que el token caduca, ya no se puede utilizar.
Para consultar la lista de endpoints de STS, consulte Service endpoints.
Variables de entorno
-
Establezca las variables de entorno con las credenciales de acceso temporales.
macOS, Linux y Unix
ImportanteUtilice las credenciales de acceso temporales (Access Key ID, Access Key Secret y token de seguridad) obtenidas de STS, no el Access Key (AK) de un usuario de RAM.
El Access Key ID obtenido de STS comienza con "STS.", por ejemplo, "STS.****".
export OSS_ACCESS_KEY_ID=<STS_ACCESS_KEY_ID> export OSS_ACCESS_KEY_SECRET=<STS_ACCESS_KEY_SECRET> export OSS_SESSION_TOKEN=<STS_SECURITY_TOKEN>Windows
ImportanteUtilice las credenciales de acceso temporales (Access Key ID, Access Key Secret y token de seguridad) obtenidas de STS, no el Access Key (AK) de un usuario de RAM.
El Access Key ID obtenido de STS comienza con "STS.", por ejemplo, "STS.****".
set OSS_ACCESS_KEY_ID=<STS_ACCESS_KEY_ID> set OSS_ACCESS_KEY_SECRET=<STS_ACCESS_KEY_SECRET> set OSS_SESSION_TOKEN=<STS_SECURITY_TOKEN> -
Proporcione las credenciales mediante variables de entorno.
Antes de ejecutar el código de ejemplo, reemplace los marcadores de posición como
<region-id>por el valor real de region and endpoint . Por ejemplo, reemplace<region-id>porap-southeast-1.# -*- coding: utf-8 -*- import oss2 from oss2.credentials import EnvironmentVariableCredentialsProvider # yourEndpoint specifies the endpoint for the region where the bucket is located. endpoint = '<endpoint>' # yourBucketName specifies the bucket name. bucket_name = 'yourBucketName' # Specify the region where the bucket is located. region = '<region-id>' # Configure access credentials by using the STS AK, SK, and Security Token from environment variables. # Note that ProviderAuthV4 indicates the use of V4 signatures. auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider()) # Initialize the bucket by using the Auth instance. Note that the region parameter is required when using V4 signatures; # otherwise, an error occurs. bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region) # Use the bucket object for subsequent operations...
Credenciales estáticas
Codifique de forma fija las credenciales en su aplicación y establezca explícitamente las claves de acceso temporales.
Antes de ejecutar el código de ejemplo, reemplace los marcadores de posición como<region-id>por el valor real de region and endpoint . Por ejemplo, reemplace<region-id>porap-southeast-1.
# -*- coding: utf-8 -*-
import oss2
# Specify the temporary AccessKey ID and AccessKey Secret obtained from STS, not the AccessKey ID and AccessKey Secret of your Alibaba Cloud account.
# Note that the Access Key ID obtained from STS starts with "STS."
sts_access_key_id = 'STS.****************'
sts_access_key_secret = 'yourAccessKeySecret'
# Specify the security token obtained from STS.
security_token = 'yourSecurityToken'
# yourEndpoint specifies the endpoint for the region where the bucket is located.
endpoint = '<endpoint>'
# yourBucketName specifies the bucket name.
bucket_name = 'yourBucketName'
# Specify the region where the bucket is located.
region = '<region-id>'
# Initialize the StsAuth instance. Note that setting auth_version to "v4" enables OSS V4 signatures.
auth = oss2.StsAuth(sts_access_key_id,
sts_access_key_secret,
security_token,
auth_version="v4")
# Initialize the bucket using the StsAuth instance. Note that the region parameter is required when using V4 signatures;
# otherwise, an error occurs.
bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region)
# Use the bucket object for subsequent operations...
ARN de rol de RAM
Este método es adecuado para el acceso entre cuentas. Inicialice el proveedor de credenciales con el ARN de un rol de RAM. La herramienta de credenciales actualiza automáticamente el token de STS mediante una llamada a AssumeRole antes de que caduque. Establezca el parámetro policy para restringir aún más los permisos.
Una cuenta de Alibaba Cloud tiene todos los permisos sobre todos los recursos. Si su AK se filtra, el sistema queda expuesto. En su lugar, utilice el AK de un usuario de RAM con los permisos mínimos obligatorios.
Para crear un AK para un usuario de RAM, consulte Create an AccessKey. El AccessKey ID y el AccessKey Secret solo se muestran en el momento de la creación. Si los olvida, cree uno nuevo.
Para obtener el ARN de un rol de RAM, consulte Create a RAM role.
-
Agregue la dependencia de credenciales.
pip install alibabacloud_credentials -
Configure el Access Key (AK) y el ARN del rol de RAM como credenciales de acceso.
Antes de ejecutar el código de ejemplo, reemplace los marcadores de posición como
<region-id>por el valor real de region and endpoint . Por ejemplo, reemplace<region-id>porap-southeast-1.# -*- coding: utf-8 -*- import oss2 from alibabacloud_credentials.client import Client from alibabacloud_credentials.models import Config from oss2 import CredentialsProvider from oss2.credentials import Credentials import os class CredentialProviderWrapper(CredentialsProvider): def __init__(self, client): self.client = client def get_credentials(self): credential = self.client.get_credential() access_key_id = credential.access_key_id access_key_secret = credential.access_key_secret security_token = credential.security_token return Credentials(access_key_id, access_key_secret, security_token) config = Config( # Obtain the Access Key (AccessKey ID and AccessKey Secret) of the RAM user from environment variables. access_key_id=os.getenv('ALIBABA_CLOUD_ACCESS_KEY_ID'), access_key_secret=os.getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET'), type='ram_role_arn', # The ARN of the RAM role to assume. Example: acs:ram::123456789012****:role/adminrole. You can set the RoleArn using the ALIBABA_CLOUD_ROLE_ARN environment variable. role_arn='<RoleArn>', # The role session name. You can set the RoleSessionName using the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable. role_session_name='<RoleSessionName>', # Optional. A more restrictive permission policy. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"} policy='<Policy>', # Optional. The validity period of the role session. role_session_expiration=3600 ) cred = Client(config) credentials_provider = CredentialProviderWrapper(cred) # Note that ProviderAuthV4 indicates the use of V4 signatures. auth = oss2.ProviderAuthV4(credentials_provider) # yourEndpoint specifies the endpoint for the region where the bucket is located. endpoint = '<endpoint>' # yourBucketName specifies the bucket name. bucket_name = 'yourBucketName' # Specify the region where the bucket is located. region = '<region-id>' # Initialize the bucket by using the Auth instance. Note that the region parameter is required when using V4 signatures; # otherwise, an error occurs. bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region) # Use the bucket object for subsequent operations...
Rol de RAM de instancia de ECS
Este método es adecuado para aplicaciones alojadas en instancias de ECS, instancias de ECI o nodos worker de Container Service for Kubernetes (ACK). Un rol de RAM de instancia de ECS permite actualizar automáticamente el token de STS en instancias de ECS, instancias de ECI o nodos worker de Container Service for Kubernetes (ACK) sin necesidad de proporcionar un AK ni un token de STS. Para obtener un rol, consulte Create a RAM role. Para adjuntarlo a una instancia, consulte Instance RAM role.
-
Agregue la dependencia de credenciales.
pip install alibabacloud_credentials -
Configure el rol de RAM de la instancia de ECS como credencial de acceso.
Antes de ejecutar el código de ejemplo, reemplace los marcadores de posición como
<region-id>por el valor real de region and endpoint . Por ejemplo, reemplace<region-id>porap-southeast-1.# -*- coding: utf-8 -*- import oss2 from alibabacloud_credentials.client import Client from alibabacloud_credentials.models import Config from oss2 import CredentialsProvider from oss2.credentials import Credentials class CredentialProviderWrapper(CredentialsProvider): def __init__(self, client): self.client = client def get_credentials(self): credential = self.client.get_credential() access_key_id = credential.access_key_id access_key_secret = credential.access_key_secret security_token = credential.security_token return Credentials(access_key_id, access_key_secret, security_token) config = Config( type='ecs_ram_role', # Credential type. Fixed value: ecs_ram_role. role_name='<RoleName>' # The name of the RAM role attached to the ECS instance. Optional. If not set, it is retrieved automatically. We strongly recommend setting this parameter to reduce requests. ) cred = Client(config) credentials_provider = CredentialProviderWrapper(cred) # Note that ProviderAuthV4 indicates the use of V4 signatures. auth = oss2.ProviderAuthV4(credentials_provider) # yourEndpoint specifies the endpoint for the region where the bucket is located. endpoint = '<endpoint>' # yourBucketName specifies the bucket name. bucket_name = 'yourBucketName' # Specify the region where the bucket is located. region = '<region-id>' # Initialize the bucket by using the Auth instance. Note that the region parameter is required when using V4 signatures; # otherwise, an error occurs. bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region) # Use the bucket object for subsequent operations...
ARN de rol de OIDC
Cuando se ejecutan aplicaciones no confiables en nodos worker de ACK, utilice RRSA para evitar que obtengan el token de STS del rol de RAM de la instancia del nodo. El clúster monta un archivo de token de OIDC de cuenta de servicio por cada pod e inyecta la configuración en las variables de entorno. La herramienta de credenciales intercambia el token de OIDC por un token de STS mediante AssumeRoleWithOIDC, sin requerir un AK ni un token de STS. Configure RAM permissions for a ServiceAccount to implement pod permission isolation by using RRSA.
-
Agregue la dependencia de credenciales.
pip install alibabacloud_credentials -
Configure el rol de OIDC como credencial de acceso.
Antes de ejecutar el código de ejemplo, reemplace los marcadores de posición como
<region-id>por el valor real de region and endpoint . Por ejemplo, reemplace<region-id>porap-southeast-1.# -*- coding: utf-8 -*- import oss2 from alibabacloud_credentials.client import Client from alibabacloud_credentials.models import Config from oss2 import CredentialsProvider from oss2.credentials import Credentials import os class CredentialProviderWrapper(CredentialsProvider): def __init__(self, client): self.client = client def get_credentials(self): credential = self.client.get_credential() access_key_id = credential.access_key_id access_key_secret = credential.access_key_secret security_token = credential.security_token return Credentials(access_key_id, access_key_secret, security_token) config = Config( # Credential type. Fixed value: oidc_role_arn. type='oidc_role_arn', # The ARN of the RAM role. You can set the RoleArn using the ALIBABA_CLOUD_ROLE_ARN environment variable. role_arn=os.environ.get('<RoleArn>'), # The ARN of the OIDC provider. You can set the OidcProviderArn using the ALIBABA_CLOUD_OIDC_PROVIDER_ARN environment variable. oidc_provider_arn=os.environ.get('<OidcProviderArn>'), # The OIDC token file path. You can set the OidcTokenFilePath using the ALIBABA_CLOUD_OIDC_TOKEN_FILE environment variable. oidc_token_file_path=os.environ.get('<OidcTokenFilePath>'), # The role session name. You can set the RoleSessionName using the ALIBABA_CLOUD_ROLE_SESSION_NAME environment variable. role_session_name='<RoleSessionName>', # Optional. A more restrictive permission policy. Example: {"Statement": [{"Action": ["*"],"Effect": "Allow","Resource": ["*"]}],"Version":"1"} policy='<Policy>', # The validity period of the session. role_session_expiration=3600 ) cred = Client(config) credentials_provider = CredentialProviderWrapper(cred) # Note that ProviderAuthV4 indicates the use of V4 signatures. auth = oss2.ProviderAuthV4(credentials_provider) # yourEndpoint specifies the endpoint for the region where the bucket is located. endpoint = '<endpoint>' # yourBucketName specifies the bucket name. bucket_name = 'yourBucketName' # Specify the region where the bucket is located. region = '<region-id>' # Initialize the bucket by using the Auth instance. Note that the region parameter is required when using V4 signatures; # otherwise, an error occurs. bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region) # Use the bucket object for subsequent operations...
Contexto de Function Compute
Este método es adecuado para funciones que se ejecutan en FC. FC asume un rol de servicio para obtener un token de STS (con validez de 36 horas) y lo transmite mediante el parámetro Credentials del contexto. Dado que el tiempo máximo de ejecución de una función es de 24 horas, el token no caduca durante la ejecución, por lo que no es necesario actualizarlo. Para otorgar a FC permisos de acceso a OSS, consulte Use a function role to grant Function Compute permissions to access other cloud services.
Inicialice el proveedor de credenciales con las credenciales del contexto de FC.
Antes de ejecutar el código de ejemplo, reemplace los marcadores de posición como<region-id>por el valor real de region and endpoint . Por ejemplo, reemplace<region-id>porap-southeast-1.
# -*- coding: utf-8 -*-
import oss2
from oss2 import CredentialsProvider
from oss2.credentials import Credentials
def handler(event, context):
class CredentialProviderWrapper(CredentialsProvider):
def get_credentials(self):
creds = context.credentials
return Credentials(creds.access_key_id, creds.access_key_secret, creds.security_token)
credentials_provider = CredentialProviderWrapper()
# Note that ProviderAuthV4 indicates the use of V4 signatures.
auth = oss2.ProviderAuthV4(credentials_provider)
# yourEndpoint specifies the endpoint for the region where the bucket is located.
endpoint = '<endpoint>'
# yourBucketName specifies the bucket name.
bucket_name = 'yourBucketName'
# Specify the region where the bucket is located.
region = '<region-id>'
# Initialize the bucket by using the Auth instance. Note that the region parameter is required when using V4 signatures;
# otherwise, an error occurs.
bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region)
# Use the bucket object for subsequent operations...
return 'success'
URI de credenciales
Este método es adecuado para aplicaciones que obtienen credenciales de un sistema externo. La herramienta de credenciales recupera un token de STS desde el URI proporcionado y gestiona la actualización automática.
Un URI de credenciales es la dirección del servidor desde donde se obtiene el token de STS.
El servicio de backend que proporciona la respuesta del URI de credenciales debe implementar la lógica de actualización automática del token de STS para garantizar que la aplicación siempre obtenga credenciales válidas.
-
Para asegurar que la herramienta de credenciales analice sintácticamente y utilice correctamente el token de STS, la respuesta del URI debe cumplir con el siguiente protocolo:
Código de estado de la respuesta: 200
-
Estructura del cuerpo de la respuesta:
{ "Code": "Success", "AccessKeySecret": "AccessKeySecret", "AccessKeyId": "AccessKeyId", "Expiration": "2021-09-26T03:46:38Z", "SecurityToken": "SecurityToken" }
-
Agregue la dependencia de credenciales.
pip install alibabacloud_credentials -
Configure el URI de credenciales como credencial de acceso.
Antes de ejecutar el código de ejemplo, reemplace los marcadores de posición como
<region-id>por el valor real de region and endpoint . Por ejemplo, reemplace<region-id>porap-southeast-1.# -*- coding: utf-8 -*- import oss2 from alibabacloud_credentials.client import Client from alibabacloud_credentials.models import Config from oss2 import CredentialsProvider from oss2.credentials import Credentials class CredentialProviderWrapper(CredentialsProvider): def __init__(self, client): self.client = client def get_credentials(self): credential = self.client.get_credential() access_key_id = credential.access_key_id access_key_secret = credential.access_key_secret security_token = credential.security_token return Credentials(access_key_id, access_key_secret, security_token) config = Config( type='credentials_uri', # The URI for the credentials, in the format http://local_or_remote_uri/. You can set the CredentialsUri using the ALIBABA_CLOUD_CREDENTIALS_URI environment variable. credentials_uri='<CredentialsUri>', ) cred = Client(config) credentials_provider = CredentialProviderWrapper(cred) # Note that ProviderAuthV4 indicates the use of V4 signatures. auth = oss2.ProviderAuthV4(credentials_provider) # yourEndpoint specifies the endpoint for the region where the bucket is located. endpoint = '<endpoint>' # yourBucketName specifies the bucket name. bucket_name = 'yourBucketName' # Specify the region where the bucket is located. region = '<region-id>' # Initialize the bucket by using the Auth instance. Note that the region parameter is required when using V4 signatures; # otherwise, an error occurs. bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region) # Use the bucket object for subsequent operations...
AK con rotación automática
Este método es adecuado para entornos donde el AK corre riesgo de comprometerse. Inicialice el proveedor de credenciales con un ClientKey de KMS, el cual rota automáticamente el AK administrado del usuario de RAM. KMS también admite la rotación inmediata si un AK se ve comprometido. Para obtener un ClientKey, consulte Create an Application Access Point.
-
Agregue la dependencia del cliente de Secrets Manager.
pip install aliyun-secret-manager-client -
Cree un archivo de configuración llamado
secretsmanager.properties.# The type of access credential. Fixed value: client_key credentials_type=client_key # The decryption password for the ClientKey. You can read it from an environment variable or a file. Set only one. client_key_password_from_env_variable=<your client key private key password environment variable name> client_key_password_from_file_path=<your client key private key password file path> # The path to the private key file of the ClientKey. client_key_private_key_path=<your client key private key file path> # The region of the associated KMS. cache_client_region_id=[{"regionId":"<regionId>"}] -
Utilice el archivo de configuración para proporcionar la información de las credenciales.
Antes de ejecutar el código de ejemplo, reemplace los marcadores de posición como
<region-id>por el valor real de region and endpoint . Por ejemplo, reemplace<region-id>porap-southeast-1.# -*- coding: utf-8 -*- import json import oss2 from oss2 import CredentialsProvider from oss2.credentials import Credentials from alibaba_cloud_secretsmanager_client.secret_manager_cache_client_builder import SecretManagerCacheClientBuilder class CredentialProviderWrapper(CredentialsProvider): def get_credentials(self): secret_cache_client = SecretManagerCacheClientBuilder.new_client() secret_info = secret_cache_client.get_secret_info("<secretName>") secret_value_json = json.loads(secret_info.secret_value) return Credentials(secret_value_json["AccessKeyId"], secret_value_json["AccessKeySecret"]) credentials_provider = CredentialProviderWrapper() # Note that ProviderAuthV4 indicates the use of V4 signatures. auth = oss2.ProviderAuthV4(credentials_provider) # yourEndpoint specifies the endpoint for the region where the bucket is located. endpoint = '<endpoint>' # yourBucketName specifies the bucket name. bucket_name = 'yourBucketName' # Specify the region where the bucket is located. region = '<region-id>' # Initialize the bucket by using the Auth instance. Note that the region parameter is required when using V4 signatures; # otherwise, an error occurs. bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region) # Use the bucket object for subsequent operations...
Proveedor de credenciales personalizado
Si ninguno de los métodos anteriores para configurar credenciales cumple con sus requisitos, defina un proveedor de credenciales personalizado mediante la implementación de la interfaz CredentialProvider. Si su implementación usa un token de STS, también debe gestionar la renovación de las credenciales.
Antes de ejecutar el código de ejemplo, reemplace los marcadores de posición como<region-id>por el valor real de region and endpoint . Por ejemplo, reemplace<region-id>porap-southeast-1.
# -*- coding: utf-8 -*-
import oss2
from oss2 import CredentialsProvider
from oss2.credentials import Credentials
class CredentialProviderWrapper(CredentialsProvider):
def get_credentials(self):
# TODO
# Implement your custom method for obtaining access credentials.
# Return long-term credentials: access_key_id, access_key_secret
return Credentials('<access_key_id>', '<access_key_secrect>')
# Return temporary credentials: access_key_id, access_key_secret, token
# For temporary credentials, you need to refresh them based on their expiration time.
# return Credentials('<access_key_id>', '<access_key_secrect>', '<token>');
credentials_provider = CredentialProviderWrapper()
# Note that ProviderAuthV4 indicates the use of V4 signatures.
auth = oss2.ProviderAuthV4(credentials_provider)
# yourEndpoint specifies the endpoint for the region where the bucket is located.
endpoint = '<endpoint>'
# yourBucketName specifies the bucket name.
bucket_name = 'yourBucketName'
# Specify the region where the bucket is located.
region = '<region-id>'
# Initialize the bucket by using the Auth instance. Note that the region parameter is required when using V4 signatures;
# otherwise, an error occurs.
bucket = oss2.Bucket(auth, endpoint, bucket_name, region=region)
# Use the bucket object for subsequent operations...
Preguntas frecuentes
¿Error: No module named _crcfunext?
Las cargas y descargas con OSS Python SDK V1 son más lentas que con otras herramientas, como ossutil u otros SDK.
-
Causa:
La biblioteca
_crcfunext.sono se genera durante la compilación decrcmodporque al sistema le falta el archivoPython.hobligatorio. Para obtener más información sobrecrcmod, consulte la introducción a crcmod. -
Solución:
Compruebe que el modo de extensión C para
crcmodesté instalado correctamente.-
Ejecute el siguiente comando para acceder al entorno de Python.
python -
Ejecute el siguiente comando para importar el módulo de extensión C
_crcfunextdesde el módulocrcmod.import crcmod._crcfunextEl siguiente error indica que el modo de extensión C de la biblioteca
crcmodno se instaló correctamente.Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named _crcfunext -
Elija una solución según su sistema operativo.
Windows
-
Descargue crcmod-1.7.win32-py2.7.msi u otra versión del archivo .msi.
NotaLa versión de 32 bits de
crcmodes compatible con sistemas Windows de 32 y 64 bits. Instale el archivo .msi. Durante la instalación, especifique la ruta de instalación de crcmod en la carpeta
Lib\site-packagesdel directorio local donde instaló Python. Por ejemplo,D:\python\Lib\site-packages\.Una vez finalizada la instalación, repita los pasos de verificación de
crcmod.
Linux
Si este problema ocurre en un sistema Linux, siga estos pasos:
-
Ejecute el siguiente comando para desinstalar
crcmod.pip uninstall crcmod Instale
python-devel. Consulte Prepare the environment.-
Ejecute el siguiente comando para reinstalar
crcmod.pip install crcmodSi la instalación vuelve a fallar, desinstale
crcmody ejecute el siguiente comando para consultar la información detallada del error.pip install crcmod -v
-
-
¿Error: No module named 'Crypto'?
-
Causa:
El módulo
Cryptono existe en el sistema o bien existe el módulocrypto(con la letra inicial en minúscula). -
Solución:
Busque el módulo Crypto en la ruta de instalación local de Python, por ejemplo,
D:\python3.9\Lib\site-packages.-
Si el módulo Crypto no existe, ejecute el siguiente comando.
python -m pip install --upgrade setuptools Si existe un módulo llamado
crypto(con c minúscula), cámbiele el nombre aCryptoy reinicie el programa.
-
¿Error: "no se reconoce como un comando interno o externo"?
En Windows, si recibe el mensaje «no se reconoce como un comando interno o externo», agregue las rutas de instalación de Python y pip (generalmente la carpeta Scripts dentro del directorio de Python) a la variable de entorno Path. Reinicie la computadora para que los cambios surtan efecto.
Error en la instalación de OSS Python SDK V1
Si la instalación falla, desinstale el paquete e inténtelo de nuevo.
pip uninstall oss2
Actualizar OSS Python SDK V1
Ejecute el siguiente comando para actualizar el SDK.
pip install --upgrade oss2
Solucionar errores AccessDenied
Un error AccessDenied indica permisos insuficientes. Siga estos pasos para solucionarlo:
Asegúrese de usar el AccessKey ID y el AccessKey Secret correctos.
Compruebe que el usuario de RAM tenga los permisos obligatorios para las operaciones del bucket o del objeto.
Revise la directiva del bucket. Un mensaje de error que contenga «Access denied by bucket policy» indica que una directiva de bucket bloqueó la solicitud.
Mejorar la velocidad de transferencia en accesos dentro de la misma región
Para lograr transferencias más rápidas, acceda a OSS desde un producto de Alibaba Cloud (como ECS) ubicado en la misma región que su bucket y utilice un endpoint interno.
Consultar AccessKeys y gestionar AccessKey Secrets
Para consultar el AccessKey de un usuario de RAM: inicie sesión en la consola de RAM y seleccione el usuario correspondiente para consultar la información de su AccessKey.
El AccessKey Secret de un usuario de RAM solo se muestra en el momento de su creación. Si lo pierde, cree un nuevo AccessKey en la consola de RAM. Create an AccessKey.