boto3 與 django-storages:如何在 Django 中對接 AWS S3

更新日期: 2024 年 12 月 18 日

在開發 Django 專案時,若需要將檔案儲存至 AWS S3,你會遇到兩個重要工具:boto3django-storages

這兩者雖然功能不同,但相輔相成,協助你輕鬆完成檔案上傳與管理。


boto3:AWS 與 Python 的官方溝通工具

boto3 是 AWS 官方提供的 Python SDK,專門用來讓 Python 程式與 AWS 服務(如 S3、EC2、DynamoDB 等)進行互動。

它的工作範圍屬於 低層次,也就是說,你需要自己撰寫程式碼來處理每一個細節,例如:

  • 建立 S3 Bucket
  • 檔案上傳與下載
  • 設定檔案權限
  • 驗證 AWS 帳戶

boto3 範例:自行寫邏輯上傳檔案

import boto3
from botocore.exceptions import NoCredentialsError

# 設定 S3 參數
s3 = boto3.client('s3', aws_access_key_id='your-key', aws_secret_access_key='your-secret')

# 上傳檔案到 S3
try:
    s3.upload_file('local_file.txt', 'my_bucket', 'file_in_s3.txt')
    print("Upload Successful")
except FileNotFoundError:
    print("The file was not found")
except NoCredentialsError:
    print("Credentials not available")

這段程式碼會將 local_file.txt 上傳到指定的 S3 bucket,但需要手動撰寫各項細節,如帳號驗證與檔案位置。


django-storages:讓 Django 無縫整合 S3

django-storages 是 Django 的擴展工具,目的是將外部儲存服務(如 AWS S3)輕鬆整合進 Django 專案中。

它本身是一個 高階封裝工具,底層依賴 boto3 進行操作,但提供了更符合 Django 框架的使用方式。

django-storages 範例:快速上傳檔案

設定好 AWS 參數後,在 settings.py 加入以下設定:

DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
AWS_ACCESS_KEY_ID = 'your-key'
AWS_SECRET_ACCESS_KEY = 'your-secret'
AWS_STORAGE_BUCKET_NAME = 'your-bucket-name'

接著,在程式中直接使用 Django 提供的 檔案存儲 API

from django.core.files.storage import default_storage
from django.core.files.base import ContentFile

# 上傳檔案
default_storage.save('uploads/my_file.txt', ContentFile('文件內容'))

# 取得檔案 URL
file_url = default_storage.url('uploads/my_file.txt')
print(file_url)

只需幾行程式碼,django-storages 就會幫你將檔案上傳到 AWS S3,並自動處理權限、驗證等繁瑣細節。


boto3 與 django-storages 的關係

簡單類比

  • boto3:像是 AWS 的「工具箱」,你需要親自組裝並設定每個細節。
  • django-storages:像是一個「一鍵工具」,它幫你把複雜的底層邏輯封裝好,你只需設定參數即可輕鬆使用。

如何安裝 boto3 與 django-storages

要使用 django-storages,必須同時安裝 boto3,因為 django-storages 依賴 boto3 與 AWS 服務進行互動。

執行以下指令安裝兩者:

pip install boto3 django-storages

常見錯誤:未安裝 boto3

若只安裝 django-storages,但未安裝 boto3,你會遇到類似以下錯誤:

ModuleNotFoundError: No module named 'boto3'

這是因為 django-storages 在運行時會呼叫 boto3 進行底層操作,若找不到 boto3 模組,便會出錯。


結論

  • boto3 是 AWS 與 Python 的官方工具,提供完整且低層次的操作能力。
  • django-storages 是 Django 的擴展工具,封裝了 boto3 的功能,讓你能以更簡單的方式在 Django 中整合 S3。

即使使用 django-storages,你仍需安裝 boto3,因為兩者是 合作運作 的。

如果你追求靈活性與高自定義度,使用 boto3;如果你想要快速整合 AWS S3,選擇 django-storages

透過這兩個工具,你可以輕鬆將檔案儲存整合到 AWS S3,提升 Django 專案的擴展性與效率。

Similar Posts