Forums

Flask, Folium and file naming mystery

Hello, The code below runs without any problems if the HTML file i'm rendering is called footprint.html, if I change the name i get an internal server error. the file is still generated but the page is not accessible 500 error. here is the code

@app.route('/maps')
def home():
    df = pd.read_csv("/home/user_name/bloodtypes/abo.csv", delimiter=',')
    df.columns = df.columns.str.strip()
    political_countries_url = (
        "http://geojson.xyz/naturalearth-3.3.0/ne_50m_admin_0_countries.geojson"
    )

    m = folium.Map(location=(30, 10), zoom_start=3, tiles="cartodb positron")
    folium.Choropleth(
        geo_data=political_countries_url,
        data=df,
        columns=("Country", "O", "A", "B"),
        key_on="feature.properties.name",
        fill_color="RdYlGn_r",
        fill_opacity=0.8,
        line_opacity=0.3,
        nan_fill_color="white",
        legend_name="Blood type distribution by country",
    ).add_to(m)

    m.save("/home/user_name/bloodtypes/maps/templates/footprint.html")

    return render_template("footprint.html")

Would greatly appreciate any help. Thanks in advance!

[edit by admin: formatting]

I really would not recommend updating Flask templates dynamically in your code -- it's likely to make all kinds of things go wrong, because Flask isn't written to handle it. You should see templates as being kind of like code -- they stay fixed while the website is running. Things that change dynamically from request to request should be put into variables and passed in to the template. If all you want to do is return the contents of the variable m as a response, just convert it to a string and return it directly rather than overwriting the template file with it -- that is, if m has a to_string method, you'd do this instead of the last two lines:

return m.to_string()

Thanks for your reply! I changed the last two lines with return m.to_string() still getting 500 error. Obviously, I don't understand what I'm doing, I'm experimenting and learning. The thing is I checked and the rendered file is updating in the templates folder, but Flask gives me an error that it can't find the file, if I change the name of the file to anything but "footprint.html". If I name the rendered file "footprint.html" then the page is accessible but the file is not updated. Most likely I need to clear the cache or something but don't know how.

I figured it out., flask renders templates only from the directory where the main app is even if you use the full path.("/home/user_name/bloodtypes/maps/templates/footprint.html") so instead of creating a new templates folder in the maps directory, I should have used the existing templates file in the main directory. ... m.save("/home/user_name/bloodtypes/templates/footprint.html") . Thanks anyway for the reply!

solved

Glad to hear that!