【发布时间】:2017-11-13 15:19:17
【问题描述】:
我正在尝试通过 Chalice 将文件上传到我的 S3 存储桶(我目前正在使用它,对此仍然很陌生)。但是,我似乎无法正确处理。
我已正确设置 AWS,成功完成本教程会返回一些消息。然后我尝试做一些上传/下载,问题出现了。
s3 = boto3.resource('s3', region_name=<some region name, in this case oregon>)
BUCKET= 'mybucket'
UPLOAD_FOLDER = os.path.abspath('') # the file I wanna upload is in the same folder as my app.py, so I simply get the current folder name
@app.route('/upload/{file_name}', methods=['PUT'])
def upload_to_s3(file_name):
s3.meta.client.upload_file(UPLOAD_FOLDER+file_name, BUCKET, file_name)
return Response(message='upload successful',
status_code=200,
headers={'Content-Type': 'text/plain'}
)
请不要担心我如何设置文件路径,当然,除非这是问题所在。
我收到了错误日志:
没有这样的文件或目录:''
在这种情况下,file_name 只是mypic.jpg。
我想知道为什么没有收到 UPLOAD_FOLDER 部分。另外,作为参考,使用绝对路径似乎对 Chalice 会很麻烦(在测试时,我看到代码被移动到 /var/task/)
有人知道如何正确设置吗?
编辑:
完整的脚本
from chalice import Chalice, Response
import boto3
app = Chalice(app_name='helloworld') # I'm just modifying the script I used for the tutorial
s3 = boto3.client('s3', region_name='us-west-2')
BUCKET = 'chalicetest1'
@app.route('/')
def index():
return {'status_code': 200,
'message': 'welcome to test API'}
@app.route('/upload/{file_name}, methods=['PUT'], content_types=['application/octet-stream'])
def upload_to_s3(file_name):
try:
body = app.current_request.raw_body
temp_file = '/tmp/' + file_name
with open(temp_file, 'wb') as f:
f.write(body)
s3.upload_file(temp_file, BUCKET, file_name)
return Response(message='upload successful',
headers=['Content-Type': 'text/plain'],
status_code=200)
except Exception, e:
app.log.error('error occurred during upload %s' % e)
return Response(message='upload failed',
headers=['Content-Type': 'text/plain'],
status_code=400)
【问题讨论】:
-
你想从哪里上传哪个文件到哪个位置?您
app.py已部署到 AWS API 和 Lambda 函数,即“同一文件夹”在部署后可能不是真的。 -
该文件与 app.py 位于同一文件夹中。我也尝试使用文件的绝对路径,但都不起作用。我想正确的问题应该是“正确的做法是什么?”
标签: python python-3.x boto3 chalice