从Dash / Flask应用下载动态生成的文件

时间:2019-01-30 15:01:11

标签: python flask plotly-dash

我尝试构建一个Dash应用程序的最小示例,该示例说明了动态生成文件然后可以通过下载按钮下载的问题。

如果运行此示例,您将看到一个文本区域,可以在其中输入文本。单击“输入”按钮会将文本存储到文件中,并为该文件创建一个下载按钮。

enter image description here

import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State

import uuid

stylesheets = [
    "https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.2/css/bulma.min.css", # Bulma
]

# create app
app = dash.Dash(
    __name__,
    external_stylesheets=stylesheets
)


app.layout = html.Div(
    className="section",
    children=[
        dcc.Textarea(
            id="text-area",
            className="textarea",
            placeholder='Enter a value...',
            style={'width': '300px'}
        ),
        html.Button(
            id="enter-button",
            className="button is-large is-outlined",
            children=["enter"]
        ),
        html.Div(
            id="download-area",
            className="block",
            children=[]
        )
    ]
)

def build_download_button(uri):
    """Generates a download button for the resource"""
    button = html.Form(
        action=uri,
        method="get",
        children=[
            html.Button(
                className="button",
                type="submit",
                children=[
                    "download"
                ]
            )
        ]
    )
    return button

@app.callback(
    Output("download-area", "children"),
    [
        Input("enter-button", "n_clicks")
    ],
    [
        State("text-area", "value")
    ]
)
def show_download_button(n_clicks, text):
    # turn text area content into file
    filename = f"{uuid.uuid1()}.txt"
    path = f"downloadable/{filename}"
    with open(path, "w") as file:
        file.write(text)
    uri = path
    return [build_download_button(uri)]


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

但是,生成的URI似乎是不正确的,因为单击按钮只是将重定向到索引页面。要使其正常工作需要什么?

3 个答案:

答案 0 :(得分:2)

由于Dash是基于Flask构建的,因此flask无法找到所生成文本文件的URI。

解决方案是添加烧瓶路由以重定向以下载资源, 在官方的情节破折号存储库中有一个简单的示例, https://github.com/plotly/dash-recipes/blob/master/dash-download-file-link-server.py

下面修改的代码可以解决您的问题

import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State

import uuid
import os
import flask
stylesheets = [
    "https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.2/css/bulma.min.css", # Bulma
]

# create app
app = dash.Dash(
    __name__,
    external_stylesheets=stylesheets
)


app.layout = html.Div(
    className="section",
    children=[
        dcc.Textarea(
            id="text-area",
            className="textarea",
            placeholder='Enter a value...',
            style={'width': '300px'}
        ),
        html.Button(
            id="enter-button",
            className="button is-large is-outlined",
            children=["enter"]
        ),
        html.Div(
            id="download-area",
            className="block",
            children=[]
        )
    ]
)

def build_download_button(uri):
    """Generates a download button for the resource"""
    button = html.Form(
        action=uri,
        method="get",
        children=[
            html.Button(
                className="button",
                type="submit",
                children=[
                    "download"
                ]
            )
        ]
    )
    return button

@app.callback(
    Output("download-area", "children"),
    [
        Input("enter-button", "n_clicks")
    ],
    [
        State("text-area", "value")
    ]
)
def show_download_button(n_clicks, text):
    if text == None:
        return
    # turn text area content into file
    filename = f"{uuid.uuid1()}.txt"
    path = f"downloadable/{filename}"
    with open(path, "w") as file:
        file.write(text)
    uri = path
    return [build_download_button(uri)]

@app.server.route('/downloadable/<path:path>')
def serve_static(path):
    root_dir = os.getcwd()
    return flask.send_from_directory(
        os.path.join(root_dir, 'downloadable'), path
    )

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

另外,也可以使用static目录代替downloadable目录,这将正常工作。

有关flask静态目录的更多信息: http://flask.pocoo.org/docs/1.0/tutorial/static/

这是摘要,

#your code

def show_download_button(n_clicks, text):
    if text == None:
        return
    filename = f"{uuid.uuid1()}.txt"
    path = f"static/{filename}"      # =====> here change the name of the direcotry to point to the static directory
    with open(path, "w") as file:
        file.write(text)
    uri = path
    return [build_download_button(uri)]

#your code

答案 1 :(得分:1)

解决方案在这里:

import uuid

import dash
from dash.dependencies import Input, Output, State
import flask
from flask.helpers import send_file

import dash_core_components as dcc
import dash_html_components as html

stylesheets = [
    "https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.2/css/bulma.min.css", # Bulma
]

server = flask.Flask('app')

# create app
app = dash.Dash(
    __name__,
    external_stylesheets=stylesheets, 
    server=server                       # <-- do not forget this line
)

# (...) your code here

@server.route("/downloadable/<path>")
def download_file (path = None):
    return send_file("downloadable/" + path, as_attachment=True)

答案 2 :(得分:1)

在 Dash 1.20.0 中,您现在拥有一个用于基于用户的动态下载的 %eax) 组件。它不需要创建自定义按钮 dcc.Downloaduuid

flask.send_file
相关问题