How to send a file from a network drive in Flask

Issue

I’m working on a web app that once the user sets the file id that he’s looking for the file would be sent. The problem that I’m facing is that the files are stored in a network drive and not in Flask’s static folder. How can I make Flask be able to access these files and forward them to the user?

Once the user types the ID, a webservice pulls the file’s path. Something like:

file:\\\\\server\folder1\folder2\folder3\file.txt

I’ve tried several ways of handling it, but none worked on the Flask environment. I always get the message that the file doesn’t exist.
Unit is mapped on Windows.

The structure is something like this

My computer
|
|---C:/folder1/flask folder
|
|
|---T:/folder with files to send

Solution

All static files must be in static folder. Some oprions you have:

  1. Copy the files that are elsewhere on your filesystem into that folder
  2. Add some code to your server script that copies the files from their origin to the static files folder
  3. Put your server script on your external drive, so your static folder is on that drive, and run it from there. If you need to serve content from several folders on that drive you might be able to create shortcuts to those folders under static folder but I can’t test right now , on Windows I doubt this will work (on Linux very likely that symbolic links would work).
  4. You could have one flask app running for each different folder where you have static content, listening on a different port. Those apps would all be identical. Your HTML served by your main app would have links with those ports.
  5. Find where in the source flask looks for the source folder, and extend by a few lines of code to be able to look in other folders.
  6. Use flask.send_file and flask.send_file_from_directory: as long as your database contains a mapping of file ID’s to file paths, and you put the file ID’s in the HTML served to client, then when client requests the file, your flask app uses the ID in the URL to determine file location and uses flask.send_file_from_directory to serve the file.
  7. You might also be able to use Flask Blueprints since each blueprint can have its own static folder

Answered By – Arsh Jamadar

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published