【问题标题】:Give permission to Python Flask application running on Apache2 ubuntu授予在 Apache2 ubuntu 上运行的 Python Flask 应用程序的权限
【发布时间】:2021-04-13 11:32:46
【问题描述】:

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

但它不起作用

【问题讨论】:

  • 你检查所有权了吗?尝试从 root 用户运行它。

标签: python linux apache ubuntu amazon-s3


【解决方案1】:

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

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 位。或者更好的是,更具体。

【讨论】:

    猜你喜欢
    • 2016-11-23
    • 2017-01-06
    • 2015-02-10
    • 2012-04-29
    • 1970-01-01
    • 2017-06-13
    • 2023-04-02
    • 2023-04-08
    相关资源
    最近更新 更多