Django production: [Errno 13] Permission denied: - django

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.

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.

Swisscom Appcloud S3 Connection reset by peer

We have a Django Webservice that uses Swisscom AppCloud's S3 solution. So far we had no problems, but without changing anything on the application we are experiencing ConnectionError: ('Connection aborted.', error(104, 'Connection reset by peer')) errors when we are trying to upload files. We are using boto3 1.4.4.
Edit:
The error occures after somwhere between 10 and 30s. When I try from my local development machine it works.
from django.conf import settings
from boto3 import session
from botocore.exceptions import ClientError
class S3Client(object):
def __init__(self):
s3_session = session.Session()
self.s3_client = s3_session.client(
service_name='s3',
aws_access_key_id=settings.AWS_ACCESS_KEY,
aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY,
endpoint_url=settings.S3_ENDPOINT,
)
.
.
.
def add_file(self, bucket, fileobj, file_name):
self.s3_client.upload_fileobj(fileobj, bucket, file_name)
url = self.s3_client.generate_presigned_url(
ClientMethod='get_object',
Params={
'Bucket': bucket,
'Key': file_name
},
ExpiresIn=60*24*356*10 # signed for 10 years. Should be enough..
)
url, signature = self._split_signed_url(url)
return url, signature, file_name
Could this be a version problem or anything else on our side?
Edit:
Made some tests with s3cmd: I can list the buckets I have access to but for all other commands like listing all objects or just listing the objects in a bucket I get a Retrying failed request: / ([Errno 54] Connection reset by peer)
After some investigation I found the error:
Swisscom's implementation of S3 is somehow not up-to-date with Amazon's. To solve the problem I had to downgrade botocore from 1.5.78 to 1.5.62.

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

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

Windows error 5: Access is denied when trying delete a directory in windows

i am trying to delete a directory but when i run the code it gives windows error 5: access is denied. here is my code: in the Release folder, there is a folder called OD.
if os.path.exists(os.path.join(get_path_for_output,'Release')):
shutil.rmtree(os.path.join(get_path_for_output,'Release'))
the error is like:
WindowsError: [Error 5] Access is denied: 'C:\\Users\\marahama\\Desktop\\Abdur_Release\\Release\\OD\\automations\\GEM\\FMS_adapter.py'
This was due to the file permissions issue.
You need to have the permissions to perform that task on that file.
To get the permissions associated with a file, useos.stat(fileName)
You can explicitly check the write permission for that file using os.access(fileName, os.W_OK)
Then, to change the permission, os.chmod(fileName,permissionNumeric).
Ex: os.chmod(fileName, '0777')
To change the permission for the current file that is being executed,
use os.chmod(__file__, '0777')
I use pydev. And my solution is:
Stop Eclipse.
Start Eclipse with option Run as administrator
takeown /F C:\<dir> /R /A
icacls C:\<dir> /grant administrators:F /t
Give ownership to administrators and give full control to administrators, if your user is an administrator.
in order to change files located in "C:" you must have admin privileges,
you can either get them before starting the script or while doing so, for instance:
#!python
# coding: utf-8
import sys
import ctypes
def run_as_admin(argv=None, debug=False):
shell32 = ctypes.windll.shell32
if argv is None and shell32.IsUserAnAdmin():
return True
if argv is None:
argv = sys.argv
if hasattr(sys, '_MEIPASS'):
# Support pyinstaller wrapped program.
arguments = map(unicode, argv[1:])
else:
arguments = map(unicode, argv)
argument_line = u' '.join(arguments)
executable = unicode(sys.executable)
if debug:
print 'Command line: ', executable, argument_line
ret = shell32.ShellExecuteW(None, u"runas", executable, argument_line, None, 1)
if int(ret) <= 32:
return False
return None
if __name__ == '__main__':
ret = run_as_admin()
if ret is True:
print 'I have admin privilege.'
raw_input('Press ENTER to exit.')
elif ret is None:
print 'I am elevating to admin privilege.'
raw_input('Press ENTER to exit.')
else:
print 'Error(ret=%d): cannot elevate privilege.' % (ret, )
code taken from: How to run python script with elevated privilege on windows
script by: Gary Lee

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')