Scale Your Django App: Store Static and Media Files on DigitalOcean Spaces

Поделиться
HTML-код
  • Опубликовано: 29 ноя 2024

Комментарии • 3

  • @isis_araujo
    @isis_araujo 2 месяца назад

    Good evening! I am from Brazil, how are you? Could you share your code?

    • @PostdocLife
      @PostdocLife  2 месяца назад

      Do you mean the upload_bucket.py? Here it is: import boto3
      import os
      import click
      session = boto3.session.Session()
      s3 = session.client('s3',
      region_name='nyc3',
      endpoint_url='nyc3.digitaloceanspaces.com',
      aws_access_key_id=os.getenv('SPACES_KEY'),
      aws_secret_access_key=os.getenv('SPACES_SECRET'))
      @click.command()
      @click.option('--bucket',
      default='your-bucket-name',
      help='The name of the S3 bucket to upload to')
      @click.option('--prefix',
      default='media/',
      help='The prefix (folder) to upload to inside the bucket')
      @click.option('--local-dir',
      default='./media',
      help='The local directory to upload from')
      def upload_folder_to_s3(bucket: str, prefix: str, local_dir: str):
      """Upload a folder from local machine to an S3 bucket or DigitalOcean Space"""
      if not os.path.exists(local_dir):
      raise Exception(f"The local directory {local_dir} does not exist")
      for root, dirs, files in os.walk(local_dir):
      for file in files:
      local_file_path = os.path.join(root, file)
      relative_path = os.path.relpath(local_file_path, local_dir)
      s3_key = os.path.join(prefix, relative_path).replace("\\", "/")
      print(f"Uploading {local_file_path} to {s3_key} in bucket {bucket}")
      s3.upload_file(local_file_path, bucket, s3_key)
      if __name__ == '__main__':
      upload_folder_to_s3()