Hey dash users,
I have a use case where a button, when pressed, should open a new tab with a static HTML report. I’ve looked around but haven’t seen anything like this…
So…does anyone know if it is possible to serve a static HTML file to a new tab?
Thanks!
Asher
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
Thanks @tcbegley - this works perfect for serving up a report! Any ideas on how it could be adjusted to serve multiple reports?
I was thinking of using the <a> tags “onclick” function, e.g.
onclick="window.open('/get_report/1'); window.open('/get_report/2');"
But such functionality doesn’t seem to exist (yet)…
If I understood right you want to open multiple different reports in different tabs when you click a button?
It’s possible to hack this together, but I don’t know if I would recommend it. Here’s what I managed to get working:
Modify app code
from pathlib import Path
import dash
import dash_html_components as html
import flask
HERE = Path(__file__).parent
app = dash.Dash()
app.layout = html.Button("Open reports", id="button")
@app.server.route("/get_report/<int:report_number>")
def get_report(report_number):
return flask.send_from_directory(HERE, f"report_{report_number}.html")
if __name__ == "__main__":
app.run_server(debug=True)
I then added the following javascript to assets/scripts.js
(saving to assets/
means it gets picked up automatically by Dash)
function openReports() {
window.open('/get_report/1');
window.open('/get_report/2');
}
window.onload = function() {
document.getElementById("button").onclick = openReports;
}
Sorry, wenn i run you code , i get the following Erroewarning
AttributeError: ‘WindowsPath’ object has no attribute ‘endswith’
do you habe some idea?