简体   繁体   English

django boto3:NoCredentialsError - 无法找到凭据

[英]django boto3: NoCredentialsError — Unable to locate credentials

I am trying to use boto3 in my django project to upload files to Amazon S3. 我正在尝试在我的django项目中使用boto3将文件上传到Amazon S3。 Credentials are defined in settings.py : 凭据在settings.py中定义:

AWS_ACCESS_KEY = xxxxxxxx
AWS_SECRET_KEY = xxxxxxxx
S3_BUCKET = xxxxxxx

In views.py : views.py

import boto3

s3 = boto3.client('s3')
path = os.path.dirname(os.path.realpath(__file__))
s3.upload_file(path+'/myphoto.png', S3_BUCKET, 'myphoto.png')

The system complains about Unable to locate credentials . 系统抱怨Unable to locate credentials I have two questions: 我有两个问题:

(a) It seems that I am supposed to create a credential file ~/.aws/credentials . (a)似乎我应该创建一个凭证文件~/.aws/credentials But in a django project, where do I have to put it? 但在django项目中,我该把它放在哪里?

(b) The s3 method upload_file takes a file path/name as its first argument. (b)s3方法upload_file将文件路径/名称作为其第一个参数。 Is it possible that I provide a file stream obtained by a form input element <input type="file" name="fileToUpload"> ? 是否有可能提供由表单输入元素<input type="file" name="fileToUpload">获得的文件流?

This is what I use for a direct upload, i hope it provides some assistance. 这是我用于直接上传的内容,我希望它提供一些帮助。

import boto
from boto.exception import S3CreateError
from boto.s3.connection import S3Connection

conn = S3Connection(settings.AWS_ACCESS_KEY,
                    settings.AWS_SECRET_KEY,
                    is_secure=True)
try:
    bucket = conn.create_bucket(settings.S3_BUCKET)
except S3CreateError as e:
    bucket = conn.get_bucket(settings.S3_BUCKET)

k = boto.s3.key.Key(bucket)
k.key = filename
k.set_contents_from_filename(filepath)

Not sure about (a) but django is very flexible with file management. 不确定(a)但django在文件管理方面非常灵活。

Regarding (b) you can also sign the upload and do it directly from the client to reduce bandwidth usage, its quite sneaky and secure too. 关于(b)您也可以签署上传并直接从客户端进行操作以减少带宽使用,它也非常狡猾和安全。 You need to use some JavaScript to manage the upload. 您需要使用一些JavaScript来管理上传。 If you want details I can include them here. 如果你想要细节我可以在这里包括它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM