How to open a .txt file in Flask? [duplicate] - python

This question already has an answer here:
Refering to a directory in a Flask app doesn't work unless the path is absolute
(1 answer)
Closed 5 years ago.
I'm trying to build a website using the Flask framework for Python.
I'm on a Linux Ubuntu server, with Apache2.
On my website, whenever someone enters the URL "/Elv_1.html", I want to open a .txt file, get some values and create a graph using pygal. Here is my code:
#app.route('/river_1.html')
def riv_1():
try:
document = open('temp.txt','r')
temp_list = []
for n in document:
n = n.rstrip('\n')
n = int(n)
temp_list.append(n)
document.close()
graf = pygal.Line(title=u'Tempt last 24h')
graf.x_labels = (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24)
graf.add('Temp', temp_list)
graf = graf.render_data_uri()
return render_template('river_1.html', graf=graf)
except Exception, e:
return str(e)
if __name__ == '__main__':
app.run(debug=True)
The file 'temp.txt' is located in the same directory as the __init__.py file. __init__.py is the Flask app that the code comes from.
When I do this on my computer using localhost to run the server, it works just fine. However, when I upload this to my Linux server and try to enter that specific URL, it shows the following error:
[Error 2] No such file or directory: 'temp.txt'
Any suggestions as to why it doesn't appear to find the file?

Try using the os module when specifying the path to your file. I am asuming you are using a windows pc when runing on localhost?
import os
document_path = os.getcwd()+'temp.txt'
document = open(documnet_path, 'r')

Make sure you are running the server from it's directory. So if you have this structure as shown below, you can't simply open terminal and type server/__init__.py, because you are in your home directory (/home/username/). You need to cd to server and there run ./__init__.py
/home/
username/
server/
__init__.py
temp.txt
Or, if you want to run it from somewhere else, run open the file from os.path.abspath(os.path.dirname(__file__)) + '/temp.txt') (Tested with python 3.5.2)
See python docs for os.path.

Related

Compiled exe needs to be run as admin but uncompiled py file doesn't?

I recently compiled a python project I have been working on for some time to an exe, only to find you'd need to run it as an administrator for it to work, despite it not requiring any elevation while it was simply a .py file. It returns an internal error "cannot create temporary directory!" if you don't run it with elevation. I presume this has to do something with the program reading/writing to the users appdata/locallow folder (it stores some of it's files in there). Is there a simple fix to this? I'd much prefer it if the apps files could remain in one of the appdata folders whether it be local, locallow or roaming.
This can be reproduced by following these steps:
create a main.py file with the following code inside:
import os, json
LOG_DIR = os.path.expanduser('~\AppData\Locallow\AppName\logs')
LOG_PATH = os.path.expanduser('~\AppData\Locallow\AppName\logs\log.txt')
PREFS_DIR = os.path.expanduser('~\AppData\Locallow\AppName\prefs')
PREFS_PATH = os.path.expanduser('~\AppData\Locallow\AppName\prefs\prefs.json')
user_prefs = None
def log_init():
if os.path.isfile(LOG_PATH):
with open(LOG_PATH, 'a') as f:
f.close()
else:
if not os.path.isdir(LOG_DIR):
os.mkdir(LOG_DIR)
with open(LOG_PATH, 'w') as f:
f.close()
def prefs_init():
global user_prefs
if os.path.isfile(PREFS_PATH):
user_prefs = json.load(open(PREFS_PATH, 'r'))
else:
if not os.path.isdir(PREFS_DIR):
os.mkdir(PREFS_DIR)
with open(PREFS_PATH, 'w') as f:
f.write('{"welc_msg": "DirNav - The all in one file browser and terminal!", "file_color": {}}')
f.close()
user_prefs = json.load(open(PREFS_PATH, 'r'))
log_init()
prefs_init()
Make the following folder: C:/Users/YOUR_USER/AppData/Locallow/AppName
Running main.py will generate 'prefs' and 'logs' with respective files inside.
Delete 'prefs' and 'logs'
Compile main.py using this command: pyinstaller -F main.py
Running the new .exe that is in the 'dist' folder from cmd will result in an 'INTERNAL ERROR: cannot create temporary directory!' message.
Run the .exe again but this time run as an administrator and it will work perfectly fine
The main premise here is why does the executable need to be run as an admin yet the .py file doesn't? And how do I make it so the executable doesn't need to be run as an admin?

Real path to config.ini in python binary *app in MacOS

I have this code:
def _read_config(self):
config = configparser.ConfigParser()
config.sections()
# I tried
path_main = os.path.dirname(os.path.realpath(__file__))
# and this after create exec file with pyinstaller nothing changed
path_main = os.getcwd()
print(path_main)
file = os.path.join(path_main, "config.ini")
print(file)
config.read(file)
return config
When I run the code in MacOS using the terminal with python gui.py, it prints this:
/Users/telos/Desktop/Telos-Monitor-Tool/client
/Users/telos/Desktop/Telos-Monitor-Tool/client/config.ini
But when I do pyinstaller --onefile --windowed gui.py, I receive 1 app file, when I run it I get this:
/Users/telos
/Users/telos/config.ini
But the one file app and ``gui.py` is in the same directory.
So I have an error because the Python parser can't find config.ini.
As in comennt discasion advise me to use print(QtCore.QCoreApplication.applicationDirPath()) after recreating app, i have 2 file 1 gui.app, 2-nd gui.exec. gui.exec find config.ini fine and all work fine, but gui.app can't and send the error.
Any idea what is the problem?
Since you are using PyQt5 if you want to get the executable folder you can use:
QtCore.QCoreApplication.applicationDirPath()

Python with open doesn't create new file after deployed at Heroku

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.

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 1.9 | views.py | execute *.bat file | location for save file

I have 2 questions(I could not find answer on stackoverflow):
First question:
I added run_command.bat file to:
DjangoProj/
---DjangoApp/
------views.py
------run_command.bat
In method save_logs in DjangoProj/DjangoApp/views.py I tried:
def save_logs(request):
choosenMachines = request.GET.getlist('mvsMachine')
(data,errors) = subprocess.Popen(r'run_command.bat' + str(choosenMachines), shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE).communicate()
But I got this error:
the run_command.bat is not recognize as external or internal command,
exec file or batch file
I suppose that Django is currently in another path(the question is which)
And second question:
Where is saved txt file created by method from DjangoProj/DjangoApp/views.py
def set_parameters_on_ftp(request):
with open('start_task.txt', 'w') as f:
for command in commands:
f.write(command+'\n')
return
It suppose it should be in: DjangoProj/DjangoApp/*
For the first question:
import os
#Set myPath variable to the path of the file being executed
myPath = os.path.dirname(os.path.abspath(__file__))
#Change current working directory to myPath
os.chdir(myPath)
#Or change current working directory to a subdirectory of myPath
os.chdir(os.path.join(myPath, 'subFolder'))
For the second question:
import os
#Check the current working directory. The txt file is getting saved here.
os.getcwd()
#This can be changed by changing the working directory as described in the answer to the first question.
EDIT: Changed the os.chdir() syntax error in the first part.
Your guess was true.
Django current running path is not in your project folder.
In my testing it was in C:\Python27
you must give exact path or use PROJECT_ROOT variable in settings file.
Have fun

Categories

Resources