django boto3: NoCredentialsError — Unable to locate credentials

孤者浪人 提交于 2019-12-30 19:56:41

问题


I am trying to use boto3 in my django project to upload files to Amazon S3. Credentials are defined in settings.py:

AWS_ACCESS_KEY = xxxxxxxx
AWS_SECRET_KEY = xxxxxxxx
S3_BUCKET = xxxxxxx

In 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. I have two questions:

(a) It seems that I am supposed to create a credential file ~/.aws/credentials. But in a django project, where do I have to put it?

(b) The s3 method upload_file takes a file path/name as its first argument. Is it possible that I provide a file stream obtained by a form input element <input type="file" name="fileToUpload">?


回答1:


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.

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. You need to use some JavaScript to manage the upload. If you want details I can include them here.



来源:https://stackoverflow.com/questions/31268177/django-boto3-nocredentialserror-unable-to-locate-credentials

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!