簡體   English   中英

FastAPI 上傳到 S3

[英]FastAPI Upload to S3

這幾天我一直在摸不着頭腦。 我仍然無法解決問題。 基本上,我只是想將 CSV 文件放在 LocalStack S3 中,但無法正常工作。

這是我的代碼片段:

api.py

from files import s3, AWS_S3_BUCKET_NAME, upload_file_to_bucket
    
@router.post('/api/customer/generate/upload',
                 name='Upload CSV to AWS S3 Bucket',
                 status_code=201)
    async def post_upload_user_csv(file_obj: UploadFile = File(...)):
        upload_obj = upload_file_to_bucket(s3_client=s3(),
                                           file_obj=file_obj.file,
                                           bucket=AWS_S3_BUCKET_NAME,
                                           folder='CSV',  # To Be updated
                                           object_name=file_obj.filename)
        if upload_obj:
            return JSONResponse(content="Object has been uploaded to bucket successfully",
                                status_code=status.HTTP_201_CREATED)
        else:
            raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                                detail="File could not be uploaded")

文件.py

import os
import boto3
import logging

from botocore.client import BaseClient
from botocore.exceptions import ClientError

AWS_ACCESS_KEY_ID = os.getenv('POSTGRES_HOST')
AWS_SECRET_KEY = os.getenv('AWS_SECRET_KEY')
AWS_S3_BUCKET_NAME = os.getenv('AWS_S3_BUCKET_NAME')


def s3() -> BaseClient:
    client = boto3.client(service_name='s3',
                          aws_access_key_id=AWS_ACCESS_KEY_ID,
                          aws_secret_access_key=AWS_SECRET_KEY,
                          endpoint_url='http://localhost:4566/')  # Use LocalStack Endpoint

    return client


def upload_file_to_bucket(s3_client, file_obj, bucket, folder, object_name=None):
    """Upload a file to an S3 bucket

    :param s3_client: S3 Client
    :param file_obj: File to upload
    :param bucket: Bucket to upload to
    :param folder: Folder to upload to
    :param object_name: S3 object name. If not specified then file_name is used
    :return: True if file was uploaded, else False
    """
    # If S3 object_name was not specified, use file_name
    if object_name is None:
        object_name = file_obj

    # Upload the file
    try:
        # with open("files", "rb") as f:
        s3_client.upload_fileobj(file_obj, bucket, f"{folder}/{object_name}")
    except ClientError as e:
        logging.error(e)
        return False
    return True

問題是 s3_client 需要先以二進制模式打開文件,然后才能將其上傳到 s3 存儲桶。 但是,這不能直接完成,文件需要臨時保存在 FastAPI 服務器上,但出於明顯的原因,我真的不想這樣做。

任何幫助都感激不盡。 先感謝您!

你能先顯示錯誤嗎? 基本上。 我以前做過。 直接從前端上傳一個文件到 aws-s3。 您可以嘗試將ContentType添加到 upload_fileobj. 這是我的代碼

 content_type = mimetypes.guess_type(fpath)[0]
 s3.Bucket(bucket_name).upload_fileobj(Fileobj=file, Key=file_path,
                                          ExtraArgs={"ACL": "public-read",
                                                     "ContentType": content_type})

另一種方式。 您應該嘗試將文件轉換為 io.BytesIO

 def s3_upload(self, file, file_path, bucket_name, width=None, height=None, make_thumb=False, make_cover=False):
    s3 = boto3.resource(service_name='s3')
    obj = BytesIO(self.image_optimize_from_buffer(file, width, height, make_thumb, make_cover))
    s3.Bucket(bucket_name).upload_fileobj(Fileobj=obj, Key=file_path,
                                          ExtraArgs={"ACL": "public-read", "ContentType": file.content_type})
    return f'https://{bucket_name}.s3.amazonaws.com/{file_path}'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM