Search code examples
pythonapacheubuntuflaskpermission-denied

Apache: Errno 13 file permission denied


I use AWS EC2 to run my application "Neural network in art". To send images I deploy a website based on flask + virtualenv + apache. After sending the image on the server starts the script, which print each iteration and I want to store it in out.txt

__init__.py:

#...
def apply_style(image_name, style_name, iterations):
    command = ['"python ~/neural_artistic_style/neural_artistic_style.py', \
            ' --subject ', '/var/www/superapp/superapp/uploads/' + image_name, \
            ' --style ', '/var/www/superapp/superapp/uploads/' + style_name, \
            ' --iterations ', iterations, \
            ' --network ~/neural_artistic_style/imagenet-vgg-verydeep-19.mat"']
    str = ''.join(command)
    network = Popen(str, shell=True, stdout=PIPE)
    stats = []
    for out in network.stdout:
        stats.append(out)
    line = ' '.join(stats)
    return line

@app.route('/upload', methods=['GET', 'POST'])
def upload():
    if request.method == 'POST':
        image = request.files['image']
        style = request.files['style']
        iterations = request.form['iter']
        if file and style:
#Saving images...                
            result = apply_style(image_name, style_name, iterations)
            f = open('out.txt', 'w')
            f.write(result)
            f.close()
            return 'FINISHED'
#...

Well, I can upload image via HTTP without writing result in out.txt, but when I do, apache log shows this:

[Wed Jun 01 ...] [:error] [pid 2360:tid 14...]     return self.view_functions[rule.endpoint](**req.view_args)
[Wed Jun 01 ...] [:error] [pid 2360:tid 14...]   File "/var/www/superapp/superapp/__init__.py", line 72, in upload
[Wed Jun 01 ...] [:error] [pid 2360:tid 14...]     f = open('out.txt', 'w')
[Wed Jun 01 ...] [:error] [pid 2360:tid 14...] IOError: [Errno 13] Permission denied: 'out.txt'

All files in this directory now have 777 permission. When I try to write something using simple script like script.py:

f = open('out.txt', 'w')
f.write('some words')
f.close()

everithing works. But with apache it doesn't. Has anyone any ideas how to fix it?


Solution

  • The problem is that apache runs your code in which will have a different working directory, one which you do not intend to write the file into. You must supply a full path to the file.

    f = open('/path/to/my/out.txt', 'w')