Skip to content

Commit cf170a3

Browse files
authored
Merge pull request #521 from rstudio/shiny-express
2 parents 5c8a21e + d9e230a commit cf170a3

File tree

3 files changed

+133
-10
lines changed

3 files changed

+133
-10
lines changed

CHANGELOG.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
99
### Added
1010
- Added the name of the environment variables to the help output for those options that
1111
use environment variables as a default value.
12+
- Added support for deploying Shiny Express applications.
1213

1314
### Changed
14-
- Improved the error and warning outputs when options conflict by providing the source
15+
- Improved the error and warning outputs when options conflict by providing the source
1516
from which the values have been determined. This allows for faster resolution of issues
1617
when combinations of stored credentials, environment variables and command line options
1718
are used.

rsconnect/main.py

Lines changed: 32 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,7 @@
8080
produce_bootstrap_output,
8181
parse_client_response,
8282
)
83+
from .shiny_express import escape_to_var_name, is_express_app
8384

8485
server_store = ServerStore()
8586
future_enabled = False
@@ -123,7 +124,7 @@ def output_params(
123124
if k in {"api_key", "api-key"}:
124125
val = "**********"
125126
sourceName = validation.get_parameter_source_name_from_ctx(k, ctx)
126-
logger.log(VERBOSE, " %-18s%s (from %s)", (k+":"), val, sourceName)
127+
logger.log(VERBOSE, " %-18s%s (from %s)", (k + ":"), val, sourceName)
127128

128129

129130
def server_args(func):
@@ -1013,7 +1014,7 @@ def deploy_voila(
10131014
server: str = None,
10141015
api_key: str = None,
10151016
insecure: bool = False,
1016-
cacert: typing.IO = None,
1017+
cacert: str = None,
10171018
connect_server: api.RSConnectServer = None,
10181019
multi_notebook: bool = False,
10191020
no_verify: bool = False,
@@ -1288,7 +1289,7 @@ def deploy_html(
12881289
server: str = None,
12891290
api_key: str = None,
12901291
insecure: bool = False,
1291-
cacert: typing.IO = None,
1292+
cacert: str = None,
12921293
account: str = None,
12931294
token: str = None,
12941295
secret: str = None,
@@ -1324,7 +1325,6 @@ def deploy_html(
13241325

13251326

13261327
def generate_deploy_python(app_mode: AppMode, alias: str, min_version: str, desc: Optional[str] = None):
1327-
13281328
if desc is None:
13291329
desc = app_mode.desc()
13301330

@@ -1415,17 +1415,40 @@ def deploy_app(
14151415
no_verify: bool = False,
14161416
):
14171417
set_verbosity(verbose)
1418-
output_params(ctx, locals().items())
1419-
kwargs = locals()
1420-
kwargs["entrypoint"] = entrypoint = validate_entry_point(entrypoint, directory)
1421-
kwargs["extra_files"] = extra_files = validate_extra_files(directory, extra_files)
1418+
entrypoint = validate_entry_point(entrypoint, directory)
1419+
extra_files = validate_extra_files(directory, extra_files)
14221420
environment = create_python_environment(
14231421
directory,
14241422
force_generate,
14251423
python,
14261424
)
14271425

1428-
ce = RSConnectExecutor(**kwargs)
1426+
if is_express_app(entrypoint + ".py", directory):
1427+
entrypoint = "shiny.express.app:" + escape_to_var_name(entrypoint + ".py")
1428+
1429+
extra_args = dict(
1430+
directory=directory,
1431+
server=server,
1432+
exclude=exclude,
1433+
new=new,
1434+
app_id=app_id,
1435+
title=title,
1436+
visibility=visibility,
1437+
disable_env_management=disable_env_management,
1438+
env_vars=env_vars,
1439+
)
1440+
1441+
ce = RSConnectExecutor(
1442+
name=name,
1443+
api_key=api_key,
1444+
insecure=insecure,
1445+
cacert=cacert,
1446+
account=account,
1447+
token=token,
1448+
secret=secret,
1449+
**extra_args,
1450+
)
1451+
14291452
(
14301453
ce.validate_server()
14311454
.validate_app_mode(app_mode=app_mode)

rsconnect/shiny_express.py

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
# The contents of this file are copied from:
2+
# https://github.com/posit-dev/py-shiny/blob/feb4cb7f872922717c39753514ae2d7fa32f10a1/shiny/express/_is_express.py
3+
4+
from __future__ import annotations
5+
6+
import ast
7+
from pathlib import Path
8+
import re
9+
10+
__all__ = ("is_express_app",)
11+
12+
13+
def is_express_app(app: str, app_dir: str | None) -> bool:
14+
"""Detect whether an app file is a Shiny express app
15+
16+
Parameters
17+
----------
18+
app
19+
App filename, like "app.py". It may be a relative path or absolute path.
20+
app_dir
21+
Directory containing the app file. If this is `None`, then `app` must be an
22+
absolute path.
23+
24+
Returns
25+
-------
26+
:
27+
`True` if it is a Shiny express app, `False` otherwise.
28+
"""
29+
if not app.lower().endswith(".py"):
30+
return False
31+
32+
if app_dir is not None:
33+
app_path = Path(app_dir) / app
34+
else:
35+
app_path = Path(app)
36+
37+
if not app_path.exists():
38+
return False
39+
40+
try:
41+
# Read the file, parse it, and look for any imports of shiny.express.
42+
with open(app_path) as f:
43+
content = f.read()
44+
tree = ast.parse(content, app_path)
45+
detector = DetectShinyExpressVisitor()
46+
detector.visit(tree)
47+
48+
except Exception:
49+
return False
50+
51+
return detector.found_shiny_express_import
52+
53+
54+
class DetectShinyExpressVisitor(ast.NodeVisitor):
55+
def __init__(self):
56+
super().__init__()
57+
self.found_shiny_express_import = False
58+
59+
def visit_Import(self, node: ast.Import):
60+
if any(alias.name == "shiny.express" for alias in node.names):
61+
self.found_shiny_express_import = True
62+
63+
def visit_ImportFrom(self, node: ast.ImportFrom):
64+
if node.module == "shiny.express":
65+
self.found_shiny_express_import = True
66+
elif node.module == "shiny" and any(alias.name == "express" for alias in node.names):
67+
self.found_shiny_express_import = True
68+
69+
# Visit top-level nodes.
70+
def visit_Module(self, node: ast.Module):
71+
super().generic_visit(node)
72+
73+
# Don't recurse into any nodes, so the we'll only ever look at top-level nodes.
74+
def generic_visit(self, node: ast.AST):
75+
pass
76+
77+
78+
def escape_to_var_name(x: str) -> str:
79+
"""
80+
Given a string, escape it to a valid Python variable name which contains
81+
[a-zA-Z0-9_]. All other characters will be escaped to _<hex>_. Also, if the first
82+
character is a digit, it will be escaped to _<hex>_, because Python variable names
83+
can't begin with a digit.
84+
"""
85+
encoded = ""
86+
is_first = True
87+
88+
for char in x:
89+
if is_first and re.match("[0-9]", char):
90+
encoded += f"_{ord(char):x}_"
91+
elif re.match("[a-zA-Z0-9]", char):
92+
encoded += char
93+
else:
94+
encoded += f"_{ord(char):x}_"
95+
96+
if is_first:
97+
is_first = False
98+
99+
return encoded

0 commit comments

Comments
 (0)