IOError: [Errno 13] Permission denied using Python, but I can't see why? - python-2.7

I have been coding an App that needs to write some lines to a directory in Linux, but the output returned keeps showing the following error:
File "/home/p4user/flexclone/main/demo/flex.py", line 1305, in p4config
fh = open(path + "/.p4config", "w")
IOError: [Errno 13] Permission denied: '/p4flex/rickclone36/.p4config'
The user does have permission for this directory, and I have tried various filenames which exists and do not exist yet. I have been spinning around for the past 36 hours and this is a roadblock. Here is the code snippet causing the issue (I have throughly traced through the code snipped too):
def p4config(self, path, client):
p4config = os.getenv('P4CONFIG', '.p4config')
p4port = self.call.getPort()
p4user = self.call.getUser()
fh = open(path + "/.p4config", "w")
if fh:
The error occurs is seen at the fh=open() line. Does anyone have suggestions, or indications why the block may be occurring? When as a user I just touch files, it's all fine.
Thanks

Related

Permission Denied to Upload Django

i'm try upload file with django(xlsx) this is my code:
myfile = request.FILES['document']
fs = FileSystemStorage()
filename = fs.save(myfile.name, myfile)
on the model i have setup the folder "media" to uploads, get this error:
Permission denied: '/var/www/html/inventariosRG/media/my_file.xlsx'
this error i'm try fixed with this:
PATH = 'media/'
myfile = request.FILES['document']
try:
import subprocess
RUTA_ABSOLUTA = os.path.join(os.path.dirname(os.path.dirname(__file__)),PATH)
subprocess.Popen('sudo chmod -R 777 '+RUTA_ABSOLUTA, shell=True)
except Exception as e:
raise Exception ("Error ",e)
fs = FileSystemStorage()
filename = fs.save(myfile.name, myfile)
this code only show the same error "permission denied..." please i'm try set the permission by command on django, any suggest thanks..!!
These answers probably relate and are better than 777-ing:
Django - Media upload [Errno 13] Permission denied
A file from the internet is owned by user 'www-data:www-data' and that user has tightly restricted permissions (because files from the internet might be bad.) Your Django media/ folder needs to be accessible and writeable to the www-data user, so making that owner the user is appropriate.
Also, I'm not a sysadmin by any means and I may be speaking from unrecognized ignorance, but building the use of sudo into your Django application seems like a big security risk to me.
I can see a use for a 'config' script, that ensures a new deployment rolls out correctly, but keep that script and your Django code well separated from files from the internet. You could add your script to /etc/sudoers to give it the authority it needs (but remember to edit sudoers with visudo) if there was some reason to automate it.

Display a docx file on the screen

I created a ms-word document using MailMerge in django. It´s worked ok.
Right now, i´d like to show this file on screen. I write the code bellow, but it didn´t work.
views.py
with open(file_path) as doc:
response = HttpResponse(doc.read(), content_type='application/ms-word')
response = HttpResponse(template_output)
response['Content-Disposition'] = 'attachment;filename=var_nomdocumento_output'
error:
[Errno 13] Permission denied: 'C:\\GROWTHTECH\\Projetos\\blockchain\\media_root/procuracao'
You forgot to provide the binary open mode. It can be r open for reading (default) w open for writing, truncating the file first, b for binary mode.
so In our case: It will be rb
file_path = 'path/path/file.docx'
with open(file_path,'rb') as doc:
response = HttpResponse(doc.read(), content_type='application/ms-word')
# response = HttpResponse(template_output)
response['Content-Disposition'] = 'attachment;filename=name.docx'
return response
No browsers currently render Word Documents as far as I know. So your file will be automatically downloaded whatever the parameter is: 'attachment;filename="file_name"' or 'inline;filename="file_name"'

I don't understand how this "os.join" function is working? I am getting errors constantly and no reading on os functions is helping me

Here's the code
sys.path.append( "../tools/" )
from parse_out_email_text import parseOutText #(its just another .py file that has a function I wrote)
from_sara = open("from_sara.txt", "r")
from_chris = open("from_chris.txt", "r")
from_data = []
word_data = []
temp_counter = 0
for name, from_person in [("sara", from_sara), ("chris", from_chris)]:
for path in from_person:
### only look at first 200 emails when developing
### once everything is working, remove this line to run over full dataset
temp_counter += 1
if temp_counter < 200:
path = os.path.join('..', path[:-1]) #(THIS IS THE PART I CAN'T GET MY HEAD AROUND)
print path
email = open(path, "r")
email.close()
print "emails processed"
from_sara.close()
from_chris.close()
When I run this, it gives me an error as shown below:
Traceback (most recent call last):
..\maildir/bailey-s/deleted_items/101.
File "C:/Users/AmitSingh/Desktop/Data/Udacity/Naya_attempt/vectorize_text.py", line 47, in <module>
email = open(path, "r")
IOError: [Errno 2] No such file or directory: '..\\maildir/bailey-s/deleted_items/101.'
I don't even have this """'..\maildir/bailey-s/deleted_items/101.'""" directory path on my laptop, I tried to change the path by replacing the '..' in the code by the actual path name to the folder where I keep all the files, and nothing changes.
path = os.path.join('..', path[:-1])
This code is part of an online course on machine learning and I have been stuck at this point for 3 hours now. Any help would be really appreciated.
(P.S. This is not a homework question and there are no grades attached to this, its a free online course)
your test data is not there so it cannot find it. you should run start-up code again and make sure the necessary maildir are all there.
Go to tools inside your udacity project directory and run startup.py.
It is about 400 Mb so sit back and relax!
I know this is extremely late, but I found this post after having the exact same problem.
All the answers that I found here and on other sites, even the issue requests in the original github, were just "run startup.py" I already did that. However, it was telling me:
Traceback (most recent call last):
File "K:\documents\Udacity\Mini-Projects\ud120-projects\text_learning\vectorize_text.py", line 48, in <module>
email = open(path, "r")
FileNotFoundError: [Errno 2] No such file or directory: '..\\maildir/bailey-s/deleted_items/101.'
Just like yours. I then found where this file was located and it was indeed on my computer
I added 'tools' to the os.path.join() line as you can see here:
for name, from_person in [("sara", from_sara), ("chris", from_chris)]:
for path in from_person:
### only look at first 200 emails when developing
### once everything is working, remove this line to run over full dataset
temp_counter += 1
if temp_counter < 200:
#path = os.path.join('..', path[:-1]) <---original
path = os.path.join('..','tools', path[:-1])
print(path)
email = open(path, "r")
This worked for me finally. So, I hope it helps anyone else that stumbles on this problem in the future.
Also, I noticed on some examples I found of other repos of the lessons. Their 'tools' folder was named 'utils'.
Here is an example, this is a repo that someone tweaked to use jupyter notebooks to run the lessons So, use the one that you have.
In your Udacity course folder, first go to tools directory, check if you have maildir folder present and if it has got subfolders in it, if they are present then go back to text_learning/vectorize_text.py, find this line of code path = os.path.join('..', path[:-1]), change it to path = os.path.join('../tools/', path[:-1]),
On terminal, cd text_learning , then python vectorize_text.py, this should solve the issue.
If this does not solve the issue, then Go to tools inside your udacity project directory and run startup.py. Wait till the process is complete
Repeat step 1.

Django production: [Errno 13] Permission denied:

In my Django app I have this kind of error: "IOError: [Errno 13] Permission denied: 'file_name'"
This is my code:
def record_export():
for file_name, tab_name in tab:
if len(globals()[tab_name].objects.all()) <> 0:
f = open(file_name, 'wb')
writer = csv.writer(f, delimiter='|')
for record in globals()[tab_name].objects.values_list():
writer.writerow([unicode(s).encode("utf-8") for s in record])
f.close()
In development enviroment all it's ok. I think that I have the permission.
In production I have: "IOError: [Errno 13] Permission denied: 'file_name'"
Do you know why?
Thanks for your help
Djangos's runserver usually runs as root, this is probably your problem.
Your webserver needs rights to read/write the file. You can use ls -l /your/path/to/file to check permissions for a given directory. To change rights and owner, use chmod and chown.
If you are running a apache2 webserver your user and group is in most cases www-data.

Django + Apache - file.open() Permission Denied

So I have the following problem:
On an ivent a javascript sends some text to the django server and there are two functions that should work:
views.py:
def log(request):
f = open('media/log.txt', 'r')
return HttpResponse(f, mimetype='text/plain')
def modelers(request):
mod_stat = request.POST['id']
time = datetime.datetime.now().strftime("%b %d %Y %H:%M:%S")
file=open('media/log.txt', 'a')
file.write(time)
file.write(' ')
file.write(mod_stat)
file.write('\n')
file.close()
return ErrorResponse()
so the user clicks on a button and the "modelers" function is getting the info and is trying to add a line to the log file. But it doesn't work!
The apache error.log says that
IOError: [Errno 13] Permission denied: 'media/log.txt', referer: ...
chmod 777 media doesn't help.. I know that I must config the apache somehow to let the django write files, but didn't find how :(
If not under apache it works great(so the url.py is OK), but I need to make it work with apache. The other part of the application also works fine but there are no operations with files.. until now..
Have you tried chmod 777 media/log.txt? Does ls -l media/ say rwxrwxrwx log.txt? If yes then try to specify absolute path to log.txt in f = open('...log.txt')