Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
374 views
in Technique[技术] by (71.8m points)

linux - Give permission to Python Flask application running on Apache2 ubuntu

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

question from:https://stackoverflow.com/questions/65617482/give-permission-to-python-flask-application-running-on-apache2-ubuntu

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...