Question:
I am trying to upload an image to S3 through Python. My code looks like this:
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 |
import os from PIL import Image import boto from boto.s3.key import Key def upload_to_s3(aws_access_key_id, aws_secret_access_key, file, bucket, key, callback=None, md5=None, reduced_redundancy=False, content_type=None): conn = boto.connect_s3(aws_access_key_id, aws_secret_access_key) bucket = conn.get_bucket(bucket, validate=False) k = Key(bucket) k.key = key k.set_contents_from_file(file) AWS_ACCESS_KEY = "...." AWS_ACCESS_SECRET_KEY = "....." filename = "images/image_0.jpg" file = Image.open(filename) key = "image" bucket = 'images' upload_to_s3(AWS_ACCESS_KEY, AWS_ACCESS_SECRET_KEY, file, bucket, key) |
I am getting this error message:
1 2 3 4 5 6 |
S3ResponseError: S3ResponseError: 400 Bad Request InvalidRequest |
This code is based on the tutorial from this website: http://stackabuse.com/example-upload-a-file-to-aws-s3/
I have tried k.set_contents_from_file as well as k.set_contents_from_filename, but both don’t seem to work for me.
The error says something about using AWS4-HMAC-SHA256, but I am not sure how to do that. Is there another way to solve this problem besides using AWS4-HMAC-SHA256? If anyone can help me out, I would really appreciate it.
Thank you!
Answer:
Just use:
1 2 3 4 5 6 |
import boto3 client = boto3.client('s3', region_name='us-west-2') client.upload_file('images/image_0.jpg', 'mybucket', 'image_0.jpg') |
Try to avoid putting your credentials in the code. Instead:
- If you are running the code from an Amazon EC2 instance, simply assign an IAM Role to the instance with appropriate permissions. The credentials will automatically be used.
- If you are running the code on your own computer, use the AWS Command-Line Interface (CLI)
aws configure
command to store your credentials in a file, which will be automatically used by your code.