Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for shiny express apps #521

Merged
merged 6 commits into from
Nov 29, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
- Added the name of the environment variables to the help output for those options that
use environment variables as a default value.
- Added support for deploying Shiny Express applications.

### Changed
- Improved the error and warning outputs when options conflict by providing the source
- Improved the error and warning outputs when options conflict by providing the source
from which the values have been determined. This allows for faster resolution of issues
when combinations of stored credentials, environment variables and command line options
are used.
Expand Down
41 changes: 32 additions & 9 deletions rsconnect/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@
produce_bootstrap_output,
parse_client_response,
)
from .shiny_express import escape_to_var_name, is_express_app

server_store = ServerStore()
future_enabled = False
Expand Down Expand Up @@ -123,7 +124,7 @@ def output_params(
if k in {"api_key", "api-key"}:
val = "**********"
sourceName = validation.get_parameter_source_name_from_ctx(k, ctx)
logger.log(VERBOSE, " %-18s%s (from %s)", (k+":"), val, sourceName)
logger.log(VERBOSE, " %-18s%s (from %s)", (k + ":"), val, sourceName)


def server_args(func):
Expand Down Expand Up @@ -1013,7 +1014,7 @@ def deploy_voila(
server: str = None,
api_key: str = None,
insecure: bool = False,
cacert: typing.IO = None,
cacert: str = None,
connect_server: api.RSConnectServer = None,
multi_notebook: bool = False,
no_verify: bool = False,
Expand Down Expand Up @@ -1288,7 +1289,7 @@ def deploy_html(
server: str = None,
api_key: str = None,
insecure: bool = False,
cacert: typing.IO = None,
cacert: str = None,
account: str = None,
token: str = None,
secret: str = None,
Expand Down Expand Up @@ -1324,7 +1325,6 @@ def deploy_html(


def generate_deploy_python(app_mode: AppMode, alias: str, min_version: str, desc: Optional[str] = None):

if desc is None:
desc = app_mode.desc()

Expand Down Expand Up @@ -1415,17 +1415,40 @@ def deploy_app(
no_verify: bool = False,
):
set_verbosity(verbose)
output_params(ctx, locals().items())
kwargs = locals()
kwargs["entrypoint"] = entrypoint = validate_entry_point(entrypoint, directory)
kwargs["extra_files"] = extra_files = validate_extra_files(directory, extra_files)
entrypoint = validate_entry_point(entrypoint, directory)
extra_files = validate_extra_files(directory, extra_files)
environment = create_python_environment(
directory,
force_generate,
python,
)

ce = RSConnectExecutor(**kwargs)
if is_express_app(entrypoint + ".py", directory):
entrypoint = "shiny.express.app:" + escape_to_var_name(entrypoint + ".py")

extra_args = dict(
directory=directory,
server=server,
exclude=exclude,
new=new,
app_id=app_id,
title=title,
visibility=visibility,
disable_env_management=disable_env_management,
env_vars=env_vars,
)

ce = RSConnectExecutor(
name=name,
api_key=api_key,
insecure=insecure,
cacert=cacert,
account=account,
token=token,
secret=secret,
**extra_args,
)

(
ce.validate_server()
.validate_app_mode(app_mode=app_mode)
Expand Down
99 changes: 99 additions & 0 deletions rsconnect/shiny_express.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
# The contents of this file are copied from:
# https://github.com/posit-dev/py-shiny/blob/feb4cb7f872922717c39753514ae2d7fa32f10a1/shiny/express/_is_express.py

from __future__ import annotations

import ast
from pathlib import Path
import re

__all__ = ("is_express_app",)


def is_express_app(app: str, app_dir: str | None) -> bool:
"""Detect whether an app file is a Shiny express app

Parameters
----------
app
App filename, like "app.py". It may be a relative path or absolute path.
app_dir
Directory containing the app file. If this is `None`, then `app` must be an
absolute path.

Returns
-------
:
`True` if it is a Shiny express app, `False` otherwise.
"""
if not app.lower().endswith(".py"):
return False

if app_dir is not None:
app_path = Path(app_dir) / app
else:
app_path = Path(app)

if not app_path.exists():
return False

try:
# Read the file, parse it, and look for any imports of shiny.express.
with open(app_path) as f:
content = f.read()
tree = ast.parse(content, app_path)
detector = DetectShinyExpressVisitor()
detector.visit(tree)

except Exception:
return False

return detector.found_shiny_express_import


class DetectShinyExpressVisitor(ast.NodeVisitor):
def __init__(self):
super().__init__()
self.found_shiny_express_import = False

def visit_Import(self, node: ast.Import):
if any(alias.name == "shiny.express" for alias in node.names):
self.found_shiny_express_import = True

def visit_ImportFrom(self, node: ast.ImportFrom):
if node.module == "shiny.express":
self.found_shiny_express_import = True
elif node.module == "shiny" and any(alias.name == "express" for alias in node.names):
self.found_shiny_express_import = True

# Visit top-level nodes.
def visit_Module(self, node: ast.Module):
super().generic_visit(node)

# Don't recurse into any nodes, so the we'll only ever look at top-level nodes.
def generic_visit(self, node: ast.AST):
pass


def escape_to_var_name(x: str) -> str:
"""
Given a string, escape it to a valid Python variable name which contains
[a-zA-Z0-9_]. All other characters will be escaped to _<hex>_. Also, if the first
character is a digit, it will be escaped to _<hex>_, because Python variable names
can't begin with a digit.
"""
encoded = ""
is_first = True

for char in x:
if is_first and re.match("[0-9]", char):
encoded += f"_{ord(char):x}_"
elif re.match("[a-zA-Z0-9]", char):
encoded += char
else:
encoded += f"_{ord(char):x}_"

if is_first:
is_first = False

return encoded
Loading