簡體   English   中英

嘗試從Flask應用程序中的EC2實例將文件上傳到Amazon S3時出現ClientError(SignatureDoesNotMatch)

[英]ClientError (SignatureDoesNotMatch) when trying to upload file to Amazon S3 from an EC2 instance in a Flask app

我正在嘗試編寫Flask應用程序以上傳到AWS S3存儲桶。 在哪里,當我在PyCharm中本地運行此程序時,效果很好。 但是,一旦將其部署到AWS(部署端口80上的Flask應用程序),我現在會收到一個錯誤...

botocore.exceptions.ClientError: An error occurred (SignatureDoesNotMatch) when calling the ListBuckets operation: The request sture we calculated does not match the signature you provided. Check your key and signing method.

當密鑰在本地工作時...但是不適用於AWS EC2實例。 我最初的想法可能是端口問題或boto3問題。 盡管我不確定,因為它可以在本地運行,但不能在AWS上運行。

有什么幫助嗎? 這是我的代碼...刪除了鍵和URL

app.py

from flask import Flask, render_template, flash
from werkzeug.utils import secure_filename
from flask_wtf import FlaskForm
from flask_wtf.file import FileField, FileRequired
from tools import s3_upload

'''
Author: xxx
'''

app = Flask(__name__)
app.config.from_object('config')
# Flask Secret Key
app.secret_key = 'xxxxx'

# Limits what file types can be uploaded
def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1] in app.config['ALLOWED_EXTENSIONS']

# Initializes upload form
class UploadForm(FlaskForm):
    example = FileField(validators=[FileRequired()])

# Route for root, handles on click action for upload form
@app.route('/', methods=['POST', 'GET'])
def upload_page():
    form = UploadForm()
    if form.validate_on_submit():
        file = form.example.data
        filename = secure_filename(file.filename)
        output = s3_upload(file,filename)
        flash('{src} uploaded to S3'.format(src=form.example.data.filename))
    return render_template('index.html', form=form)

if __name__ == '__main__':
    app.run()

tools.py

import boto3
from flask import current_app as app

'''
Author: xxx
'''

def s3_upload(source_file, source_filename):
    # What directory on Amazon S3 Bucket to upload to.
    upload_dir = app.config["S3_UPLOAD_DIRECTORY"]

    #Connect to S3 and upload file
    s3 = boto3.client('s3')
    s3.upload_fileobj(source_file, app.config["S3_BUCKET"], upload_dir + "/" + source_filename)

config.py

S3_KEY = 'xxx'
S3_SECRET = 'xxxx'
S3_UPLOAD_DIRECTORY = 'xxxx'
S3_BUCKET = 'xxxx'
ALLOWED_EXTENSIONS = ['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif']

SECRET_KEY = "xxxx"
DEBUG = True

嘗試將客戶端對象更改為:

client = boto3.client('s3', config=boto3.session.Config(signature_version='s3v4'))

事實證明,該問題是AWS的關鍵問題,也是我使用此處在網絡上被阻止的端口引起的網絡安全問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM