Django - Permission denied to open media in production server (Azure) - python

Now i am working on production server (AzureWebsites) and i want to open my .txt files.
This is the tree that i used to save my stopwords.txt
-App
-media
-App
stopwords.txt
-static
-templates
settings.py
MEDIA_ROOT = path.join(PROJECT_ROOT, 'media').replace('\\', '/')
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = '/media/'
I want to open the text file using this command
handle = open('/media/stopwords.txt', 'r+')
var = handle.read()
This is the error i got when run my app
[Errno 13] Permission denied: '/media/stopwords.txt'
and when i try to modify the open statements with this
handle = open(settings.MEDIA_ROOT + 'stopwords.txt', 'r+')
i got this error
[Errno 2] No such file or directory: 'D:/home/site/wwwroot/mediastopwords.txt'
Can anyone please help fix this problem?

Try handle = open(settings.MEDIA_ROOT + '/stopwords.txt', 'r+')

According to your tree stopwords is stored under /media/App/stopwords.txt
So to open it you need:
handle = open(settings.MEDIA_ROOT + '/App/stopwords.txt', 'r+')

Related

OSError: [Errno 30] Read-only file system in Django on Heroku

I'm using Django 2.0 and Heroku to host the application.
My media directory settings are like
App/settings/production.py:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static_cdn', 'media_root')
I'm using gTTS to convert text to speech and save .mp3 file in the media directory:
tts_file_name = str(int(time.time())) + '.mp3'
joined_path = os.path.join(settings.MEDIA_ROOT, 'tts')
joined_path_with_file = os.path.join(joined_path, tts_file_name)
# create directory if does not exists
if not os.path.exists(joined_path):
os.makedirs(joined_path)
tts = gTTS(text='Good morning', lang='en')
tts.save(joined_path_with_file)
# tts path to send to template
tts_media_url = os.path.join(settings.MEDIA_URL, 'tts', tts_file_name)
It is working fine on local system as I can change file permissions manually also.
But It is not working on Heroku and giving error:
OSError: [Errno 30] Read-only file system: '/static_cdn'
I tried to locate static_cdn by running heroku shell, but could not even found static_cdn in application path and root path. But it seems to be working as other uploading through form is working perfectly.
using Django model's upload_to is working and even directory is created in static_cdn.
How can I create directory in static_cdn on Heroku the same way Django does using model's upload_to?
Changed MEDIA_ROOT path by removing additional os.path.dirname() and it is working now.
MEDIA_ROOT = os.path.join(BASE_DIR, 'static_cdn', 'media_root')
In my case, this error occurred because I set the STATIC_ROOT = '/static/'
This means it's looking at / root folder of the system and then static, which is obviously read-only,
changing it to STATIC_ROOT = 'static/' fixed my issue.
I'm using gTTS to convert text to speech and save .mp3 file in the media directory
I'm not sure what's causing your immediate error, but this isn't going to work very well on Heroku. Its filesystem is ephemeral: you can write to it, but whatever you write will be lost when the dyno restarts. This happens frequently (at least once per day).
Heroku recommends using a third-party file or object store like Amazon S3 for storing generated files, uploaded files, etc. I recommend gong down this path. There are many Django libraries for using S3, and other services, as storage backends.

Django can't find static files after changing name of folder in project path

I have a Django project that I have been working on and I want to change the name of a folder in the project's file path. My current path to my project looks like this:
/Users/user/Documents/Python/Django Projects/ProjectName/
I want to change the project path to:
/Users/user/Documents/Python/Django_Projects/ProjectName/
When I do this change I get the following error message:
OSError at /
[Errno 2] No such file or directory:
'/Users/user/Documents/Python/Django Projects/ProjectName/assets'
In my settings.py file I have this:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'assets'), )
In the request META the PWD value is unchanged:
PWD '/Users/user/Documents/Python/Django Projects/ProjectName'
I'm fairly new to programming so I apologise for asking such a simple question, but any help would be greatly appreciated.
Thanks

django app multiple hard drives [Errno 18] Invalid cross-device link

I have a Django app on a Debian server and my current site_media directory on the current disk is full. So I want to upload files On a second disk. The path on server is /disk :
obj = form.save(commit=False)
obj.user_id = self.request.user.pk
obj.save()
initial_path = obj.file.path
print(initial_path)
new = settings.MEDIA_ROOT_NEW + obj.file.name
print(new)
os.rename(initial_path,new)
shutil.move(initial_path, new)
and in my settings.py I have:
MEDIA_ROOT = os.path.join(PROJECT_PATH, 'site_media/')
MEDIA_ROOT_NEW = '/disk/site_media/'
still I get error:
django [Errno 18] Invalid cross-device link
Any ideas?
os.rename() may fail across different file systems.
The operation may fail on some Unix flavors if src and dst are on different filesystems.
shutil.move() should work
If the destination is on the current filesystem, then os.rename() is used. Otherwise, src is copied (using shutil.copy2()) to dst and then removed.
but you've got a os.rename(initial_path,new) just before your shutil.move(initial_path, new). Remove the first os.rename() and it should work.

Permission issue Python 3.4 apache

im have FLASK app with
www/FlaskApp/FlaskApp/init.py file with funtion
python file wut next contains
#app.route('/')
def hello():
file = open('myfile.txt', 'w+')
os.mknod("newfile.txt")
return render_template('page2.html')
but if im run site,its return error, in file log write
PermissionError: [Errno 13] Permission denied: 'myfile.txt'
im set permision 777 for all www directories
open FileZilla
right click on www dir, and set 777 permision
Why file dont create?
Not sure if this is an optimal solution, and I don't know enough about Flask as to tell you why the relative path isn't working (I would think that it would write the file where ever your python script was) but you could get it to work by using an environment variable to specify where to store your apps data. For instance:
import os
#app.route('/')
def open_file():
filename = os.path.join(os.environ['FLASK_APP_DATA'], 'myfile.txt')
print (filename)
file = open(filename, 'w+')
file.write("This is a test")
file.close()
Then you could have the environment variable set differently on your dev box and your prod box.

Django Python does not display the correct PDF file

I have PDF files which are stored on the server. I am writing a code which prompts users to download the PDF file. I used the following code:
filename ="somepdf.pdf"
filedir = "media/"
filepath = os.path.join( filedir, filename )
pdf=open(filepath)
response = HttpResponse(pdf.read(),content_type='application/pdf')
response['Content-Disposition'] = 'attachment;filename=%s' % filename
return response
For some reason, I rechecked the PDF file that was prompted. The PDF file are not readable (corrupted file perhaps).
Do you know what happen?
You have missed MEDIA_ROOT:
from settings import MEDIA_ROOT
...
filepath = os.path.join(MEDIA_ROOT, filedir, filename)
I found what the answer is.
Apparently the Media_ROOT and Media_URL doesn't work in my case. I use the web browsing debugging tool and locate the discrepancy between the link and the actual PDF.
It should be "/media/" not "media"
I used this code in the HTML to serve the file:
<embed height="100%" width="100%" name="plugin" src="/media/receipts/Receipt_1.pdf" type="application/pdf">

Categories

Resources