This commit is contained in:
Nanten
2025-02-20 15:40:24 +09:00
parent bb80afbf8e
commit dd132aabbe
+37 -18
View File
@@ -14,10 +14,22 @@ load_dotenv()
# .envファイルからCloudflare R2のエンドポイントを読み込む
ENDPOINT = os.getenv('R2_ENDPOINT')
def validate_environment():
"""環境変数の確認"""
required_vars = [
'R2_ENDPOINT',
'R2_ACCESS_KEY_ID',
'R2_SECRET_ACCESS_KEY',
'R2_BUCKET_NAME',
'R2_CUSTOM_URL'
]
missing_vars = [var for var in required_vars if not os.getenv(var)]
if missing_vars:
raise ValueError(f"Missing required environment variables: {', '.join(missing_vars)}")
def upload_to_r2(image_path):
"""
画像をCloudflare R2にアップロードする。
Args:
image_path (str): アップロードする画像のパス。
@@ -27,6 +39,8 @@ def upload_to_r2(image_path):
"""
try:
validate_environment()
# R2のクライアントを作成
s3 = boto3.client(
's3',
@@ -50,26 +64,31 @@ def upload_to_r2(image_path):
# アップロードされた画像のURLを返す
return f"{os.getenv('R2_CUSTOM_URL')}{random_filename}"
except ValueError as e:
print(f"Configuration error: {e}")
return None
except boto3.exceptions.BotoServerError as e:
print(f"R2 server error: {e}")
return None
except boto3.exceptions.ClientError as e:
print(f"R2 client error: {e}")
return None
except Exception as e:
print(f"Error uploading image: {e}")
print(f"Unexpected error: {e}")
return None
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Upload an image to Cloudflare R2.')
parser.add_argument('--image-path', required=True, help='Path to the image file.')
parser = argparse.ArgumentParser(description='Upload images to Cloudflare R2.')
parser.add_argument('--images-path', nargs='+', required=True, help='Paths to image files.')
args = parser.parse_args()
image_path = args.image_path
for image_path in args.images_path:
if not os.path.exists(image_path):
print(f"Error: Image not found at {image_path}. Skipping.")
continue
# 画像が存在するか確認
if not os.path.exists(image_path):
print(f"Error: Image not found at {image_path}")
exit(1)
# R2に画像をアップロード
image_url = upload_to_r2(image_path)
if image_url:
print(f"{image_url}")
else:
print("Image upload failed.")
image_url = upload_to_r2(image_path)
if image_url:
print(image_url)
else:
print(f"Image upload failed for {image_path}.")