权限被拒绝来自Flask App的AWS EC2 file.save

时间:2015-12-16 19:16:41

标签: python amazon-ec2 flask

我正在Flask中编写一个应用程序,并将其部署在EC2中。我试图让用户上传本地目录中的文件。但是在保存上传文件时,我收到了权限被拒绝错误。我附上下面的代码。请帮我修复它。我试图将文件夹权限更改为sudo chmod -R 777 / var / www,但这没有帮助。我确实理解给写权限是坏的,但这对于开发模式并希望通过它 这是代码

@app.route('/upload', methods=['GET', 'POST'])
         def upload_file():
        # Get the name of the uploaded files
        uploaded_files = request.files.getlist("file[]")
        filenames = []
        for file in uploaded_files:
        # Check if the file is one of the allowed types/extensions
         if file and allowed_file(file.filename):
        # Make the filename safe, remove unsupported chars
        filename = secure_filename(file.filename)
        # Move the file form the temporal folder to the upload
        # folder we setup
        current_date = time.strftime("%x").split("/")           [0]+time.strftime("%x").split("/")[1]+time.strftime("%x").split("/")[2]
        directory = os.path.join('loadedfiles/')
        uploadedfilesdir = directory + current_date
        if not os.path.exists(uploadedfilesdir):
            os.makedirs(uploadedfilesdir)
        file.save(os.path.join(uploadedfilesdir, filename)) 
        # Save the filename into a list, we'll use it later
        filenames.append(filename)
        # Redirect the user to the uploaded_file route, which
        # will basicaly show on the browser the uploaded file
# Load an html page with a link to each uploaded file
return render_template('upload.html', filenames=filenames)

2 个答案:

答案 0 :(得分:0)

可能与此question相关,是将相对路径转换为绝对路径的解决方案。我不知道程序是如何在EC2上启动的,但似乎工作目录位于某些Python /库目录中,其中不允许执行的程序写入。使用绝对路径的修复可能如下所示:

directory = os.path.join('/var/www/', 'loadedfiles/', current_date)

答案 1 :(得分:-1)

尝试给出类似的绝对路径

path = ./static/upload_folder

尝试一下

path = /var/www/folder/folder/static/upload_folder

然后不要忘记通过此命令授予该文件夹的所有权限

sudo chmod -R 777 /var/www/folder/folder/static/upload_folder

这对我有用!