Shun Yamada
Shun Yamada

Reputation: 979

Can't put image filed to Amazon s3 in Python Flask

I want to upload an image file on Flask + Amazon s3 but this error occurs:

enter image description here

Actually I have s3 to be in public. But after uploading the image, this can't get...

My code:

import os

import io
import boto3
from flask import Flask, flash, request, redirect, url_for, current_app
from werkzeug.utils import secure_filename

basedir = os.path.abspath(os.path.dirname(__file__))

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in current_app.config["ALLOWED_EXTENSIONS"]

def uploads_file(request):
    file = request.files['file']
    if file.filename == '':
        flash('No selected file')
        return redirect(request.url)
    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        s3_bucket = current_app.config['S3_BUCKET']
        s3_dir = current_app.config['S3_DIR']
        s3 = boto3.client('s3', region_name = 'us-west-1')
        response = s3.put_object(
            Body = io.BufferedReader(file).read(),
            Bucket = s3_bucket,
            Key = f'{s3_dir}/{filename}'
        )
        return filename

I have added app/.aws/credentials.

aws_access_key_id=XXXXXXXXXX
aws_secret_access_key=XXXXXXXXXXXXXXXXX

Upvotes: 0

Views: 264

Answers (1)

dmitrybelyakov
dmitrybelyakov

Reputation: 3864

You can also pass credentials when you create s3 client. Something like this should work:

client = boto3.client(
    's3',
    aws_access_key_id=key_id,
    aws_secret_access_key=access_secret,
    region_name='us-west-1',
)

with open(path, 'rb') as src:
    client.put_object(
        ACL='public-read',
        Bucket=bucket_name,
        Key=filename,
        Body=src
    )

Upvotes: 1

Related Questions