-1

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..

  • url_for gives you the public path under which the resource is available over http (hence "url"). You should give that path to the client (i.e. browser), and they can open it. You cannot use that as a file path and open the file. – zvone May 17 '23 at 13:30
  • I already thought so indeed, but see my edit. I should be able to open files outside of the static directory then without url_for() no? – jimdijkemans May 17 '23 at 13:56
  • Why so complicated? static files downloads can be [implemented by one line](https://stackoverflow.com/a/20648053/13946204) – rzlvmp May 18 '23 at 12:49
  • @rzlvmp In retrospect, this was indeed a bad way to do this. My idea was to process the PDF file in the backend, to convert it to text and display it on my page like that. This however didn't really workout as i intended. I now serve the PDF by embedding it using the tag. – jimdijkemans May 18 '23 at 12:53

1 Answers1

0

Found out that url_for() is only used for serving files to the front-end. I was still struggling on why my files cannot be found when u manually input the path, when they are not in my static folder.

Turns out i needed to start all the way from the root of the project: Instead of /pdf/{file_name}, I had to use path.join(app.root_path, 'pdf')

My file structure was as follows: app/(folder with my entrypoint)/pdfs/{file_name}.