This article explains how to use the TOS Python SDK to perform common operations such as creating buckets, uploading objects, downloading objects, and deleting objects.
In multi-process scenarios, create a separate TosClient for each process. Do not share the same TosClient across processes to avoid concurrency and data corruption issues in read/write requests.
Installation and initialization
Install python-devel
You need to install the python-devel package.
The TOS Python SDK relies on crcmod to calculate CRC checksums. The C extension mode of crcmod depends on the Python.h file from the python-devel package. If Python.h is missing, crcmod’s C extension mode installation fails, causing crcmod to run in pure Python mode. The pure Python mode has much lower CRC calculation performance than the C extension mode, resulting in inefficient upload and download operations.
tip
If enabling CRC checksum causes poor upload or download performance, you can disable CRC64 checksum.
Verify crcmod mode
Enter the Python environment and type import crcmod._crcfunext.
- If the following error message appears, it means the C extension mode of the crcmod library failed to install; the crcmod library is operating in pure Python mode. The reason is that when compiling crcmod, _crcfunext.so depends on the Python.h file, which is missing in the system, causing the _crcfunext.so library to fail to generate.
- If no error message appears, it means the C extension mode of the crcmod library installed successfully.
If an error appears, you can resolve it as follows:
- If you are using Windows or Mac OS X, the Python-dependent header files install automatically with Python, so you do not need to install python-devel.
- If you are using CentOS, RHEL, or Fedora, you can install it using the following command:
- If you use Debian or Ubuntu, install it with the following command:
Client general example
The following code is a general template using the TOS Python SDK.
Create a bucket
A bucket is a globally unique namespace in TOS, acting as a container to store object data. The following code creates a new bucket named bucket-test.
Upload an object
After successfully creating a new bucket, you can upload objects to it. The following code uploads a string to the TOS bucket bucket-test.
Downloading objects
The following code downloads the specified TOS object into memory.
Listing objects
The following code lists objects in the specified bucket bucket-test, listing up to 2,000 objects.
Deleting objects
The following code deletes the object object-test from the specified bucket bucket-test.
Close TosClient
The TOS Python SDK enables persistent connections by default. When you create multiple TosClient instances to access TOS, use the following code to close unused TosClient instances and release connection resources.