授予在Apache2 ubuntu上运行的Python Flask应用程序权限

2024-09-30 01:21:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在Ubuntu的Apache2服务器上运行Flask应用程序。应用程序将从表单中获取输入并将其保存到文本文件中。该文件仅在上载到S3时存在。之后,它被删除

            foodforthought = request.form['txtfield']
        with open("filetos3.txt", "w") as file:
            file.write(foodforthought)
        file.close()
        s3.Bucket("bucketname").upload_file(Filename = "filetos3.txt", Key = usr+"-"+str(datetime.now()))
        os.remove("filetos3.txt")

但应用程序没有创建文件的权限:

[Errno 13] Permission denied: 'filetos3.txt'

我已尝试通过以下方式授予应用所在文件夹的权限:

 sudo chmod -R 777 /var/www/webApp/webApp

但它不起作用


Tags: 文件服务器txt应用程序权限flask表单s3
1条回答
网友
1楼 · 发布于 2024-09-30 01:21:15

我猜应用程序是从不同的位置运行的。您从中获得了什么输出:

import os
print(os.getcwd())

您需要为该目录设置权限。最好使用绝对路径。由于该文件是临时文件,请使用tempfile作为detailed here

foodforthought = request.form['txtfield']

with tempfile.NamedTemporaryFile() as fd:
    fd.write(foodforthought)
    fd.flush()

    # Name of file is in the .name attribute.
    s3.Bucket("bucketname").upload_file(Filename = fd.name, Key = usr+"-"+str(datetime.now()))

    # The file is automatically deleted when closed, which is when the leaving the context manager.

最后一点注意:您不需要close文件,因为您使用的是上下文管理器。此外,避免递归设置777。最安全的方法是设置+wX,以便只在目录上设置execute位,在所有内容上设置write位。或者更具体一点

相关问题 更多 >

    热门问题