更新时间:2024-07-02 GMT+08:00

静态网站托管(Python SDK)

功能说明

支持将静态网站文件上传至OBS的桶中作为对象,并对这些对象赋予公共读权限,然后将该桶配置成静态网站托管模式,以实现在OBS上托管静态网站的目的。第三方用户在访问静态托管网站的时候,实际上是在访问OBS的桶中的对象。在使用静态网站托管功能时,OBS还支持配置请求重定向,通过重定向配置可以将特定的请求或所有请求实施重定向。

更多关于静态网站托管的内容请参考静态网站托管

接口约束

网站文件托管

1.将网站文件上传至OBS的桶中,并设置对象MIME类型。

2.设置对象访问权限为公共读。

3.通过浏览器访问对象

本示例用于上传网站html文件,并设置对象公共读权限来实现网站文件托管:

 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
51
52
from obs import ObsClient
import os
from obs import PutObjectHeader
from obs import HeadPermission
import traceback

# 推荐通过环境变量获取AKSK,这里也可以使用其他外部引入方式传入,如果使用硬编码可能会存在泄露风险。
# 您可以登录访问管理控制台获取访问密钥AK/SK,获取方式请参见https://support.huaweicloud.com/intl/zh-cn/usermanual-ca/ca_01_0003.html。
ak = os.getenv("AccessKeyID")
sk = os.getenv("SecretAccessKey")
# 【可选】如果使用临时AKSK和SecurityToken访问OBS,则同样推荐通过环境变量获取
security_token = os.getenv("SecurityToken")
# server填写Bucket对应的Endpoint, 这里以中国-香港为例,其他地区请按实际情况填写。
server = "https://obs.ap-southeast-1.myhuaweicloud.com"
# 创建obsClient实例
# 如果使用临时AKSK和SecurityToken访问OBS,需要在创建实例时通过security_token参数指定securityToken值
obsClient = ObsClient(access_key_id=ak, secret_access_key=sk, server=server)
try:
    bucketName = 'bucketname'
    # 设置网站文件名
    objectKey = 'test.html'
    # 本地html网站文件路径
    file_path = 'localfile.html'
    headers = PutObjectHeader()
    # 设置对象MIME类型
    headers.contentType = 'text/html'

    # 上传对象
    resp = obsClient.putFile(bucketName, objectKey, file_path, headers=headers)

    # 返回码为2xx时,接口调用成功,否则接口调用失败
    if resp.status < 300:
        print('Put File Succeeded')
        print('requestId:', resp.requestId)
        # 设置对象访问权限为公共读
        resp2 = obsClient.setObjectAcl(bucketName, objectKey, aclControl=HeadPermission.PUBLIC_READ)
        if resp2.status < 300:
            print('Set Object Acl Succeeded')
            print('requestId:', resp2.requestId)
        else:
            print('Set Object Acl Failed')
            print('requestId:', resp2.requestId)
            print('errorCode:', resp2.errorCode)
            print('errorMessage:', resp2.errorMessage)
    else:
        print('Put File Failed')
        print('requestId:', resp.requestId)
        print('errorCode:', resp.errorCode)
        print('errorMessage:', resp.errorMessage)
except:
    print('Put File Failed')
    print(traceback.format_exc())

上例中可以使用https://bucketname.your-endpoint/test.html在浏览器直接访问托管的文件。

设置托管配置

本示例用于设置名为examplebucket的桶website配置。

 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
from obs import ObsClient
from obs import WebsiteConfiguration
from obs import IndexDocument
from obs import ErrorDocument
from obs import RoutingRule
from obs import Condition
from obs import Redirect
import os
import traceback

# 推荐通过环境变量获取AKSK,这里也可以使用其他外部引入方式传入,如果使用硬编码可能会存在泄露风险。
# 您可以登录访问管理控制台获取访问密钥AK/SK,获取方式请参见https://support.huaweicloud.com/intl/zh-cn/usermanual-ca/ca_01_0003.html。
ak = os.getenv("AccessKeyID")
sk = os.getenv("SecretAccessKey")
# 【可选】如果使用临时AKSK和SecurityToken访问OBS,则同样推荐通过环境变量获取
security_token = os.getenv("SecurityToken")
# server填写Bucket对应的Endpoint, 这里以中国-香港为例,其他地区请按实际情况填写。
server = "https://obs.ap-southeast-1.myhuaweicloud.com"
# 创建obsClient实例
# 如果使用临时AKSK和SecurityToken访问OBS,需要在创建实例时通过security_token参数指定securityToken值
obsClient = ObsClient(access_key_id=ak, secret_access_key=sk, server=server)
try:
    # 配置错误页面,指定当4XX错误出现时返回的页面。
    errorDocument = ErrorDocument(key='error.html')
    # 配置默认页面
    indexDocument = IndexDocument(suffix='index.html')
    # 指定重定向规则:当状态码为404时重定向到NotFound.html
    routingRule1 = RoutingRule(condition=Condition(httpErrorCodeReturnedEquals=404),
                               redirect=Redirect(protocol='http', replaceKeyWith='NotFound.html'))
    # 设置重定向规则,格式为列表,可设置多条
    routingRules = [routingRule1]
    bucketName = "examplebucket"
    # 设置桶website配置
    resp = obsClient.setBucketWebsite(bucketName,
                                      WebsiteConfiguration(errorDocument=errorDocument, indexDocument=indexDocument,
                                                           routingRules=routingRules))

    # 返回码为2xx时,接口调用成功,否则接口调用失败
    if resp.status < 300:
        print('Set Bucket Website Succeeded')
        print('requestId:', resp.requestId)
    else:
        print('Set Bucket Website Failed')
        print('requestId:', resp.requestId)
        print('errorCode:', resp.errorCode)
        print('errorMessage:', resp.errorMessage)
except:
    print('Set Bucket Website Failed')
    print(traceback.format_exc())

本示例用于配置所有请求重定向:

 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
from obs import ObsClient
import os
import traceback
from obs import WebsiteConfiguration
from obs import RedirectAllRequestTo

# 推荐通过环境变量获取AKSK,这里也可以使用其他外部引入方式传入。如果使用硬编码可能会存在泄露风险
# 您可以登录访问管理控制台获取访问密钥AK/SK,获取方式请参见https://support.huaweicloud.com/intl/zh-cn/usermanual-ca/ca_01_0003.html
ak = os.getenv("AccessKeyID")
sk = os.getenv("SecretAccessKey")
# 【可选】如果使用临时AKSK和SecurityToken访问OBS,则同样推荐通过环境变量获取
security_token = os.getenv("SecurityToken")
# server填写Bucket对应的Endpoint, 这里以中国-香港为例,其他地区请按实际情况填写。
server = "https://obs.ap-southeast-1.myhuaweicloud.com" 
# 创建obsClient实例
# 如果使用临时AKSK和SecurityToken访问OBS,需要在创建实例时通过security_token参数指定securityToken值
obsClient = ObsClient(access_key_id=ak, secret_access_key=sk, server=server)
try:
    bucketName = 'bucketname'
    # 配置所有请求重定向
    resp = obsClient.setBucketWebsite(bucketName,
                                       WebsiteConfiguration(
                                           redirectAllRequestTo=RedirectAllRequestTo(hostName='www.example.com',
                                                                                     protocol='http')))
    if resp.status < 300:
        print('Set Bucket Website Succeeded')
        print('requestId:', resp.requestId)
    else:
        print('Set Bucket Website Failed')
        print('requestId:', resp.requestId)
        print('errorCode:', resp.errorCode)
        print('errorMessage:', resp.errorMessage)
except:
    print('Set Bucket Website Failed')
    print(traceback.format_exc())

查看托管配置

本示例用于获取名为examplebucket的桶website配置。

 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
from obs import ObsClient
import os
import traceback

# 推荐通过环境变量获取AKSK,这里也可以使用其他外部引入方式传入,如果使用硬编码可能会存在泄露风险。
# 您可以登录访问管理控制台获取访问密钥AK/SK,获取方式请参见https://support.huaweicloud.com/intl/zh-cn/usermanual-ca/ca_01_0003.html。
ak = os.getenv("AccessKeyID")
sk = os.getenv("SecretAccessKey")
# 【可选】如果使用临时AKSK和SecurityToken访问OBS,则同样推荐通过环境变量获取
security_token = os.getenv("SecurityToken")
# server填写Bucket对应的Endpoint, 这里以中国-香港为例,其他地区请按实际情况填写。
server = "https://obs.ap-southeast-1.myhuaweicloud.com"
# 创建obsClient实例
# 如果使用临时AKSK和SecurityToken访问OBS,需要在创建实例时通过security_token参数指定securityToken值
obsClient = ObsClient(access_key_id=ak, secret_access_key=sk, server=server)
try:
    bucketName="examplebucket"
    #获取桶website配置
    resp = obsClient.getBucketWebsite(bucketName)
    # 返回码为2xx时,接口调用成功,否则接口调用失败
    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())

清除托管配置

本示例用于删除名为examplebucket的桶website配置。

 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
from obs import ObsClient
import os
import traceback

# 推荐通过环境变量获取AKSK,这里也可以使用其他外部引入方式传入,如果使用硬编码可能会存在泄露风险。
# 您可以登录访问管理控制台获取访问密钥AK/SK,获取方式请参见https://support.huaweicloud.com/intl/zh-cn/usermanual-ca/ca_01_0003.html。
ak = os.getenv("AccessKeyID")
sk = os.getenv("SecretAccessKey")
# 【可选】如果使用临时AKSK和SecurityToken访问OBS,则同样推荐通过环境变量获取
security_token = os.getenv("SecurityToken")
# server填写Bucket对应的Endpoint, 这里以中国-香港为例,其他地区请按实际情况填写。
server = "https://obs.ap-southeast-1.myhuaweicloud.com" 
# 创建obsClient实例
# 如果使用临时AKSK和SecurityToken访问OBS,需要在创建实例时通过security_token参数指定securityToken值
obsClient = ObsClient(access_key_id=ak, secret_access_key=sk, server=server)
try:
    bucketName = "examplebucket"
    # 删除桶website配置
    resp = obsClient.deleteBucketWebsite(bucketName)

    # 返回码为2xx时,接口调用成功,否则接口调用失败
    if resp.status < 300:
        print('Delete Bucket Website Succeeded')
        print('requestId:', resp.requestId)
    else:
        print('Delete Bucket Website Failed')
        print('requestId:', resp.requestId)
        print('errorCode:', resp.errorCode)
        print('errorMessage:', resp.errorMessage)
except:
    print('Delete Bucket Website Failed')
    print(traceback.format_exc())

相关链接

  • 关于静态网站托管的API说明,请参见设置桶的网站配置
  • 更多关于静态网站托管的示例代码,请参见Github示例
  • 静态网站托管接口返回的错误码含义、问题原因及处理措施可参考OBS错误码