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

1
  • Did u check the ownership? try running it from a root user. Commented Jan 14, 2021 at 7:13

1 Answer 1

2
+50

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.