Serve static html to new tab?

Hey @asherkhb, here’s a little snippet that does the kind of thing I think you want to do. It adds a file route to the Dash app’s underlying flask server, based on this method for serving local images in a Dash app.

In addition to that, I added target="_blank" to the html.A component to ensure the link gets opened in a new tab. This app will serve up a report called report.html saved in the same directory, but you can configure the paths however you like.

I passed a html.Button as the child of the html.A to make it look like a button that you’re clicking on, but all the work is being done by html.A.

from pathlib import Path

import dash
import dash_html_components as html
import flask

HERE = Path(__file__).parent

app = dash.Dash()

app.layout = html.A(html.Button("report"), href="/get_report", target="_blank")


@app.server.route("/get_report")
def get_report():
    return flask.send_from_directory(HERE, "report.html")


if __name__ == "__main__":
    app.run_server(debug=True)

Final note, be really careful if the path to the report you serve up is in any way determined by user input. You run the risk of people being able to serve up arbitrary files saved on your server (which would be bad!). See the code snippet in the images example which does some safety checks and throws an error if it gets something unexpected.

3 Likes