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

标签 python linux apache ubuntu amazon-s3

我正在 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

但是不起作用

最佳答案

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

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.

最后一些注意事项:您不需要关闭该文件,因为您使用了上下文管理器。另外,避免递归设置 777。最安全的方法是设置+wX,以便仅在目录上设置execute位,并在所有内容上设置write位。或者更好的是,更具体。

关于python - 授予在 Apache2 ubuntu 上运行的 Python Flask 应用程序的权限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65617482/

相关文章:

linux - 在 Amazon EC2 中创建子域

linux - 通过 HTTP 协议(protocol)进行身份验证的 Git 克隆

linux - 部署设备树覆盖时出错

php - 设置的最大cURL连接数是多少?

python - 在 PyQtGraph 中显示平均值

python - 无法通过 WSL 使用 conda 显示 matplotlib 的输出

python - 如何将日期时间格式化为 "2012-12-11 12:00:00"

python - 使用Python将嵌套列表插入mysql数据库

node.js - 转发端口从 80 和 443 到 8080

java - 将 Apache 重定向到 Vesta CP 上的 Tomcat