You can additionally rely on the state property session_args that returns a dict of query parameters to their bytes-encoded values. It’s useful when you only need to catch the query parameters and not sync them. Search for session_args on these pages for more details:
Thanks @ahuang11 and @maximlt, it works using .servable() on a much smaller project mimicking your example, but fails with panel serve app.py on my project which uses serve(). state and session_args never seems to be populated, possibly I’m trying to access them in the wrong place. I’ll dig in a little further.
@justinwiley i’ve created examples, how to correct use pn.serve and get pn.state.location
import panel as pn
if 'page' in pn.state.location.query_params:
page = pn.state.location.query_params['page']
else:
page = 'home'
def view():
return pn.pane.Markdown(f"# This is the {page} page")
if __name__ == '__main__':
pn.serve(view)
AttributeError: 'NoneType' object has no attribute 'query_params'
Solution:
To fix the error, move any code that depends on pn.state.location inside the function passed to pn.serve(), ensuring it runs within the session context:
import panel as pn
def view():
query_params = pn.state.location.query_params
if 'page' in query_params:
page = query_params['page']
else:
page = 'home'
return pn.pane.Markdown(f"# This is the {page} page")
if __name__ == '__main__':
pn.serve(view)
Now, if you navigate for example to /?page=example, you will get: this is the example page