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.
Related
Issue: Unable to save file in directory (/root/Notion/Image) when using Cron schedule
This is what my code is trying to do:
Check email
Download image attachment
Store in a directory - root/Notion/Image
Retrieve file path
The script is working when I run it manually in Google Cloud terminal. The problem is when I try to schedule it on Cron, it's unable to access the folder to save the file locally.
This is the error when the script failed and require permission:
Traceback (most recent call last):
File "Notion/test.py", line 121, in <module>
path = get_attachments(email.message_from_bytes(msg[0][1]))
File "Notion/test.py", line 47, in get_attachments
with open(filePath, 'wb') as f:
PermissionError: [Errno 13] Permission denied: '/root/Notion/Image/3.jpeg'
This is the code to retrieve attachment from email
def get_attachments(msg):
for part in msg.walk():
if part.get_content_maintype()=='multipart':
continue
if part.get('Content-Disposition') is None:
continue
fileName = part.get_filename()
if bool(fileName):
filePath = os.path.join(attachment_dir, fileName)
with open(filePath, 'wb') as f:
f.write(part.get_payload(decode=True))
return str(filePath)
Resolved:
The problem is that I shouldn't use root directory since it requires permission. I've changed it to home directory instead.
attachment_dir = '/home/dev_thomas_yang/folder_name/folder_name'
For people who needs to check their home direction, simply run this script.
from pathlib import Path
home= str(Path.home())
print(home)
Thanks Triplee for the patience to breakdown my issue despite my sloppy ways of presenting it!
The easiest fix hands down is to change the code so it doesn't try to write to /root. Have it write to the invoking user's home directory instead.
Your question doesn't show the relevant parts of the code, but just change attachment_dir so it's not an absolute path. Maybe separately take care of creating the directory if it doesn't already exist.
import pathlib
# ...
attachment_dir = pathlib.Path("cron/whatever/attachments").mkdir(parents=True, exist_ok=True)
# ...
for loop in circumstances:
get_attachments(something)
A better design altogether would be to have get_attachments accept the directory name as a parameter, so you can make this configurable from the code which calls it. Global variables are a nuisance and cause hard-to-debug problems because they hide information which is important for understanding the code, and tricky to change when you try to debug that code and don't know which parts of the code depend on the old value.
my problem is that on local, my code works fine but when I pushed it on the server, the file isn't created.
Here's the code:
def write_binary_file(bfile, location):
"""Write binary file in the location"""
try:
with open(location, "wb+") as img_file:
img_file.write(bfile)
except IOError as err:
Handling error
file_url = os.path.join(settings.BASE_DIR, "dir", "dir", "dir", "dir", "user_img", filename + '.jpeg')
write_binary_file(bfile, file_url):
Difference between local and server:
_local os is windows
_server os is linux
I don't know if this matter or not since I'm using os.path.join and os.path.sep to build the url and getting file url without the first dir.
It worked before in the server but one day, somehow, it didn't work anymore till now
space left on the server: about 3Go
permission on the directory: 775 (rwxrwxr-x)
Well, figured what was the problem, it was nginx config to hide file path in the server
I'm working on a python project in which I need to create a new JSON file.It's working locally but when I deploy my app to Heroku the file creation doesn't work.
Here's what I have tried:
From settings.py
APP_ROOT = os.path.dirname(os.path.abspath(__file__)) # refers to application_top
APP_FINALIZED = os.path.join(APP_ROOT, 'finalized')
From app.py
HOME = os.path.join(APP_FINALIZED)
print(HOME)
with open(HOME + '/description_' + str(fid) + '.json', 'w', encoding="utf-8")\
as f:
f.write(json.dumps(data, indent=4, ensure_ascii=False))
Updated: can we write this file directly to the S3 bucket, anyway?
it's working fine locally, but when I deploy it on Heroku the file doesn't create, even it doesn't show any error.
I'll add this as answer as well in case someone elese needs help.
Heroku's file system is (as far as I can remember) read-only.
Please check this answer.
I am working with django and celery. In my celery task, I instantiate a class and that class is responsible for generating and mailing a CSV file.
My problem is I am getting IOError: [Errno 13] Permission denied
when i try to do fp = open(filename, 'w'). But how do I get to know which user of my server is trying to create that file and how can I provide that user with appropriate permissions.I am working on AWS server.
My code for writing files is this:
with open(filename, 'w') as f_pointer:
os.chmod(filename, 777)
myfile = csv.writer(f_pointer)
myfile.writerow(columns)
myfile.writerows(rows)
Thanks
First check the file permission or owner , then use the property permission.
ls -l filename
Another, you should check if this user can create the filename in the directory .
The file is opened by the same user who is running the process. Now if the directory where you are creating the file or file you opening to write to are not writable by the user, then chmod will not work.
You'll have to chose the directory/file that is writable by the user.
When i want to open a file in C:\ (windows dir.) this error shows up:
PermissionError: [Errno 13] Permission denied: 'C:\h.txt'
What should i do?
I know this question has been asked several times but i can't find solution!
code:
f=open ('C:\\h.txt','w')
f.write ('python')
f.close
I am not on win machine, but give this a try, you can manage permissions using these commands
Try to open your file using os.fdopen
import os
with os.fdopen(os.open('file.txt', os.O_WRONLY | os.O_CREAT, 0600), 'w') as f:
f.write(...)
UPDATE
import os
is_accessible = os.access("C:\\temp\\python",os.F_OK) #Check if you have access, this should be a path
if is_accessible == False: #If you don't, create the path
os.makedirs("C:\\temp\\python")
os.chdir("C:\\temp\\python") # Check now if the path exist
f = os.open( "p.txt", os.O_RDWR|os.O_CREAT ) #Create the file
os.write(f, b"This is a test \n") #Try to write
os.close(f)
I'm not on a Windows machine but perhaps you should try and create this file in the directory c:\Temp.
Likewise make sure you've not got Notepad etc with that file open.