pythonfile-permissionsmkstemp

tempfile.mkstemp permissions settings


I am using tempfile.mkstemp to generate a random available filename and write some content with os.fdopen. I then pass the filename to a task via celery.

This task opens the file, processes the content, and finally removes the file. In testing this works fine, however I have realised that this will break in my live environment where the user running the task is not the same as the one which creates the file.

This means that the user cannot open the file because tempfile.mkstemp sets the permissions to 600(-rw-------).

I cannot make both processes run by the same user, so is there some way to modify the file permissions set by tempfile.mkstemp?

I am running Python 3.6 on Ubuntu 14.04.


Solution

  • Given that you use os.fdopen after you call mkstemp(), you may be better off using tempfile.NamedTemporaryFile(delete=False). It returns a Python file object instead of an fd.

    Either way, the returned file will have mode=0600, so you will need to change it. Use os.fchmod(temp_file.fileno(), 0640) or similar (change the mode as per your needs).