All Products
Search
Document Center

Object Storage Service:Use a presigned URL to download an object (Python SDK V2)

Last Updated:Jul 31, 2025

By default, the access control list (ACL) of an object in an Object Storage Service (OSS) bucket is private. Only the object owner has permission to access the object. This topic describes how to use the OSS SDK for Python to generate a presigned URL that allows a user to download a specific object for a specified period using the HTTP GET method. A user can use the presigned URL to access the object multiple times before the URL expires. If the presigned URL expires, you can generate a new one to extend the user's access.

Usage notes

  • The sample code in this topic uses the region ID cn-hangzhou of the China (Hangzhou) region. By default, a public endpoint is used to access a bucket. If you want to access the bucket from other Alibaba Cloud services in the same region, use the internal endpoint. For more information about OSS regions and endpoints, see Regions and endpoints.

  • You do not need specific permissions to generate a presigned URL. However, to allow others to use the presigned URL to download an object, you must have the oss:GetObject permission. For more information, see Common examples of RAM policies.

  • In this topic, the V4 signature algorithm is used to generate presigned URLs that are valid for up to seven days. For more information, see (Recommended) Include a V4 signature in a URL.

Process

The following flowchart shows how to download an object by using a presigned URL.

image

Method definition

You can call the presign method to generate a presigned URL that grants time-limited access to an OSS object. The presigned URL can be used multiple times before it expires.

The following code shows the syntax of the presign method:

presign(request: GetObjectRequest, **kwargs) → PresignResult

Request parameters

Parameter

Type

Description

request

GetObjectRequest

The API operation that you want the presigned URL to support. For more information, see Client.presign.

expires

datetime.timedelta

The validity period of the presigned URL starting from the current time. This is an optional parameter. For example, if you want to set the validity period to 30 minutes, set expires to 30 * time.Minute. If you do not specify this parameter, the presigned URL will have a default validity period of 15 minutes.

expiration

datetime.datetime

The absolute expiration date and time of the presigned URL. This is an optional parameter.

Important

If you use the V4 signature algorithm, the maximum validity period is seven days. If you specify both expiration and expires, expiration takes precedence.

Response parameters

Type

Description

PresignResult

The returned results, including the presigned URL, HTTP method, expiration time, and request headers specified in the request. For more information, see PresignResult.

The PresignResult class contains the following content:

Parameter

Type

Description

method

str

The HTTP method, which corresponds to the API operation specified in the presign request. For example, the HTTP method of the GetObject operation is GET.

url

str

The presigned URL.

expiration

datetime

The expiration time of the presigned URL.

signed_headers

MutableMapping

The signed headers specified in the request. For example, if content_type is specified, content_type is returned.

For more information about the presign method, see presign.

Sample code

  1. The file owner generates a presigned URL for the GET method.

    import argparse
    import alibabacloud_oss_v2 as oss
    
    # Create a command-line parameter parser and describe the purpose of the script: generate a presigned URL for a GET request.
    parser = argparse.ArgumentParser(description="presign get object sample")
    
    # Add the --region command-line parameter to specify the region in which the bucket is located. This parameter is required.
    parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
    # Add the --bucket command-line parameter to specify the name of the bucket that stores the object. This parameter is required.
    parser.add_argument('--bucket', help='The name of the bucket.', required=True)
    # Add the --endpoint command-line parameter to specify the domain name that other services can use to access OSS. This parameter is optional.
    parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
    # Add the --key command-line parameter to specify the key of the object (file) in OSS. This parameter is required.
    parser.add_argument('--key', help='The name of the object.', required=True)
    
    def main():
        # Parse the command-line parameters to obtain the specified values.
        args = parser.parse_args()
    
        # Load the authentication information required to access OSS from environment variables for identity verification.
        credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
    
        # Use the default configurations of the SDK to create a configuration object and set the credential provider.
        cfg = oss.config.load_default()
        cfg.credentials_provider = credentials_provider
        
        # Set the region property of the configuration object based on the command-line parameters.
        cfg.region = args.region
    
        # If a custom endpoint is provided, update the endpoint property of the configuration object.
        if args.endpoint is not None:
            cfg.endpoint = args.endpoint
    
        # Use the preceding configurations to initialize the OSS client to interact with OSS.
        client = oss.Client(cfg)
    
        # Generate a presigned GET request.
        pre_result = client.presign(
            oss.GetObjectRequest(
                bucket=args.bucket,  # Specify the bucket name.
                key=args.key,        # Specify the object key.
            )
        )
    
        # Print the method, expiration time, and URL of the presigned request.
        print(f'method: {pre_result.method},'
              f' expiration: {pre_result.expiration.strftime("%Y-%m-%dT%H:%M:%S.000Z")},'
              f' url: {pre_result.url}'
        )
    
        # Print the signed headers of the presigned request.
        for key, value in pre_result.signed_headers.items():
            print(f'signed headers key: {key}, signed headers value: {value}')
    
    # When this script is directly executed, call the main function to start the processing logic.
    if __name__ == "__main__":
        main()  # The entry point of the script. The program flow starts here.
  2. Other users download the file using the presigned URL for the GET method.

    curl

    curl -SO "https://examplebucket.oss-cn-hangzhou.aliyuncs.com/exampleobject.txt?x-oss-date=20241112T092756Z&x-oss-expires=3599&x-oss-signature-version=OSS4-HMAC-SHA256&x-oss-credential=LTAI****************/20241112/cn-hangzhou/oss/aliyun_v4_request&x-oss-signature=ed5a******************************************************"

    Java

    import java.io.BufferedInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.HttpURLConnection;
    import java.net.URL;
    
    public class Demo {
        public static void main(String[] args) {
            // Specify the presigned URL that allows HTTP GET requests. 
            String fileURL = "https://examplebucket.oss-cn-hangzhou.aliyuncs.com/exampleobject.txt?x-oss-date=20241112T092756Z&x-oss-expires=3599&x-oss-signature-version=OSS4-HMAC-SHA256&x-oss-credential=LTAI****************/20241112/cn-hangzhou/oss/aliyun_v4_request&x-oss-signature=ed5a******************************************************";
            // Specify the path in which the downloaded object is stored, including the object name and extension. 
            String savePath = "C:/downloads/myfile.txt";
    
            try {
                downloadFile(fileURL, savePath);
                System.out.println("Download completed!");
            } catch (IOException e) {
                System.err.println("Error during download: " + e.getMessage());
            }
        }
    
        private static void downloadFile(String fileURL, String savePath) throws IOException {
            URL url = new URL(fileURL);
            HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
            httpConn.setRequestMethod("GET");
    
            // Specify the response code.
            int responseCode = httpConn.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // Configure the input stream.
                InputStream inputStream = new BufferedInputStream(httpConn.getInputStream());
                // Configure the output stream.
                FileOutputStream outputStream = new FileOutputStream(savePath);
    
                byte[] buffer=new byte[4096]; // Specify the size of the buffer.
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
    
                outputStream.close();
                inputStream.close();
            } else {
                System.out.println("No file to download. Server replied HTTP code: " + responseCode);
            }
            httpConn.disconnect();
        }
    }

    Node.js

    const https = require('https');
    const fs = require('fs');
    
    const fileURL = "https://examplebucket.oss-cn-hangzhou.aliyuncs.com/exampleobject.txt?x-oss-date=20241112T092756Z&x-oss-expires=3599&x-oss-signature-version=OSS4-HMAC-SHA256&x-oss-credential=LTAI****************/20241112/cn-hangzhou/oss/aliyun_v4_request&x-oss-signature=ed5a******************************************************";
    const savePath = "C:/downloads/myfile.txt";
    
    https.get(fileURL, (response) => {
        if (response.statusCode === 200) {
            const fileStream = fs.createWriteStream(savePath);
            response.pipe(fileStream);
            
            fileStream.on('finish', () => {
                fileStream.close();
                console.log("Download completed!");
            });
        } else {
            console.error(`Download failed. Server responded with code: ${response.statusCode}`);
        }
    }).on('error', (err) => {
        console.error("Error during download:", err.message);
    });

    Python

    import requests
    
    file_url = "https://examplebucket.oss-cn-hangzhou.aliyuncs.com/exampleobject.txt?x-oss-date=20241112T092756Z&x-oss-expires=3599&x-oss-signature-version=OSS4-HMAC-SHA256&x-oss-credential=LTAI****************/20241112/cn-hangzhou/oss/aliyun_v4_request&x-oss-signature=ed5a******************************************************"
    save_path = "C:/downloads/myfile.txt"
    
    try:
        response = requests.get(file_url, stream=True)
        if response.status_code == 200:
            with open(save_path, 'wb') as f:
                for chunk in response.iter_content(4096):
                    f.write(chunk)
            print("Download completed!")
        else:
            print(f"No file to download. Server replied HTTP code: {response.status_code}")
    except Exception as e:
        print("Error during download:", e)

    Go

    package main
    
    import (
        "io"
        "net/http"
        "os"
    )
    
    func main() {
        fileURL := "https://examplebucket.oss-cn-hangzhou.aliyuncs.com/exampleobject.txt?x-oss-date=20241112T092756Z&x-oss-expires=3599&x-oss-signature-version=OSS4-HMAC-SHA256&x-oss-credential=LTAI****************/20241112/cn-hangzhou/oss/aliyun_v4_request&x-oss-signature=ed5a******************************************************"
        savePath := "C:/downloads/myfile.txt"
    
        response, err := http.Get(fileURL)
        if err != nil {
            panic(err)
        }
        defer response.Body.Close()
    
        if response.StatusCode == http.StatusOK {
            outFile, err := os.Create(savePath)
            if err != nil {
                panic(err)
            }
            defer outFile.Close()
    
            _, err = io.Copy(outFile, response.Body)
            if err != nil {
                panic(err)
            }
            println("Download completed!")
        } else {
            println("No file to download. Server replied HTTP code:", response.StatusCode)
        }
    }

    JavaScript

    const fileURL = "https://examplebucket.oss-cn-hangzhou.aliyuncs.com/exampleobject.txt?x-oss-date=20241112T092756Z&x-oss-expires=3599&x-oss-signature-version=OSS4-HMAC-SHA256&x-oss-credential=LTAI****************/20241112/cn-hangzhou/oss/aliyun_v4_request&x-oss-signature=ed5a******************************************************";
    const savePath = "C:/downloads/myfile.txt"; // Specify the name of the downloaded object.
    
    fetch(fileURL)
        .then(response => {
            if (!response.ok) {
                throw new Error(`Server replied HTTP code: ${response.status}`);
            }
            return response.blob(); // Change the type of the response to blob.
        })
        .then(blob => {
            const link = document.createElement('a');
            link.href = window.URL.createObjectURL(blob);
            link.download=savePath; // Specify the name of the downloaded object.
            document.body.appendChild(link); // This step ensures that the presigned URL exists in the document.
            link.click(); // Click the presigned URL to simulate the object download.
            link.remove(); // Remove the presigned URL after the object is downloaded.
            console.log("Download completed!");
        })
        .catch(error => {
            console.error("Error during download:", error);
        });

    Android-Java

    import android.os.AsyncTask;
    import android.os.Environment;
    import java.io.BufferedInputStream;
    import java.io.FileOutputStream;
    import java.io.InputStream;
    import java.net.HttpURLConnection;
    import java.net.URL;
    
    public class DownloadTask extends AsyncTask<String, String, String> {
        @Override
        protected String doInBackground(String... params) {
            String fileURL = params[0];
            String savePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/myfile.txt"; // Specify the path in which you want to store the downloaded object.
            try {
                URL url = new URL(fileURL);
                HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
                httpConn.setRequestMethod("GET");
                int responseCode = httpConn.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    InputStream inputStream = new BufferedInputStream(httpConn.getInputStream());
                    FileOutputStream outputStream = new FileOutputStream(savePath);
                    byte[] buffer = new byte[4096];
                    int bytesRead;
                    while ((bytesRead = inputStream.read(buffer)) != -1) {
                        outputStream.write(buffer, 0, bytesRead);
                    }
                    outputStream.close();
                    inputStream.close();
                    return "Download completed!";
                } else {
                    return "No file to download. Server replied HTTP code: " + responseCode;
                }
            } catch (Exception e) {
                return "Error during download: " + e.getMessage();
            }
        }
    }

    Objective-C

    #import <Foundation/Foundation.h>
    
    int main(int argc, const char * argv[]) {
        @autoreleasepool {
            // Specify the presigned URL and the path in which you want to store the object.
            NSString *fileURL = @"https://examplebucket.oss-cn-hangzhou.aliyuncs.com/exampleobject.txt?x-oss-date=20241112T092756Z&x-oss-expires=3599&x-oss-signature-version=OSS4-HMAC-SHA256&x-oss-credential=LTAI****************/20241112/cn-hangzhou/oss/aliyun_v4_request&x-oss-signature=ed5a******************************************************";
            NSString *savePath = @"/Users/your_username/Desktop/myfile.txt"; // Replace your_username with your username.
            
            // Create a URL object.
            NSURL *url = [NSURL URLWithString:fileURL];
            
            // Create an object download task.
            NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                // Handle errors.
                if (error) {
                    NSLog(@"Error during download: %@", error.localizedDescription);
                    return;
                }
                
                // Check the data in the object.
                if (!data) {
                    NSLog(@"No data received.");
                    return;
                }
                
                // Save the object.
                NSError *writeError = nil;
                BOOL success = [data writeToURL:[NSURL fileURLWithPath:savePath] options:NSDataWritingAtomic error:&writeError];
                if (success) {
                    NSLog(@"Download completed!");
                } else {
                    NSLog(@"Error saving file: %@", writeError.localizedDescription);
                }
            }];
            
            // Start the object download task.
            [task resume];
            
            // Continue to run the main thread to complete the asynchronous request.
            [[NSRunLoop currentRunLoop] run];
        }
        return 0;
    }

Common scenarios

Generate a presigned URL that allows HTTP GET requests for a specific version of an object

The following sample code shows how to generate a presigned URL that allows HTTP GET requests for a specific version of an object:

import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line parameter parser and describe the purpose of the script: generate a presigned URL for a GET request.
parser = argparse.ArgumentParser(description="presign get object sample")

# Add the --region command-line parameter to specify the region in which the bucket is located. This parameter is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Add the --bucket command-line parameter to specify the name of the bucket that stores the object. This parameter is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# Add the --endpoint command-line parameter to specify the domain name that other services can use to access OSS. This parameter is optional.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
# Add the --key command-line parameter to specify the key of the object (file) in OSS. This parameter is required.
parser.add_argument('--key', help='The name of the object.', required=True)

def main():
    # Parse the command-line parameters to obtain the specified values.
    args = parser.parse_args()

    # Load the authentication information required to access OSS from environment variables for identity verification.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Use the default configurations of the SDK to create a configuration object and set the credential provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider
    
    # Set the region property of the configuration object based on the command-line parameters.
    cfg.region = args.region

    # If a custom endpoint is provided, update the endpoint property of the configuration object.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Use the preceding configurations to initialize the OSS client to interact with OSS.
    client = oss.Client(cfg)

    # Generate a presigned GET request.
    # Note: The version_id parameter is optional. You need to use this parameter only when versioning is enabled for your bucket.
    pre_result = client.presign(
        oss.GetObjectRequest(
            bucket=args.bucket,  # Specify the bucket name.
            key=args.key,        # Specify the object key.
            version_id='yourVersionId'  # Replace with the actual version ID if applicable.
        )
    )

    # Print the method, expiration time, and URL of the presigned request.
    print(f'method: {pre_result.method},'
          f' expiration: {pre_result.expiration.strftime("%Y-%m-%dT%H:%M:%S.000Z")},'
          f' url: {pre_result.url}'
    )

    # Print the signed headers of the presigned request.
    for key, value in pre_result.signed_headers.items():
        print(f'signed headers key: {key}, signed headers value: {value}')

# When this script is directly executed, call the main function to start the processing logic.
if __name__ == "__main__":
    main()  # The entry point of the script. The program flow starts here.

Download an object using a presigned URL that contains specified request headers

If you specify request headers when you generate a presigned URL for an HTTP GET request, you must include the same request headers in the GET request that uses the presigned URL. This prevents request failures and signature errors.

  1. Generate a presigned URL that allows HTTP GET requests and contains specific request headers.

    import argparse
    import alibabacloud_oss_v2 as oss
    
    # Create a command-line parameter parser and describe the purpose of the script: generate a presigned URL for a GET request.
    parser = argparse.ArgumentParser(description="presign get object sample")
    
    # Add the --region command-line parameter to specify the region in which the bucket is located. This parameter is required.
    parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
    # Add the --bucket command-line parameter to specify the name of the bucket that stores the object. This parameter is required.
    parser.add_argument('--bucket', help='The name of the bucket.', required=True)
    # Add the --endpoint command-line parameter to specify the domain name that other services can use to access OSS. This parameter is optional.
    parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
    # Add the --key command-line parameter to specify the key of the object (file) in OSS. This parameter is required.
    parser.add_argument('--key', help='The name of the object.', required=True)
    
    def main():
        # Parse the command-line parameters to obtain the specified values.
        args = parser.parse_args()
    
        # Load the authentication information required to access OSS from environment variables for identity verification.
        credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
    
        # Use the default configurations of the SDK to create a configuration object and set the credential provider.
        cfg = oss.config.load_default()
        cfg.credentials_provider = credentials_provider
    
        # Set the region property of the configuration object based on the command-line parameters.
        cfg.region = args.region
    
        # If a custom endpoint is provided, update the endpoint property of the configuration object.
        if args.endpoint is not None:
            cfg.endpoint = args.endpoint
    
        # Use the preceding configurations to initialize the OSS client to interact with OSS.
        client = oss.Client(cfg)
    
        # Generate a presigned GET request.
        pre_result = client.presign(
            oss.GetObjectRequest(
                bucket=args.bucket,  # Specify the bucket name.
                key=args.key,        # Specify the object key.
                range_behavior="standard", # Specify a request header.
                request_payer="requester", # Specify a request header.
            )
        )
    
        # Print the method, expiration time, and URL of the presigned request.
        print(f'method: {pre_result.method},'
              f' expiration: {pre_result.expiration.strftime("%Y-%m-%dT%H:%M:%S.000Z")},'
              f' url: {pre_result.url}'
        )
    
        # Print the signed headers of the presigned request.
        for key, value in pre_result.signed_headers.items():
            print(f'signed headers key: {key}, signed headers value: {value}')
    
    # When this script is directly executed, call the main function to start the processing logic.
    if __name__ == "__main__":
        main()  # The entry point of the script. The program flow starts here.
  2. Download the object using the presigned URL and specifying the request headers.

    curl -X GET "https://examplebucket.oss-cn-hangzhou.aliyuncs.com/exampleobject.txt?x-oss-date=20241113T093321Z&x-oss-expires=3599&x-oss-signature-version=OSS4-HMAC-SHA256&x-oss-credential=LTAI****************&x-oss-signature=ed5a******************************************************" \
    -H "x-oss-range-behavior: standard" \
    -H "x-oss-request-payer: requester" \
    -o "myfile.txt"
    import requests
    
    def download_file(signed_url, file_path, headers=None, metadata=None):
        """
        Downloads a file using a presigned URL.
    
        :param signed_url: The presigned URL.
        :param file_path: The full path to which the file is downloaded.
        :param headers: Optional. The custom HTTP headers.
        :param metadata: Optional. The custom metadata. This parameter is not used in GET requests.
        :return: None
        """
        if not headers:
            headers = {}
    
        try:
            response = requests.get(signed_url, headers=headers, stream=True)
            print(f"Returned download status code: {response.status_code}")
    
            if response.status_code == 200:
                with open(file_path, 'wb') as file:
                    for chunk in response.iter_content(chunk_size=8192):
                        if chunk:
                            file.write(chunk)
                print("File downloaded successfully")
            else:
                print("Download failed")
                print(response.text)
        except Exception as e:
            print(f"An error occurred: {e}")
    
    if __name__ == "__main__":
        # Replace <signedUrl> with the authorization URL.
        signed_url = "<signedUrl>"
        file_path = "/Users/yourLocalPath>/Downloads/downloadedFile.txt" # The local path to save the file.
    
        headers = {
            "X-Oss-Range-Behavior":"standard",
            "X-Oss-Request-Payer":"requester",
        }
    
        download_file(signed_url, file_path, headers=headers)

Forcibly download an object using a presigned URL

  1. Generate a URL that contains the response-content-disposition parameter.

    import argparse
    import alibabacloud_oss_v2 as oss
    
    # Create a command-line parameter parser and describe the purpose of the script: generate a presigned URL for a GET request.
    parser = argparse.ArgumentParser(description="presign get object sample")
    
    # Add the --region command-line parameter to specify the region in which the bucket is located. This parameter is required.
    parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
    # Add the --bucket command-line parameter to specify the name of the bucket that stores the object. This parameter is required.
    parser.add_argument('--bucket', help='The name of the bucket.', required=True)
    # Add the --endpoint command-line parameter to specify the domain name that other services can use to access OSS. This parameter is optional.
    parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
    # Add the --key command-line parameter to specify the key of the object (file) in OSS. This parameter is required.
    parser.add_argument('--key', help='The name of the object.', required=True)
    
    def main():
        # Parse the command-line parameters to obtain the specified values.
        args = parser.parse_args()
    
        # Load the authentication information required to access OSS from environment variables for identity verification.
        credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
    
        # Use the default configurations of the SDK to create a configuration object and set the credential provider.
        cfg = oss.config.load_default()
        cfg.credentials_provider = credentials_provider
    
        # Set the region property of the configuration object based on the command-line parameters.
        cfg.region = args.region
    
        # If a custom endpoint is provided, update the endpoint property of the configuration object.
        if args.endpoint is not None:
            cfg.endpoint = args.endpoint
    
        # Use the preceding configurations to initialize the OSS client to interact with OSS.
        client = oss.Client(cfg)
    
        # Generate a presigned GET request.
        pre_result = client.presign(
            oss.GetObjectRequest(
                bucket=args.bucket,  # Specify the bucket name.
                key=args.key,        # Specify the object key.
                response_content_disposition="attachment;filename=test.txt",
            )
        )
    
        # Print the method, expiration time, and URL of the presigned request.
        print(f'method: {pre_result.method},'
              f' expiration: {pre_result.expiration.strftime("%Y-%m-%dT%H:%M:%S.000Z")},'
              f' url: {pre_result.url}'
        )
    
        # Print the signed headers of the presigned request.
        for key, value in pre_result.signed_headers.items():
            print(f'signed headers key: {key}, signed headers value: {value}')
    
    # When this script is directly executed, call the main function to start the processing logic.
    if __name__ == "__main__":
        main()  # The entry point of the script. The program flow starts here.

  2. Use the presigned URL that contains the query parameters to download the specified object.

    curl -X GET "https://examplebucket.oss-cn-hangzhou.aliyuncs.com/exampleobject.txt?response-content-disposition=attachment%3B%20filename%3Dtest.txt&x-oss-date=20241113T093321Z&x-oss-expires=3599&x-oss-signature-version=OSS4-HMAC-SHA256&x-oss-credential=LTAI****************&x-oss-signature=ed5a******************************************************" \
    -o "myfile.txt"
    import requests
    
    def download_file(signed_url, file_path):
        """
        Downloads a file using a presigned URL.
    
        :param signed_url: The presigned URL.
        :param file_path: The full path to which the file is downloaded.
        :param headers: Optional. The custom HTTP headers.
        :param metadata: Optional. The custom metadata. This parameter is not used in GET requests.
        :return: None
        """
    
        try:
            response = requests.get(signed_url, stream=True)
            print(f"Returned download status code: {response.status_code}")
    
            if response.status_code == 200:
                with open(file_path, 'wb') as file:
                    for chunk in response.iter_content(chunk_size=8192):
                        if chunk:
                            file.write(chunk)
                print("File downloaded successfully")
            else:
                print("Download failed")
                print(response.text)
        except Exception as e:
            print(f"An error occurred: {e}")
    
    if __name__ == "__main__":
        # Replace <signedUrl> with the authorization URL.
        signed_url = "<signedUrl>"
        file_path = "/Users/yourLocalPath>/Downloads/downloadedFile.txt" # The local path to save the file.
    
        download_file(signed_url, file_path)

Generate a presigned URL that allows object downloads using a custom domain name

The following sample code shows how to use a custom domain name to generate a presigned URL that allows HTTP GET requests:

import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line parameter parser and describe the purpose of the script: generate a presigned GET request.
parser = argparse.ArgumentParser(description="presign get object sample")

# Add the --region command-line parameter to specify the region in which the bucket is located. This parameter is required.
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
# Add the --bucket command-line parameter to specify the name of the bucket that stores the object. This parameter is required.
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# Add the --endpoint command-line parameter to specify the domain name that other services can use to access OSS. This parameter is optional.
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
# Add the --key command-line parameter to specify the key of the object (file) in OSS. This parameter is required.
parser.add_argument('--key', help='The name of the object.', required=True)

def main():
    # Parse the command-line parameters to obtain the specified values.
    args = parser.parse_args()

    # Load the authentication information required to access OSS from environment variables for identity verification.
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Use the default configurations of the SDK to create a configuration object and set the credential provider.
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider
    
    # Set the region property of the configuration object based on the command-line parameters.
    cfg.region = args.region

    # Set a custom domain name, such as "http://static.example.com".
    cfg.endpoint = "http://static.example.com"
    
    # Use a CNAME.
    cfg.use_cname = True

    # Use the preceding configurations to initialize the OSS client to interact with OSS.
    client = oss.Client(cfg)

    # Generate a presigned GET request.
    pre_result = client.presign(
        oss.GetObjectRequest(
            bucket=args.bucket,  # Specify the bucket name.
            key=args.key,        # Specify the object key.
        )
    )

    # Print the method, expiration time, and URL of the presigned request.
    print(f'method: {pre_result.method},'
          f' expiration: {pre_result.expiration.strftime("%Y-%m-%dT%H:%M:%S.000Z")},'
          f' url: {pre_result.url}'
    )

    # Print the signed headers of the presigned request.
    for key, value in pre_result.signed_headers.items():
        print(f'signed headers key: {key}, signed headers value: {value}')

# When this script is directly executed, call the main function to start the processing logic.
if __name__ == "__main__":
    main()  # The entry point of the script. The program flow starts here.

References

  • For the complete sample code that shows how to download an object using a presigned URL, see presigner_get_object.py.