您可以將儲存空間配置成靜態網站託管模式。配置生效後,訪問網站相當於訪問儲存空間,並且能夠自動跳轉至指定的索引頁面和錯誤頁面。
更多關於靜態網站託管的介紹,請參見開發指南中的配置靜態網站託管。
設定靜態網站託管
以下代碼用於設定靜態網站託管:
# -*- coding: utf-8 -*-
import oss2
from oss2.models import BucketWebsite
# 阿里雲主帳號AccessKey擁有所有API的存取權限,風險很高。強烈建議您建立並使用RAM帳號進行API訪問或日常運維,請登入 https://ram.console.aliyun.com 建立RAM帳號。
auth = oss2.Auth('<yourAccessKeyId>', '<yourAccessKeySecret>')
# Endpoint以杭州為例,其它Region請按實際情況填寫。
bucket = oss2.Bucket(auth, 'http://oss-cn-hangzhou.aliyuncs.com', '<yourBucketName>')
# 開啟靜態網站託管模式,並把索引頁面設定為index.html,404錯誤版面設定為error.html。
bucket.put_bucket_website(BucketWebsite('index.html', 'error.html'))
查看靜態網站託管配置
以下代碼用於查看靜態網站託管配置:
# -*- coding: utf-8 -*-
import oss2
# 阿里雲主帳號AccessKey擁有所有API的存取權限,風險很高。強烈建議您建立並使用RAM帳號進行API訪問或日常運維,請登入 https://ram.console.aliyun.com 建立RAM帳號。
auth = oss2.Auth('<yourAccessKeyId>', '<yourAccessKeySecret>')
# Endpoint以杭州為例,其它Region請按實際情況填寫。
bucket = oss2.Bucket(auth, 'http://oss-cn-hangzhou.aliyuncs.com', '<yourBucketName>')
try:
# 當靜態網站託管模式沒有開啟時,get_bucket_website會拋出NoSuchWebsite異常。
website = bucket.get_bucket_website()
print('Index file is {0}, error file is {1}'.format(website.index_file, website.error_file))
except oss2.exceptions.NoSuchWebsite as e:
print('Website is not configured, request_id={0}'.format(e.request_id))
刪除靜態網站託管配置
以下代碼用於刪除靜態網站託管配置:
# -*- coding: utf-8 -*-
import oss2
# 阿里雲主帳號AccessKey擁有所有API的存取權限,風險很高。強烈建議您建立並使用RAM帳號進行API訪問或日常運維,請登入 https://ram.console.aliyun.com 建立RAM帳號。
auth = oss2.Auth('<yourAccessKeyId>', '<yourAccessKeySecret>')
# Endpoint以杭州為例,其它Region請按實際情況填寫。
bucket = oss2.Bucket(auth, 'http://oss-cn-hangzhou.aliyuncs.com', '<yourBucketName>')
bucket.delete_bucket_website()