Grabbing URL before serving Dash layout

@chriddyp
Hi Chris,

We were wondering if there was some way to grab the URL before serving the Dash app layout. We are currently setting app.layout to a function (as seen in your tutorial here: Live Updates | Dash for Python Documentation | Plotly), but need this URL to update a component within the layout.

def serve_layout():

   # We need to grab the URL here to update a component below
   # We tried url_string = request.url here, but failed (see below)

   return html.Div([ ... ])

app.layout = serve_layout()

Ideally, we would use the dcc.Location component to grab the URL through ‘pathname,’ however, this component is not initialized yet. We thought to use Flask’s request.url function, but this is not accessible from this function (error: RuntimeError: Working outside of request context.). How can we access the request? Or any other ideas to get this URL?

Best,

Jonathan

If you render your content dynamically using dcc.Location and dcc.Link then your callback function that renders the content will be called on every page load and on every new URL automatically - you won’t need serve_layout anymore.

Adapting from the example here: https://plot.ly/dash/urls

app.layout = html.Div([
    # represents the URL bar, doesn't render anything
    dcc.Location(id='url', refresh=False),

    # content will be rendered in this element
    html.Div(id='page-content')
])


@app.callback(dash.dependencies.Output('page-content', 'children'),
              [dash.dependencies.Input('url', 'pathname')])
def display_page(pathname):
    # this is called every page load and every URL change
    # you can update your components with this URL in here
    return html.Div([
        html.H3('You are on page {}'.format(pathname))
    ])
1 Like

Hi @chriddyp,

Thanks, this was really helpful! It seems to be an error with no consequences, but I’m noticing that dcc.Location initializes its pathname as None in the beginning. The callback seems to be firing multiple times upon browser open, where the first time pathname=None, and then subsequent times it’s correct with the URL.

Best,

Jonathan Hsu

@jyhsu - Yeah, that’s done for a couple of reasons, see https://github.com/plotly/dash/issues/133#issuecomment-330714608 for more details.

So, what you can do is either return 'Loading...' or simply '' when pathname is None. It’ll get called after everything renders again with the proper pathname.

1 Like