Access OSS objects as read-only Python file objects using the File-Like interface in OSS SDK for Python 2.0.
Usage notes
-
The sample code uses the China (Hangzhou) region (
cn-hangzhou) with the public endpoint. To access OSS from other Alibaba Cloud services in the same region, use an internal endpoint. OSS regions and endpoints. -
Access credentials are obtained from environment variables. For more information about how to configure access credentials, see Configure access credentials.
-
Downloading requires the
oss:GetObjectpermission. Grant custom permissions to a RAM user.
Method
OSS SDK for Python 2.0 provides the File-Like interface for read-only access to bucket objects via the ReadOnlyFile class.
-
ReadOnlyFile supports single-stream and prefetch modes. Adjust parallel task count to improve read speed.
-
Built-in reconnection handles connection drops in unstable networks.
class ReadOnlyFile:
...
def open_file(self, bucket: str, key: str, version_id: Optional[str] = None, request_payer: Optional[str] = None, **kwargs) -> ReadOnlyFile:
...
Request parameters
|
Parameter |
Type |
Description |
|
bucket |
str |
The name of the bucket. |
|
key |
str |
The name of the object. |
|
version_id |
str |
The version ID of the object. Valid only when multiple versions exist. |
|
request_payer |
str |
Set to requester when pay-by-requester is enabled. |
|
**kwargs |
Any |
Optional keyword arguments (dictionary). |
Options of kwargs
|
Option |
Type |
Description |
|
enable_prefetch |
bool |
Enables prefetch mode. Default: disabled. |
|
prefetch_num |
int |
Number of prefetch chunks. Default: 3. Effective only in prefetch mode. |
|
chunk_size |
int |
Size of each prefetch chunk in MiB. Default: 6. Effective only in prefetch mode. |
|
prefetch_threshold |
int |
Sequential read threshold before prefetch activates, in MiB. Default: 20. |
|
block_size |
int |
The size of a chunk. Default value: None. |
Response parameters
|
Parameter |
Type |
Description |
|
file |
ReadOnlyFile |
The ReadOnlyFile instance. |
Common methods of ReadOnlyFile
|
Method |
Description |
|
close(self) |
Closes the file and releases resources, such as memory and active sockets. |
|
read(self, n=None) |
Reads up to n bytes from the object and returns the data read. |
|
seek(self, pos, whence=0) |
Sets the read position. whence values: 0 (start), 1 (current position), 2 (end). |
|
Stat() (os.FileInfo, error) |
Queries object information, including the object size, last modified time, and metadata. |
If multiple out-of-order reads occur in prefetch mode, the SDK falls back to single-stream mode.
Examples
References
-
Full API design reference: File-Like (GitHub).