经过几天对该主题的研究,我来到这里,我有一个 Django 课程:问题,管理员可以创建一个问题:他必须为每个项目输入一个“标题”和一些“项目”+ 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] 无效参数:'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 不是空的!
感谢您阅读这个大问题,如果您能帮助我,我将不胜感激!
** 编辑 **
为了获得一个非空文件,我删除了 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() 得到了一个意外的关键字参数“ExtraArgs”