Skip to content

Commit

Permalink
Simplify determining whether script is executed as application (#4252)
Browse files Browse the repository at this point in the history
  • Loading branch information
philippjfr authored Jan 6, 2023
1 parent 1ede7de commit ff8037e
Show file tree
Hide file tree
Showing 13 changed files with 66 additions and 27 deletions.
3 changes: 3 additions & 0 deletions doc/api/state.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@ The `pn.state` object makes various global state available and provides methods
`refresh_token`
: The refresh token issued by the OAuth provider to authorize requests to its APIs (if available these are usually longer lived than the `access_token`).

`served`
:Whether we are currently inside a script or notebook that is being served using `panel serve`.

`session_args`
: When running a server session this return the request arguments.

Expand Down
58 changes: 51 additions & 7 deletions panel/io/state.py
Original file line number Diff line number Diff line change
Expand Up @@ -835,14 +835,16 @@ def _decode_cookie(self, cookie_name):

@property
def access_token(self) -> str | None:
"""
Returns the OAuth access_token if enabled.
"""
return self._decode_cookie('access_token')

@property
def refresh_token(self) -> str | None:
return self._decode_cookie('refresh_token')

@property
def app_url(self) -> str | None:
"""
Returns the URL of the app that is currently being executed.
"""
if not self.curdoc:
return
app_url = self.curdoc.session_context.server_context.application_context.url
Expand All @@ -851,6 +853,9 @@ def app_url(self) -> str | None:

@property
def curdoc(self) -> Document | None:
"""
Returns the Document that is currently being executed.
"""
try:
doc = curdoc_locked()
if doc and doc.session_context or self._is_pyodide:
Expand All @@ -862,18 +867,30 @@ def curdoc(self) -> Document | None:

@curdoc.setter
def curdoc(self, doc: Document) -> None:
"""
Overrides the current Document.
"""
self._curdoc.set(doc)

@property
def cookies(self) -> Dict[str, str]:
"""
Returns the cookies associated with the request that started the session.
"""
return self.curdoc.session_context.request.cookies if self.curdoc and self.curdoc.session_context else {}

@property
def headers(self) -> Dict[str, str | List[str]]:
"""
Returns the header associated with the request that started the session.
"""
return self.curdoc.session_context.request.headers if self.curdoc and self.curdoc.session_context else {}

@property
def loaded(self) -> bool:
"""
Whether the application has been fully loaded.
"""
curdoc = self.curdoc
if curdoc:
if curdoc in self._loaded:
Expand Down Expand Up @@ -907,6 +924,11 @@ def location(self) -> Location | None:

return loc

@property
def log_terminal(self):
from .admin import log_terminal
return log_terminal

@property
def notifications(self) -> NotificationArea | None:
from ..config import config
Expand All @@ -920,12 +942,28 @@ def notifications(self) -> NotificationArea | None:
return self._notifications.get(self.curdoc) if self.curdoc else None

@property
def log_terminal(self):
from .admin import log_terminal
return log_terminal
def refresh_token(self) -> str | None:
"""
Returns the OAuth refresh_token if enabled and available.
"""
return self._decode_cookie('refresh_token')

@property
def served(self):
"""
Whether we are currently inside a script or notebook that is
being served using `panel serve`.
"""
try:
return inspect.stack()[1].frame.f_globals['__name__'].startswith('bokeh_app_')
except Exception:
return False

@property
def session_args(self) -> Dict[str, List[bytes]]:
"""
Returns the request arguments associated with the request that started the session.
"""
return self.curdoc.session_context.request.arguments if self.curdoc and self.curdoc.session_context else {}

@property
Expand All @@ -944,6 +982,9 @@ def template(self) -> BaseTemplate | None:

@property
def user(self) -> str | None:
"""
Returns the OAuth user if enabled.
"""
from tornado.web import decode_signed_value

from ..config import config
Expand All @@ -954,6 +995,9 @@ def user(self) -> str | None:

@property
def user_info(self) -> Dict[str, Any] | None:
"""
Returns the OAuth user information if enabled.
"""
from tornado.web import decode_signed_value

from ..config import config
Expand Down
2 changes: 1 addition & 1 deletion panel/tests/pane/test_alert.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,6 @@ def manualtest_all_view():
return pn.Column(*alerts, margin=50)


if __name__.startswith("bokeh"):
if pn.state.served:
pn.extension(sizing_mode="stretch_width")
manualtest_all_view().servable()
2 changes: 1 addition & 1 deletion panel/tests/pane/test_echart.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ def plot(bar1, bar2):
return pn.pane.ECharts(my_plot, width=500, height=250)
return pn.Row(pn.Column(bar1, bar2), plot)

if __name__.startswith("bokeh"):
if pn.state.served:
# manualtest_echart().servable()
get_pyechart2().servable()
if __name__.startswith("__main__"):
Expand Down
12 changes: 2 additions & 10 deletions panel/tests/template/fast/test_fast_grid_template.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from holoviews import opts

from panel.config import config
from panel.io.state import state
from panel.layout import Column
from panel.pane import HTML, HoloViews, Markdown
from panel.param import Param
Expand All @@ -19,8 +20,6 @@
opts.defaults(opts.Ellipse(line_width=3, color=ACCENT_COLOR))




def test_template_theme_parameter():
template = FastGridTemplate(title="Fast", theme="dark")
# Not '#3f3f3f' which is for the Vanilla theme
Expand All @@ -30,8 +29,6 @@ def test_template_theme_parameter():

assert isinstance(template._get_theme(), FastGridDarkTheme)



COLLAPSED_ICON = """
<svg style="stroke: var(--accent-fill-rest);" width="18" height="18" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg" slot="collapsed-icon">
<path d="M15.2222 1H2.77778C1.79594 1 1 1.79594 1 2.77778V15.2222C1 16.2041 1.79594 17 2.77778 17H15.2222C16.2041 17 17 16.2041 17 15.2222V2.77778C17 1.79594 16.2041 1 15.2222 1Z" stroke-linecap="round" stroke-linejoin="round"></path>
Expand Down Expand Up @@ -95,7 +92,6 @@ def test_template_theme_parameter():
`from awesome_panel_extensions.frameworks import fast`.
""" # noqa


def _create_hvplot():
# Generate some data
cl1 = np.random.normal(loc=2, scale=0.2, size=(200, 200))
Expand All @@ -111,18 +107,15 @@ def _create_hvplot():
plot = clusters * hv.Ellipse(2, 2, 2) * hv.Ellipse(-2, -2, (4, 2))
return plot


def _navigation_menu():
return HTML(NAVIGATION_HTML)


def _sidebar_items():
return [
Markdown("## Settings"),
_navigation_menu(),
]


def _fast_button_card():
button = Button(name="Click me", button_type="primary")
button.param.name.precedence = 0
Expand Down Expand Up @@ -152,7 +145,6 @@ def _fast_button_card():
sizing_mode="stretch_both",
)


def manualtest_app():
app = FastGridTemplate(
title="FastGridTemplate w. Layout Persistence",
Expand All @@ -175,6 +167,6 @@ def manualtest_app():
return app


if __name__.startswith("bokeh"):
if state.served:
config.sizing_mode = "stretch_width"
manualtest_app().servable()
2 changes: 1 addition & 1 deletion panel/tests/template/fast/test_fast_list_template.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,6 @@ def test_accent():
assert template.header_background==accent


if __name__.startswith("bokeh"):
if pn.state.served:
pn.extension(sizing_mode="stretch_width")
manualtest_app().servable()
2 changes: 1 addition & 1 deletion panel/tests/template/test_manual.py
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ def _get_app():
theme = _get_theme()
return template_func(template_class=template_class, theme=theme)

if __name__.startswith("bokeh"):
if pn.state.served:
pn.extension(sizing_mode="stretch_width")
_get_app().servable()
# manualtest_template_with_no_sidebar().servable()
2 changes: 1 addition & 1 deletion panel/tests/template/test_vanilla_manual.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ def cosine(freq, phase):
return vanilla


if __name__.startswith("bokeh"):
if pn.state.served:
pn.extension(sizing_mode="stretch_width")
manualtest_vanilla_with_sidebar().servable()
# manualtest_vanilla_with_no_sidebar().servable()
2 changes: 1 addition & 1 deletion panel/tests/widgets/test_speech_to_text.py
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,6 @@ def update_result_panel(results_last):
return app


if __name__.startswith("bokeh"):
if pn.state.served:
pn.extension(sizing_mode="stretch_width")
manualtest_get_color_app().servable()
2 changes: 1 addition & 1 deletion panel/tests/widgets/test_terminal.py
Original file line number Diff line number Diff line change
Expand Up @@ -220,5 +220,5 @@ def get_app():
return template


if __name__.startswith("bokeh"):
if pn.state.served:
get_app().servable()
2 changes: 1 addition & 1 deletion panel/tests/widgets/test_text_to_speech.py
Original file line number Diff line number Diff line change
Expand Up @@ -297,6 +297,6 @@ def manualtest_get_app():
return template


if __name__.startswith("bokeh"):
if pn.state.served:
pn.extension(sizing_mode="stretch_width")
manualtest_get_app().servable()
2 changes: 1 addition & 1 deletion panel/tests/widgets/test_tqdm.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,6 @@ def run(*events):
tqdm, button
)

if __name__.startswith("bokeh"):
if pn.state.served:
# get_tqdm_app_simple().servable()
get_tqdm_app().servable()
2 changes: 1 addition & 1 deletion panel/tests/widgets/test_trend_indicator.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,5 +98,5 @@ def update_datasource():
return app


if __name__.startswith("bokeh"):
if state.served:
manualtest_app().servable()

0 comments on commit ff8037e

Please sign in to comment.