2

I am running a Flask application where the user makes a GET request by typing something in a text box. The backend code that receives the GET request does some computations on the query parameter and sends back the name of 2 or 3 newly created json files that are created as a result of the computations. The user can then view some graphs created from the JSON files depending on some filtering chosen by the user. My issue is that I want these json files to be stored in a folder called data (and they accumulate over time for various reasons and for faster response). My app structure is roughly:

/data
/static
/templates
/python src files

Now I can get the html code to GET the files under static but it doesnt work for the files under the data folder. How do I let Flask know that a GET request on the data folder be allowed?

user2399453
  • 2,930
  • 5
  • 33
  • 60

2 Answers2

2

You can use send_from_directory() to serve files from /data.

@app.route('/data/<path:filepath>')
def data(filepath):
    return send_from_directory('data', filepath)
xli
  • 1,298
  • 1
  • 9
  • 30
  • Thanks, I will try this, is it possible for the filename to be under another level of directories also? For eg /data/dir1/f1.json or /data/dir2/f2.json etc – user2399453 Sep 25 '16 at 03:19
  • I modified my answer to allow subdirectories. Also, there was a small error previously: it should be 'data' and not '/data' for the directory path. – xli Sep 25 '16 at 03:24
  • Thanks after I try it and if it works I will accept your answer. It will take me a few hours. Thanks a lot – user2399453 Sep 25 '16 at 03:30
0

Why not have the caching logic in the action function? If the file has already been cached then feed it out from a single file load. I would imaging you would also want access control and that would not happen by serving static files from the HTTP service.

JamesH
  • 36
  • 4
  • I dont understand the term action function, is it the front end code that requests the JSON files? The html code does not know the names of the JSON files that it will need to parse because it depends on the result of a computation done by the backend code. Once the backend sends a response back with the names of the JSON files the html code can then filter them depending on user interactions. – user2399453 Sep 25 '16 at 03:17