I have some problems with file serving with flask.
Firstly, my file tree:
processedMain
--processed1
--processed2
--...
--processedN
In each folder I have bunch of files that I represent it all in table where i put href link with path of each of files and pass it through route function with send_file return.
The problem is that the only way that I was able to make it work is to creating @app.route for every subfolder hardcoded, like this:
@app.route('/' + pathFits1[1] + '<id>', methods=['GET'])
def returnImg1(id):
return send_file(pathFits1[1] + id, as_attachment=True, attachment_filename=id)
@app.route('/' + pathFits1[2] +'<id>', methods=['GET'])
def returnImg2(id):
return send_file(pathFits1[2] + id, as_attachment=True, attachment_filename=id)
@app.route('/' + pathFits1[3] + '<id>', methods=['GET'])
def returnImg3(id):
return send_file(pathFits1[3] + id, as_attachment=True, attachment_filename=id)
where pathFits1[i] is path to the subfolder and id is passed when user clicks on file in web table.
Problem is that I have a lot of subfolder, and its tiring to create @app.route for each. Is this possible to create just one route for every thing?
P.S. I'm quite new to flask, so if I forgot to tell something, please tell me I will fill it out.
Solution
Actually it was embarrassingly simple. As @Dan.D pointed, flask has convertors of captured variables, for me it was all I needed, as my id variable already contains full path to file. So now it's just this 3 lines which substitute a whole bunch or duplicated code:
@app.route('/<path:id>')
def returnImg(id):
fileName = id.rsplit('/', 1)[-1]
return send_file(id, as_attachment=True, attachment_filename=fileName)
Where id is full path to file, path: is converter to path and fileName is name of file that user will download without path in it (all after last slash)