I'm developing a Flask application and trying to access static files using the url_for() function. However, I keep encountering a "File or directory not found" error even though url_for() returns the correct path.
Here is the code regarding the issue:
@app.route("/paper/<string:id_>/read", methods=['GET'])
def readPaper(id_):
paper = session.get(Paper, id_)
fpath = url_for('static', filename=f'papers/{paper.file_path}')
print(fpath) # returns '/static/papers/BPGAA-Final.pdf'
with open(fpath, 'rb') as pdfFile:
print(pdfFile)
The error:
File "project_root/app/routes.py", line 82, in readPaper
with open(fpath, 'rb') as pdfFile:
FileNotFoundError: [Errno 2] No such file or directory: '/static/papers/BPGAA-Final.pdf'
I have tried using "f'/static/papers/{paper.file_path}'"
instead, this returns the exact same path as the url_for()
function, but still throws the error that it can't find the directory/file.
no doubt that the url_for()
function doesn't work. I'm using it somewhere else in my code to include both a logo and my css file. These work correctly.
I am dumbfounded on why my file cannot be located, does it have something to do with the open()
function?
I would appreciate some help :-)
EDIT: I have also tried putting the files im trying to open in other directories. I still get the same error..