Help Center> Object Storage Service> Python> Bucket-Related APIs (SDK for Python)> Obtaining Static Website Hosting for a Bucket (SDK for Python)
Updated on 2024-05-11 GMT+08:00

Obtaining Static Website Hosting for a Bucket (SDK for Python)

Function

You can host static website resources such as HTML web pages, flash files, as well as audio and video files in an OBS bucket, so that you can provide these hosted resources using the bucket's website endpoint to end users. Typical use cases include:

  • Redirecting all requests to another website
  • Redirecting specific requests

This API returns the static website hosting configuration of the bucket.

Restrictions

Method

ObsClient.getBucketWebsite(bucketName)

Request Parameters

Parameter

Type

Mandatory (Yes/No)

Description

bucketName

str

Yes

Explanation:

Bucket name

Restrictions:

  • A bucket name must be unique across all accounts and regions.
  • A bucket name:
    • Must be 3 to 63 characters long and start with a digit or letter. Lowercase letters, digits, hyphens (-), and periods (.) are allowed.
    • Cannot be formatted as an IP address.
    • Cannot start or end with a hyphen (-) or period (.).
    • Cannot contain two consecutive periods (..), for example, my..bucket.
    • Cannot contain periods (.) and hyphens (-) adjacent to each other, for example, my-.bucket or my.-bucket.
  • If you repeatedly create buckets of the same name in the same region, no error will be reported and the bucket properties comply with those set in the first creation request.

Default value:

None

Responses

Type

Description

GetResult

Explanation:

SDK common results

Table 1 GetResult

Parameter

Type

Description

status

int

Explanation:

HTTP status code

Value range:

A status code is a group of digits ranging from 2xx (indicating successes) to 4xx or 5xx (indicating errors). It indicates the status of a response. For more information, see Status Code.

Default value:

None

reason

str

Explanation:

Reason description.

Default value:

None

errorCode

str

Explanation:

Error code returned by the OBS server. If the value of status is less than 300, this parameter is left blank.

Default value:

None

errorMessage

str

Explanation:

Error message returned by the OBS server. If the value of status is less than 300, this parameter is left blank.

Default value:

None

requestId

str

Explanation:

Request ID returned by the OBS server

Default value:

None

indicator

str

Explanation:

Error indicator returned by the OBS server.

Default value:

None

hostId

str

Explanation:

Requested server ID. If the value of status is less than 300, this parameter is left blank.

Default value:

None

resource

str

Explanation:

Error source (a bucket or an object). If the value of status is less than 300, this parameter is left blank.

Default value:

None

header

list

Explanation:

Response header list, composed of tuples. Each tuple consists of two elements, respectively corresponding to the key and value of a response header.

Default value:

None

body

object

Explanation:

Result content returned after the operation is successful. If the value of status is larger than 300, this parameter value is null. The value varies with the API being called. For details, see Bucket-Related APIs (SDK for Python) and Object-Related APIs (SDK for Python).

Default value:

None

GetResult.body Type

Description

WebsiteConfiguration

Explanation:

Website hosting settings of a bucket

Table 2 WebsiteConfiguration

Parameter

Type

Mandatory (Yes/No)

Description

redirectAllRequestTo

RedirectAllRequestTo

No if used as a request parameter

Explanation:

Redirection rules for all requests. For details, see Table 3.

indexDocument

IndexDocument

No if used as a request parameter

Explanation:

Default page configuration. For details, see Table 4.

errorDocument

ErrorDocument

No if used as a request parameter

Explanation:

Error page configuration. For details, see Table 5.

routingRules

list of RoutingRule

No if used as a request parameter

Explanation:

List of routing rules. For details, see Table 6.

  • errorDocument, indexDocument, and routingRules must be used together and they cannot be used with redirectAllRequestsTo.
  • When errorDocument, indexDocument, and routingRules are used together, routingRules can be left blank.
  • You must specify either the combo of fields ErrorDocument, IndexDocument, and RoutingRules, or the RedirectAllRequestsTo field.
Table 3 RedirectAllRequestTo

Parameter

Type

Mandatory (Yes/No)

Description

hostName

str

Yes if used as a request parameter

Explanation:

Host name used for redirection, for example, www.example.com

Restrictions:

The host name must comply with the host name rules.

Default value:

None

protocol

str

No if used as a request parameter

Explanation:

Protocol used for redirection

Value range:

  • http
  • https

Default value:

None

Table 4 IndexDocument

Parameter

Type

Mandatory (Yes/No)

Description

suffix

str

Yes if used as a request parameter

Explanation:

Suffix that is appended to the request for a directory. For example, if the suffix is index.html and you request samplebucket/images/, the returned data will be for the object named images/index.html in the bucket samplebucket.

Value range:

This parameter can neither be left blank nor contain slashes (/).

Default value:

None

Table 5 ErrorDocument

Parameter

Type

Mandatory (Yes/No)

Description

key

str

No if used as a request parameter

Explanation:

Object name to use when a 4XX error occurs. This parameter specifies the webpage to display when an error occurs.

Value range:

The value must contain 1 to 1,024 characters.

Default value:

None

Table 6 RoutingRule

Parameter

Type

Mandatory (Yes/No)

Description

condition

Condition

No if used as a request parameter

Explanation:

Conditions that must be met for the specified redirect to apply

Value range:

See Table 7.

Default value:

None

redirect

Redirect

Yes if used as a request parameter

Explanation:

Details about the redirection. For details, see Table 8.

Default value:

None

Table 7 Condition

Parameter

Type

Mandatory (Yes/No)

Description

keyPrefixEquals

str

No if used as a request parameter

Explanation:

Object name prefix for the redirection to take effect. If the name prefix of the requested object is the same as the value specified for this parameter, the redirection rule takes effect.

For example, to redirect the requests for the object ExamplePage.html, set KeyPrefixEquals to ExamplePage.html.

Restrictions:

This parameter cannot be used together with httpErrorCodeReturnedEquals.

Value range:

The value must contain 1 to 1,024 characters.

Default value:

None

httpErrorCodeReturnedEquals

int

No if used as a request parameter

Explanation:

HTTP error code for the redirection to take effect. If there is an error, and the error code returned is the same as the value specified for this parameter, the redirection rule takes effect.

For example, if you want to redirect requests to NotFound.html when HTTP error code 404 is returned, set httpErrorCodeReturnedEquals to 404 in Condition, and set ReplaceKeyWith to NotFound.html in Redirect.

Restrictions:

This parameter cannot be used together with keyPrefixEquals.

Value range:

See Error Codes.

Default value:

None

Table 8 Redirect

Parameter

Type

Mandatory (Yes/No)

Description

protocol

str

No if used as a request parameter

Explanation:

Protocol used for redirection

Value range:

  • http
  • https

Default value:

None

hostName

str

No if used as a request parameter

Explanation:

Host name used for redirection

Default value:

None

replaceKeyPrefixWith

str

No if used as a request parameter

Explanation:

Object name prefix used in the redirection request

Value range:

The value must contain 1 to 1,024 characters.

Default value:

None

replaceKeyWith

str

No if used as a request parameter

Explanation:

Object name used in the redirection request

Restrictions:

This parameter cannot be used together with replaceKeyPrefixWith.

Value range:

The value must contain 1 to 1,024 characters.

Default value:

None

httpRedirectCode

int

No if used as a request parameter

Explanation:

HTTP status code in the response to the redirect request. For details, see Status Code.

Default value:

None

Code Examples

This example returns the static website hosting configuration of bucket examplebucket.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
from obs import ObsClient
import os
import traceback

# Obtain an AK and SK pair using environment variables or import the AK and SK pair in other ways. Using hard coding may result in leakage.
# Obtain an AK and SK pair on the management console. For details, see https://support.huaweicloud.com/intl/en-us/usermanual-ca/ca_01_0003.html.
ak = os.getenv("AccessKeyID")
sk = os.getenv("SecretAccessKey")
# (Optional) If you use a temporary AK and SK pair and a security token to access OBS, obtain them from environment variables.
security_token = os.getenv("SecurityToken")
# Set server to the endpoint corresponding to the bucket. Here uses CN-Hong Kong as an example. Replace it with the one in use.
server = "https://obs.ap-southeast-1.myhuaweicloud.com" 

# Create an obsClient instance.
# If you use a temporary AK and SK pair and a security token to access OBS, you must specify security_token when creating an instance.
obsClient = ObsClient(access_key_id=ak, secret_access_key=sk, server=server)
try:
    bucketName="examplebucket"
    # Obtain the website configuration of the bucket.
    resp = obsClient.getBucketWebsite(bucketName)
    # If status code 2xx is returned, the API is called successfully. Otherwise, the API call fails.
    if resp.status < 300:
        print('Get Bucket Website Succeeded')
        print('requestId:', resp.requestId)
        if resp.body.redirectAllRequestTo:
            print('redirectAllRequestTo.hostName:', resp.body.redirectAllRequestTo.hostName,
                  ',redirectAllRequestTo.protocol:', resp.body.redirectAllRequestTo.protocol)
        if resp.body.indexDocument:
            print('indexDocument.suffix:', resp.body.indexDocument.suffix)
        if resp.body.errorDocument:
            print('errorDocument.key:', resp.body.errorDocument.key)
        if resp.body.routingRules:
            index = 1
            for rout in resp.body.routingRules:
                print('routingRule[', index, ']:')
                index += 1
                print('condition.keyPrefixEquals:', rout.condition.keyPrefixEquals,
                      ',condition.httpErrorCodeReturnedEquals:', rout.condition.httpErrorCodeReturnedEquals)
                print('redirect.protocol:', rout.redirect.protocol, ',redirect.hostName:', rout.redirect.hostName,
                      ',redirect.replaceKeyPrefixWith:', rout.redirect.replaceKeyPrefixWith,
                      ',redirect.replaceKeyWith:', rout.redirect.replaceKeyWith, ',redirect.httpRedirectCode:',
                      rout.redirect.httpRedirectCode)
    else:
        print('Get Bucket Website Failed')
        print('requestId:', resp.requestId)
        print('errorCode:', resp.errorCode)
        print('errorMessage:', resp.errorMessage)
except:
    print('Get Bucket Website Failed')
    print(traceback.format_exc())