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