Permission denied while trying to write to file from view

I created a chat for this question: here

I have a view that is trying to execute f = open('textfile.txt', 'w') , but on my live server this throws an error [Errno 13] Permission denied: 'textfile.txt' .

My file structure is as follows:

 - root | - project | - app | - media 

where the view lives in the app .

I tried to have textfile.txt in the root, project, application and media, all of which have 777 file permissions (the owner, group and the public can read, write and execute) [* 1].

If I change the command to read permission, i.e. f = open('textfile.txt', 'r') , I get the same error.

My media root has the value os.path.join(os.path.dirname(__file__), 'media').replace('\\','/') and all this is done on the apache server via webfaction.

So, I have two questions. Where is django / python trying to open this file? and what I need to change in order to get permission to view, to open and write to a file.

[* 1] I know this is not a good idea, I have this kit for current debugging purposes.


EDIT:

I don’t know if this is relevant, but now when I change it to f = open(os.path.join(settings.MEDIA_URL, 'textfile.txt'), 'r') , and not to f = open(os.path.join(settings.MEDIA_URL, 'textfile.txt'), 'w') , I get the error [Errno 2] No such file or directory .

I don’t know if it matters or not ...

+4
source share
1 answer

Given the following:

 f = open('textfile.txt', 'w') 

It should create a file in the same directory as __file__ , the current script or views.py in your script.

However, it is better to be explicit and, therefore, exclude any potential deviations. I would recommend changing this line to:

 import os f = open(os.path.join(os.path.dirname(__file__), 'textfile.txt'), 'w') 

Or even better, something like:

 import os from django.conf import settings f = open(os.path.join(settings.MEDIA_ROOT, 'textfile.txt'), 'w') 

Then you are always sure where exactly the file is saved, which should allow you to optimize your permissions in a more appropriate way. Alternatively, you can use PROJECT_ROOT .

+4
source

Source: https://habr.com/ru/post/1380063/


All Articles