Dash + Flask request args

In flask, normally you can:

@server.route('/args/')
def args():
   name = request.args.get('name')
   age = request.args.get('age')
   return "name: {}  age: {}".format(name, age)

With a URL like:

http://localhost:8000/args/?name=matt&age=100

(over simplified example)
Currently referenceing the following links:

https://dash.plot.ly/urls

stack overflow discussion

How would this work with dash, because I would like the args from the server.route to get passed into an app.callback?
I really would like to try and integrate the above code, I want to avoid the following:

@app.callback(
[Output('display-name','children'),
Output('display-age','children')]
[Input('url','pathname')])
def load_page(pathname):
    ##parse through the args with regex or str.split()
    return name, age

What exactly do you want to avoid in your example? You’ve got the url so you just use Python’s standard library to parse it, e.g.:

import urllib.parse

...

@app.callback(
    [Output('display-name', 'children'), Output('display-age', 'age')]
    [Input('url', 'pathname')]
)
def load_page(url):
    parsed_url = urllib.parse.urlparse(url)
    parsed_query = urllib.parse.parse_qs(parsed_url.query)
    name = parsed_query['name'][0]
    age = parsed_query['age'][0]
    return name, age

You can also get the url using flask.request.headers.get('Referer') but I would not recommend it except for dynamic layouts, you also still need to parse it.

Ahh great, this is exactly what I was looking for! (In hindsight I should have considered urllib…)

I want to avoid the following

To this I was referring to the bottom portion of my original post

##parse through the args with regex or str.split()

urllib.parse solves this perfectly. Thank you again :smile:

EDIT:
I did want to point out that in testing this with dash, my url was the following: http://localhost:8000/?name=matt&age=1000

Using the code provided above, I debugged what Dash picked up as the input URL in the callback, and also logged the parsed_url and parsed_query objects:

pathname: /
parsed_url: ParseResult(scheme='', netloc='', path='/', params='', query='', fragment='')
parsed_query={}

Thus I changed my URL to: http://localhost:8000/name=matt&age=1000 (note I removed the ‘?’)

So then I had to alter your code slightly:

parsed_url = urllib.parse.urlparse(url[1:])
parsed_query = urllib.parse.parse_qs(parsed_url.path)
1 Like