Reputation: 432
I'm trying to get a JPEG image from an app to another. Where I'm receiving it, the stream comes on the request's body and I try to make the file whole again, like this:
if r.status_code == 200:
f = open(os.path.join(os.path.dirname(os.path.realpath(__file__)) + "\\static\\tmp\\" + filename), 'wb')
f.write(r.content)
f.close()
return True
which works just fine when running in localhost. The file is in its place and just like it was when I uploaded it.
When I went to deploy all the apps and test them, Apache didn't allow me to do f = open(...)
, giving me the error:
IOError: [Errno 13] Permission denied: u'/var/www/my_url\\static\\tmp\\2378687.jpeg'
And that's strange, because the tmp folder has the attributes
unconfined_u:object_r:httpd_sys_rw_content_t:s0
Shouldn't it allow me to create the new file, even not being the sudo user?
Upvotes: 0
Views: 1026
Reputation:
You have a bug in line the very first line of your function. It should be
f = open(os.path.join(os.path.dirname(os.path.realpath(__file__),
"static", "tmp", filename), 'wb')
The directory separator is different on Windows and Linux. That is why it works locally, but not on the server. The os
module is there to abstract away those differences, but you don't actually use it to construct your filename. The way your code is written, the os.path.join()
is a noop.
Your code tries to write a file named my_url\static\tmp\2378687.jpeg
to the directory /var/www/my_url
.
Also, you should use a context manager, probably a configurable constant for the file path and catching errors would be good idea, too:
UPLOAD_DIR = '/var/www/my_url/static/tmp'
if r.status_code == 200:
try:
with open(os.path.join(UPLOAD_DIR, filename), 'wb') as f
f.write(r.content)
except IOError as e:
# log e.message or something
return False
return True
Upvotes: 1
Reputation: 3502
Use os.path.join instead of \\
. This make your code more portable between linux/windows os.
f = open(os.path.join(os.path.dirname(os.path.realpath(__file__), "static,"tmp" , filename), 'wb')
you are not referring to /tmp, instead you are trying to write in static folder: /var/www/my_url
. Try to use absolute path for this.
Upvotes: 2