user3079275 user3079275 - 2 months ago 18
JSON Question

Serving a dynamically generated file in Flask

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?

xli xli
Answer

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)
Comments