django boto3:NoCredentialsError - 无法找到凭据 [英] django boto3: NoCredentialsError -- Unable to locate credentials

查看:2574
本文介绍了django boto3:NoCredentialsError - 无法找到凭据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的django项目中使用 boto3 将文件上传到Amazon S3。凭证在 settings.py 中定义:

  AWS_ACCESS_KEY = xxxxxxxx 
AWS_SECRET_KEY = xxxxxxxx
S3_BUCKET = xxxxxxx

视图中。 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')

系统抱怨无法找到凭据。我有两个问题:



(a)似乎我应该创建一个凭据文件〜/ .aws / credentials 。但是在django项目中,我该怎么做呢?



(b)s3方法 upload_file 文件路径/名称作为其第一个参数。可以通过表单输入元素< input type =filename =fileToUpload> 获取文件流?

解决方案

这是我直接上传的内容,希望能提供一些帮助。

  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)
除了S3CreateError为e :
bucket = conn.get_bucket(settings.S3_BUCKET)

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

不确定(a),但是django在文件管理方面非常灵活。关于(b)您还可以登录上传,并直接从客户端进行,以减少带宽使用,这也是相当偷偷和安全的。您需要使用一些JavaScript来管理上传。如果你想要细节,我可以在这里加入。


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">?

解决方案

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.

这篇关于django boto3:NoCredentialsError - 无法找到凭据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆