2

I'm running a Flask application on Apache2 server on Ubuntu. The application would take input from a form and save it to a text file. The file exists only for the moment when it's uploaded to S3. After that it's deleted.:

            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")

but the app doesn't have permission to create the file:

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

I already tried to give permissions to the folder where the app is located with:

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

but it doesn't work

Pranjal
  • 3,633
  • 3
  • 6
  • 13
KRASSUSS
  • 21
  • 3

1 Answers1

2

My guess is that the application is run from a different location. What output do you get from this:

import os
print(os.getcwd())

It's for that directory you need to set permissions. Better yet, use an absolute path. Since the file is temporary, use tempfile as 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.

Some final notes: You don't need to close the file, since you use a context manager. Also, avoid setting 777 recursively. The safest way is to set +wX in order to only set execute bit on directories and write bit on everything. Or better yet, be even more specific.

obeq
  • 635
  • 1
  • 4
  • 14