【问题标题】:How to send some values through url from a flask app to dash app ? flask and dash app are running independently如何通过 url 从烧瓶应用程序发送一些值到破折号应用程序? flask 和 dash 应用程序独立运行
【发布时间】:2021-09-11 22:25:31
【问题描述】:

我有一个在一端运行的烧瓶应用程序和一个破折号应用程序都单独运行,但我在烧瓶应用程序主页中有一个链接,单击该链接会重定向到破折号应用程序,但我想将一些值(例如当前 user_id)传递给破折号应用程序在重定向到 dash 应用程序时,然后我想从 URL 读取该值,然后我可以显示它 dash 主页。

如果有人可以帮助我,请帮助我。

【问题讨论】:

  • 如果它是一个链接,那么只需像在 GET 请求中一样添加参数:<a link="https://www.example.com/dash/otherapi?userid=17116">
  • 但是我如何在dash app中读取这些参数值
  • 我假设您的“dash”应用程序也在作为 Web 服务器进行侦听。 Dash 非常灵活;有很多方法可以获取数据。您现在如何获取数据?

标签: python flask integration plotly-dash


【解决方案1】:

这个Dash tutorial 页面解释了如何使用dcc.Location 处理URL。您可以获取路径名作为回调输入,并使用像urllib 这样的库来解析它。

这个sn-p改编自一个例子和这个StackOverflow thread

import urllib.parse

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

app = dash.Dash(__name__)

app.layout = html.Div([
    dcc.Location(id='url', refresh=False),
    html.Div(id='page-content')
])


@app.callback(Output('page-content', 'children'),
              Input('url', 'pathname'))
def display_page(pathname):
    if pathname.startswith("my-dash-app"):
        # e.g. pathname = '/my-dash-app?firstname=John&lastname=Smith&birthyear=1990'

        parsed = urllib.parse.urlparse(pathname)
        parsed_dict = urllib.parse.parse_qs(parsed.query)
        
        print(parsed_dict)
        # e.g. {'firstname': ['John'], 'lastname': ['Smith'], 'birthyear': ['1990']}

        # use parsed_dict below
        # ...

        return page_content

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

【讨论】:

    【解决方案2】:

    来自 location 的 search 参数将返回 URL 参数作为字符串,pathname 对我不起作用,如 @xhlulu 回答中所述:

    @app.callback(Output('page-content', 'children'),
                  Input('url', 'search'))  # <--- this has changed
    def display_page(params):
        # e.g. params = '?firstname=John&lastname=Smith&birthyear=1990'
        parsed = urllib.parse.urlparse(params)
        parsed_dict = urllib.parse.parse_qs(parsed.query)
    
        print(parsed_dict)
        # e.g. {'firstname': ['John'], 'lastname': ['Smith'], 'birthyear': ['1990']}
    
        # use parsed_dict below
        # ...
    
       return page_content
    

    【讨论】:

    • 'pathname' 将忽略任何搜索条件。 “搜索”将忽略路径。此输入标准将同时获得。 @app.callback(Output('url-content', 'children'), [Input('url', 'pathname'), Input('url', 'searchdata')]) def display_page(pathname,searchdata): ...
    猜你喜欢
    • 2018-10-25
    • 2021-09-10
    • 2018-02-01
    • 2015-07-05
    • 2015-09-07
    • 2018-12-13
    • 1970-01-01
    • 2020-03-17
    相关资源
    最近更新 更多