Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

flask running in mod_wsgi cannot write to /tmp

Apache v2.4.12-2

Mod_wsgi v4.4.8-1

Python v3.4.2

python-flask v0.10.1-5

Arch linux - kernel 3.12.36

I'm using mod_wsgi and flask to host a server. I am able to reproduce this issue with the following simplified code and generic .wsgi script:

MainServer.py:

import flask

app = flask.Flask(__name__)

@app.before_first_request
def initstuff():
    test_file = '/tmp/test'
    with open(test_file, 'w') as f:
        f.write('test')

@app.route('/', methods=['GET'])
def rootdir():
    return 'Hello world'

MainServer.wsgi:

from MainServer import app as application

Expected: a file with the contents 'test' is written in /tmp

Actual outcome: No file is written. No errors reported in log

If I run the same code but instead point to any other directory which my user has permission to write, it creates the file as expected. /tmp is the only directory where I am having this issue.

If I run the above code directly and use flask's built in server (app.run), it can create the file in /tmp as expected without any issues.

I've ensured that the mod_wsgi server is running as the same user as the script with app.run is and that this user is able to write to /tmp.

--edit--

Running httpd directly from the command line does not cause this issue. Starting httpd as a systemd service does

like image 240
N. Simon Avatar asked Apr 25 '15 17:04

N. Simon


2 Answers

I think is related to this answer: https://unix.stackexchange.com/questions/167835/where-apaches-tmp-located

Apache might be using private-tmp which causes /tmp to be redirected to /var/tmp/systemd-private--httpd.service-/

like image 177
meeuw Avatar answered Nov 12 '22 11:11

meeuw


Try setting the app logger level to DEBUG (and adding a Handler):

import logging
from logging.handlers import RotatingFileHandler
import flask

app = flask.Flask(__name__)

@app.before_first_request
def initstuff():
    test_file = '/tmp/test'
    with open(test_file, 'w') as f:
        f.write('test')

@app.route('/', methods=['GET'])
def rootdir():
    return 'Hello world'

if __name__ == '__main__':
    handler = RotatingFileHandler('app.log', maxBytes=10000, backupCount=1)
    handler.setLevel(logging.DEBUG)
    app.logger.addHandler(handler)
    app.run(host='0.0.0.0', port=8056, debug=True, use_reloader=False)

Then look in app.log to see what the problem is.

like image 42
chown Avatar answered Nov 12 '22 12:11

chown