我试图用python在s3空间保存一个mp3文件,但得到了一个空文件

2024-04-25 23:10:02 发布

您现在位置:Python中文网/ 问答频道 /正文

经过几天的研究,我来到这里, 我有一个Django类:Question,管理员可以创建一个问题:他必须为每个项目输入一个“标题”和一些“项目”+True或False。我想把问题的“标题”作为一个mp3文件,所以我使用gTTS(谷歌文本到语音),当我在本地使用它时,它也可以工作

 if(sender == Question and kwargs['update_fields'] == None):

    myQuestion = kwargs['instance']
    output = gTTS(myQuestion.title, lang="fr")
    mySound = './media/questionsSound/Question'+str(myQuestion.id)+'.mp3'
    output.save(mySound)

现在我想把这些mp3文件保存在s3空间中,因为我有很多应用程序可以调用它们

因此,在第一次,我只是试图用我的桶的路径替换我的声音路径,但我得到了以下错误消息:

[Errno 22] Invalid argument: 'https://[mySpaceName].fra1.digitaloceanspaces.com/[myBucketName]/questionSound/Question95.mp3'

这是第一个对我来说毫无意义的问题,因为URL存在。我用拖放的文件尝试了它。 因此,我试图找到一种解决方法,并决定将文件保存在原始文件夹./media/questionsSoud...中,然后将其上载到s3空间:

    import boto3
    from boto3 import session
    from botocore.client import Config
    from boto3.s3.transfer import S3Transfer

    session = session.Session()
    client = session.client('s3', region_name='fra1', endpoint_url=settings.AWS_S3_ENDPOINT_URL, aws_access_key_id=settings.AWS_ACCESS_KEY_ID, aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY)
    transfer = S3Transfer(client)

    transfer.upload_file(mySound, settings.AWS_STORAGE_BUCKET_NAME, "testhello.mp3")
    response = client.put_object(ACL='public-read', Bucket=settings.AWS_STORAGE_BUCKET_NAME, Key='testhello.mp3')
    

现在问题不同了:我的共享空间中有一个文件,但它是“二进制/八位字节流”类型,而不是“音频/mpeg”,并且它是绝对空的(我下载并尝试了它),即使mySound不是空的

如果你能读到这个大问题,我将非常感激你能帮助我

** EDIT **

为了得到一个非空文件,我删除了put_object()行 但是我仍然得到了“二进制/八位字节”的内容类型,所以我在GitHub上找到了类似于函数upload_file()的内容

    mimetype, _ = mimetypes.guess_type(mySound)
    print(mimetype)
    if mimetype is None:
        raise Exception("Failed to guess mimetype")
    transfer.upload_file(mySound, settings.AWS_STORAGE_BUCKET_NAME, "testhello.mp3", ExtraArgs={
            "ContentType": mimetype
        })

但是我得到了这个错误

upload_file() got an unexpected keyword argument 'ExtraArgs'


Tags: 文件importclientawssettingss3sessionmp3
2条回答

谢谢你的帮助

对于使用DigitalOcean的用户来说,这最终不是什么大问题,您可以在前端应用程序中调用“二进制/八位字节流”的url,它实际上被视为音频文件

您的put_object()命令没有指定要存储的数据,因此它正在创建一个零长度的文件尝试用put_object()删除您的行,它应该可以工作,因为前一行可能已经上载了文件

我不熟悉使用Digital Ocean,但下面是您通常用于S3的代码:

s3_client = boto3.client('s3')

s3_client.upload_file('./file.mp3', 'mybucket', 'file.mp3', ExtraArgs={'ACL': 'public-read', 'Content-Type': 'audio/mpeg'})

相关问题 更多 >