Package: rsconnect-python
The rsconnect-python CLIThis package provides a CLI (command-line interface) for interacting
with and deploying to Posit Connect. This is also used by thersconnect-jupyterpackage to deploy
Jupyter notebooks via the Jupyter web console. Many types of content supported by Posit
Connect may be deployed by this package, including WSGI-style APIs, Dash, Streamlit, and
Bokeh applications.Content types not directly supported by the CLI may also be deployed if they include a
preparedmanifest.jsonfile. See"Deploying R or Other
Content"for details.Deploying Python Content to Posit ConnectPosit Connect supports the deployment of Jupyter notebooks, Python APIs (such as
those based on Flask or FastAPI) and apps (such as Dash, Streamlit, and Bokeh apps).
Much like deploying R
content to Posit Connect, there are some caveats to understand when replicating your
environment on the Posit Connect server:Posit Connect insists on matching<MAJOR.MINOR>versions of Python. For example,
a server with only Python 3.8 installed will fail to match content deployed with
Python 3.7. Your administrator may also enable exact Python version matching which
will be stricter and require matching major, minor, and patch versions. For more
information see thePosit Connect Admin Guide chapter titled Python Version
Matching.InstallationTo installrsconnect-pythonfrom PYPI, you may use any python package manager such as
pip:pipinstallrsconnect-pythonYou may also build and install a wheel directly from a repository clone:gitclonehttps://github.com/rstudio/rsconnect-python.gitcdrsconnect-python
pipinstallpipenv
makedist
pipinstall./dist/rsconnect_python-*.whlUsing the rsconnect CLIHere's an example command that deploys a Jupyter notebook to Posit Connect.rsconnectdeploynotebook\--serverhttps://connect.example.org\--api-keymy-api-key\my-notebook.ipynbNoteThe examples here use long command line options, but there are short
options (-s,-k, etc.) available also. Runrsconnect deploy notebook --helpfor details.Setting uprsconnectCLI auto-completionIf you would like to use your shell's tab completion support with thersconnectcommand, use the command below for the shell you are using.bashIf you are using thebashshell, use this to enable tab completion.#~/.bashrceval"$(_RSCONNECT_COMPLETE=sourcersconnect)"zshIf you are using thezshshell, use this to enable tab completion.#~/.zshrceval"$(_RSCONNECT_COMPLETE=source_zshrsconnect)"If you getcommand not found: compdef, you need to add the following lines to your.zshrcbefore the completion setup:#~/.zshrcautoload-Uzcompinit
compinitManaging Server InformationThe information used by thersconnectcommand to communicate with a Posit Connect
server can be tedious to repeat on every command. To help, the CLI supports the idea
of saving this information, making it usable by a simple nickname.WarningOne item of information saved is the API key used to authenticate with
Posit Connect. Although the file where this information is saved is marked as
accessible by the owner only, it's important to remember that the key is present
in the file as plain text so care must be taken to prevent any unauthorized access
to the server information file.TLS Support and Posit ConnectUsually, a Posit Connect server will be set up to be accessed in a secure manner,
using thehttpsprotocol rather than simplehttp. If Posit Connect is set up
with a self-signed certificate, you will need to include the--insecureflag on
all commands. If Posit Connect is set up to require a client-side certificate chain,
you will need to include the--cacertoption that points to your certificate
authority (CA) trusted certificates file. Both of these options can be saved along
with the URL and API Key for a server.NoteWhen certificate information is saved for the server, the specified file
is read and itscontentsare saved under the server's nickname. If the CA file's
contents are ever changed, you will need to add the server information again.See theNetwork Optionssection for more details about these options.Remembering Server InformationUse theaddcommand to store information about a Posit Connect server:rsconnectadd\--api-keymy-api-key\--serverhttps://connect.example.org\--namemyserverNoteThersconnectCLI will verify that the serve URL and API key
are valid. If either is found not to be, no information will be saved.If any of the access information for the server changes, simply rerun theaddcommand with the new information and it will replace the original
information.Once the server's information is saved, you can refer to it by its nickname:rsconnectdeploynotebook--namemyservermy-notebook.ipynbIf there is information for only one server saved, this will work too:rsconnectdeploynotebookmy-notebook.ipynbListing Server InformationYou can see the list of saved server information with:rsconnect listRemoving Server InformationYou can remove information about a server with:rsconnect remove --name myserverRemoving may be done by its nickname (--name) or URL (--server).Verifying Server InformationYou can verify that a URL refers to a running instance of Posit Connect by using
thedetailscommand:rsconnectdetails--serverhttps://connect.example.orgIn this form,rsconnectwill only tell you whether the URL given does, in fact, refer
to a running Posit Connect instance. If you include a valid API key:rsconnectdetails--serverhttps://connect.example.org--api-keymy-api-keythe tool will provide the version of Posit Connect (if the server is configured to
divulge that information) and environmental information including versions of Python
that are installed on the server.You can also use nicknames with thedetailscommand if you want to verify that the
stored information is still valid.Notebook Deployment OptionsThere are a variety of options available to you when deploying a Jupyter notebook to
Posit Connect.Including Extra FilesYou can include extra files in the deployment bundle to make them available when your
notebook is run by the Posit Connect server. Just specify them on the command line
after the notebook file:rsconnectdeploynotebookmy-notebook.ipynbdata.csvPackage DependenciesIf arequirements.txtfile exists in the same directory as the notebook file, it will
be included in the bundle. It must specify the package dependencies needed to execute
the notebook. Posit Connect will reconstruct the Python environment using the
specified package list.If there is norequirements.txtfile or the--force-generateoption is specified,
the package dependencies will be determined from the current Python environment, or
from an alternative Python executable specified via the--pythonoption:rsconnectdeploynotebook--python/path/to/pythonmy-notebook.ipynbYou can see the packages list that will be included by runningpip list --format=freezeyourself,
ensuring that you use the same Python that you use to run your Jupyter Notebook:/path/to/python-mpiplist--format=freezeStatic (Snapshot) DeploymentBy default,rsconnectdeploys the original notebook with all its source code. This
enables the Posit Connect server to re-run the notebook upon request or on a schedule.If you just want to publish an HTML snapshot of the notebook, you can use the--staticoption. This will causersconnectto execute your notebook locally to produce the HTML
file, then publish the HTML file to the Posit Connect server:rsconnectdeploynotebook--staticmy-notebook.ipynbCreating a Manifest for Future DeploymentYou can create amanifest.jsonfile for a Jupyter Notebook, then use that manifest
in a later deployment. Use thewrite-manifestcommand to do this.Thewrite-manifestcommand will also create arequirements.txtfile, if it does
not already exist or the--force-generateoption is specified. It will contain the
package dependencies from the current Python environment, or from an alternative
Python executable specified in the--pythonoption.Here is an example of thewrite-manifestcommand:rsconnectwrite-manifestnotebookmy-notebook.ipynbNoteManifests for static (pre-rendered) notebooks cannot be created.API/Application Deployment OptionsYou can deploy a variety of APIs and applications using sub-commands of thersconnect deploycommand.api: WSGI-compliant APIs (e.g.,bottle,falcon,flask,flask-restx,flasgger,pycnic).flask: Flask APIs (Note:flaskis an alias ofapi.).fastapi: ASGI-compliant APIs (e.g,fastapi,quart,sanic,starlette)dash: Python Dash appsstreamlit: Streamlit appsbokeh: Bokeh server appsAll options below apply equally to theapi,fastapi,dash,streamlit,
andbokehsub-commands.Including Extra FilesYou can include extra files in the deployment bundle to make them available when your
API or application is run by the Posit Connect server. Just specify them on the
command line after the API or application directory:rsconnectdeployapiflask-api/data.csvSince deploying an API or application starts at a directory level, there will be times
when some files under that directory subtree should not be included in the deployment
or manifest. Use the--excludeoption to specify files or directories to exclude.rsconnectdeploydash--excludedash-app-venv--excludeTODO.txtdash-app/You can exclude a directory by naming it:rsconnectdeploydash--excludedash-app-venv--excludeoutput/dash-app/The--excludeoption may be repeated, and may include a glob pattern.
You should always quote a glob pattern so that it will be passed torsconnectas-is
instead of letting the shell expand it. If a file is specifically listed as an extra
file that also matches an exclusion pattern, the file will still be included in the
deployment (i.e., extra files take precedence).rsconnectdeploydash--excludedash-app-venv--exclude“*.txt”dash-app/The following shows an example of an extra file taking precedence:rsconnectdeploydash--exclude“*.csv”dash-app/important_data.csvSome directories are excluded by default, to prevent bundling and uploading files that are not needed or might interfere with the deployment process:.Rproj.user
.env
.git
.svn
.venv
__pycache__
env
packrat
renv
rsconnect-python
rsconnect
venvAny directory that appears to be a Python virtual environment (by containingbin/python) will also be excluded.Package DependenciesIf arequirements.txtfile exists in the API/application directory, it will be
included in the bundle. It must specify the package dependencies needed to execute
the API or application. Posit Connect will reconstruct the Python environment using
the specified package list.If there is norequirements.txtfile or the--force-generateoption is specified,
the package dependencies will be determined from the current Python environment, or
from an alternative Python executable specified via the--pythonoption:rsconnectdeployapi--python/path/to/pythonmy-api/You can see the packages list that will be included by runningpip list --format=freezeyourself,
ensuring that you use the same Python that you use to run your API or application:/path/to/python-mpiplist--format=freezeCreating a Manifest for Future DeploymentYou can create amanifest.jsonfile for an API or application, then use that
manifest in a later deployment. Use thewrite-manifestcommand to do this.Thewrite-manifestcommand will also create arequirements.txtfile, if it does
not already exist or the--force-generateoption is specified. It will contain
the package dependencies from the current Python environment, or from an alternative
Python executable specified in the--pythonoption.Here is an example of thewrite-manifestcommand:rsconnectwrite-manifestapimy-api/Deploying R or Other ContentYou can deploy other content that has an existing Posit Connectmanifest.jsonfile. For example, if you download and unpack a source bundle from Posit Connect,
you can deploy the resulting directory. The options are similar to notebook or
API/application deployment; seersconnect deploy manifest --helpfor details.Here is an example of thedeploy manifestcommand:rsconnectdeploymanifest/path/to/manifest.jsonNoteIn this case, the existing content is deployed as-is. Python environment
inspection and notebook pre-rendering, if needed, are assumed to be done already
and represented in the manifest.The argument todeploy manifestmay also be a directory so long as that directory
contains amanifest.jsonfile.If you have R content but don't have amanifest.jsonfile, you can use the RStudio
IDE to create the manifest. See the help for thersconnect::writeManifestR function:install.packages('rsconnect')library(rsconnect)?rsconnect::writeManifestOptions for All Types of DeploymentsThese options apply to any type of content deployment.TitleThe title of the deployed content is, by default, derived from the filename. For
example, if you deploymy-notebook.ipynb, the title will bemy-notebook. To change
this, use the--titleoption:rsconnect deploy notebook --title "My Notebook" my-notebook.ipynbWhen usingrsconnect deploy api,rsconnect deploy fastapi,rsconnect deploy dash,rsconnect deploy streamlit, orrsconnect deploy bokeh, the title is derived from the directory
containing the API or application.When usingrsconnect deploy manifest, the title is derived from the primary
filename referenced in the manifest.Verification After DeploymentAfter deploying your content, rsconnect accesses the deployed content
to verify that the deployment is live. This is done with aGETrequest
to the content, without parameters. The request is
considered successful if there isn't a 5xx code returned. Errors like
400 Bad Request or 405 Method Not Allowed because not all apps supportGET /.
For cases where this is not desired, use the--no-verifyflag on the command line.Environment variablesYou can set environment variables during deployment. Their names and values will be
passed to Posit Connect during deployment so you can use them in your code. Note that
if you are usingrsconnectto deploy to shinyapps.io, environment variable management
is not supported on that platform.For example, ifnotebook.ipynbcontainsprint(os.environ["MYVAR"])You can set the value ofMYVARthat will be set when your code runs in Posit Connect
using the-E/--environmentoption:rsconnectdeploynotebook--environmentMYVAR='hello world'notebook.ipynbTo avoid exposing sensitive values on the command line, you can specify
a variable without a value. In this case, it will use the value from the
environment in which rsconnect-python is running:exportSECRET_KEY=12345rsconnectdeploynotebook--environmentSECRET_KEYnotebook.ipynbIf you specify environment variables when updating an existing deployment,
new values will be set for the variables you provided. Other variables will
remain unchanged. If you don't specify any variables, all of the existing
variables will remain unchanged.Environment variables are set on the content item before the content bundle
is uploaded and deployed. If the deployment fails, the new environment variables
will still take effect.Network OptionsWhen specifying information thatrsconnectneeds to be able to interact with Posit
Connect, you can tailor how transport layer security is performed.TLS/SSL CertificatesPosit Connect servers can be configured to use TLS/SSL. If your server's certificate
is trusted by your Jupyter Notebook server, API client or user's browser, then you
don't need to do anything special. You can test this out with thedetailscommand:rsconnectdetails\--api-keymy-api-key\--serverhttps://connect.example.org:3939If this fails with a TLS Certificate Validation error, then you have two options.Provide the Root CA certificate that is at the root of the signing chain for your
Posit Connect server. This will enablersconnectto securely validate the
server's TLS certificate.rsconnectdetails\--api-keymy-api-key\--serverhttps://connect.example.org\--cacert/path/to/certificate.pemPosit Connect is in "insecure mode". This disables TLS certificate verification,
which results in a less secure connection.rsconnectadd\--api-keymy-api-key\--serverhttps://connect.example.org\--insecureOnce you work out the combination of options that allow you to successfully work with
an instance of Posit Connect, you'll probably want to use theaddcommand to haversconnectremember those options and allow you to just use a nickname.Updating a DeploymentIf you deploy a file again to the same server,rsconnectwill update the previous
deployment. This means that you can keep runningrsconnect deploy notebook my-notebook.ipynbas you develop new versions of your notebook. The same applies to other Python content
types.Forcing a New DeploymentTo bypass this behavior and force a new deployment, use the--newoption:rsconnectdeploydash--newmy-app/Updating a Different DeploymentIf you want to update an existing deployment but don't have the saved deployment data,
you can provide the app's numeric ID or GUID on the command line:rsconnectdeploynotebook--app-id123456my-notebook.ipynbYou must be the owner of the target deployment, or a collaborator with permission to
change the content. The type of content (static notebook, notebook with source code,
API, or application) must match the existing deployment.NoteThere is no confirmation required to update a deployment. If you do so
accidentally, use the "Source Versions" dialog in the Posit Connect dashboard to
activate the previous version and remove the erroneous one.Finding the App IDThe App ID associated with a piece of content you have previously deployed from thersconnectcommand line interface can be found easily by querying the deployment
information using theinfocommand. For more information, see theShowing the Deployment Informationsection.If the content was deployed elsewhere orinfodoes not return the correct App ID,
but you can open the content on Posit Connect, find the content and open it in a
browser. The URL in your browser's location bar will contain#/apps/NNNwhereNNNis your App ID. The GUID identifier for the app may be found on theInfotab for
the content in the Posit Connect UI.Showing the Deployment InformationYou can see the information that thersconnectcommand has saved for the most recent
deployment with theinfocommand:rsconnectinfomy-notebook.ipynbIf you have deployed to multiple servers, the most recent deployment information for
each server will be shown. This command also displays the path to the file where the
deployment data is stored.Stored Information FilesStored information files are stored in a platform-specific directory:PlatformLocationMac$HOME/Library/Application Support/rsconnect-python/Linux$HOME/.rsconnect-python/or$XDG_CONFIG_HOME/rsconnect-python/Windows$APPDATA/rsconnect-pythonRemembered server information is stored in theservers.jsonfile in that directory.Deployment DataAfter a deployment is completed, information about the deployment is saved
to enable later redeployment. This data is stored alongside the deployed file,
in anrsconnect-pythonsubdirectory, if possible. If that location is not writable
during deployment, then the deployment data will be stored in the global configuration
directory specified above.Generated fromrsconnect-python {{ rsconnect_python.version }}Hide Jupyter Notebook Input Code CellsThe user can render a Jupyter notebook without its corresponding input code cells by passing the '--hide-all-input' flag through the cli:rsconnectdeploynotebook\--serverhttps://connect.example.org\--api-keymy-api-key\--hide-all-input\my-notebook.ipynbTo selectively hide input cells in a Jupyter notebook, the user needs to follow a two step process:tag cells with the 'hide_input' tag,then pass the ' --hide-tagged-input' flag through the cli:rsconnectdeploynotebook\--serverhttps://connect.example.org\--api-keymy-api-key\--hide-tagged-input\my-notebook.ipynbBy default, rsconnect-python does not install Jupyter notebook related depenencies. These dependencies are installed via rsconnect-jupyter. When the user is using the hide input features in rsconnect-python by itself without rsconnect-jupyter, he/she needs to install the following package depenecies:notebook
nbformat
nbconvert>=5.6.1Content subcommandsrsconnect-python supports multiple options for interacting with Posit Connect's/v1/contentAPI. Both administrators and publishers can use the content subcommands
to search, download, and rebuild content on Posit Connect without needing to access the
dashboard from a browser.NoteThersconnect contentCLI subcommands are intended to be easily scriptable.
The default output format isJSONso that the results can be easily piped into
other command line utilities likejqfor further post-processing.rsconnectcontent--help# Usage: rsconnect content [OPTIONS] COMMAND [ARGS]...#   Interact with Posit Connect's content API.# Options:#   --help  Show this message and exit.# Commands:#   build            Build content on Posit Connect.#   describe         Describe a content item on Posit Connect.#   download-bundle  Download a content item's source bundle.#   search           Search for content on Posit Connect.Content SearchThersconnect content searchsubcommands can be used by administrators and publishers
to find specific content on a given Posit Connect server. The search returns
metadata for each content item that meets the search criteria.rsconnectcontentsearch--help# Usage: rsconnect content search [OPTIONS]# Options:#   -n, --name TEXT                 The nickname of the Posit Connect server.#   -s, --server TEXT               The URL for the Posit Connect server.#   -k, --api-key TEXT              The API key to use to authenticate with#                                   Posit Connect.#   -i, --insecure                  Disable TLS certification/host validation.#   -c, --cacert FILENAME           The path to trusted TLS CA certificates.#   --published                     Search only published content.#   --unpublished                   Search only unpublished content.#   --content-type [unknown|shiny|rmd-static|rmd-shiny|static|api|tensorflow-saved-model|jupyter-static|python-api|python-dash|python-streamlit|python-bokeh|python-fastapi|quarto-shiny|quarto-static]#                                   Filter content results by content type.#   --r-version VERSIONSEARCHFILTER#                                   Filter content results by R version.#   --py-version VERSIONSEARCHFILTER#                                   Filter content results by Python version.#   --title-contains TEXT           Filter content results by title.#   --order-by [created|last_deployed]#                                   Order content results.#   -v, --verbose                   Print detailed messages.#   --help                          Show this message and exit.rsconnectcontentsearch# [#   {#     "max_conns_per_process": null,#     "content_category": "",#     "load_factor": null,#     "cluster_name": "Local",#     "description": "",#     "bundle_id": "142",#     "image_name": null,#     "r_version": null,#     "content_url": "https://connect.example.org:3939/content/4ffc819c-065c-420c-88eb-332db1133317/",#     "connection_timeout": null,#     "min_processes": null,#     "last_deployed_time": "2021-12-02T18:09:11Z",#     "name": "logs-api-python",#     "title": "logs-api-python",#     "created_time": "2021-07-19T19:17:32Z",#     "read_timeout": null,#     "guid": "4ffc819c-065c-420c-88eb-332db1133317",#     "parameterized": false,#     "run_as": null,#     "py_version": "3.8.2",#     "idle_timeout": null,#     "app_role": "owner",#     "access_type": "acl",#     "app_mode": "python-api",#     "init_timeout": null,#     "id": "18",#     "quarto_version": null,#     "dashboard_url": "https://connect.example.org:3939/connect/#/apps/4ffc819c-065c-420c-88eb-332db1133317",#     "run_as_current_user": false,#     "owner_guid": "edf26318-0027-4d9d-bbbb-54703ebb1855",#     "max_processes": null#   },#   ...# ]Seethis sectionfor more comprehensive usage examples
of the available search flags.Content BuildNoteThersconnect content buildsubcommand requires Posit Connect >= 2021.11.1Posit Connect caches R and Python packages in the configuredServer.DataDir.
Under certain circumstances (examples below), these package caches can become stale
and need to be rebuilt. This refresh automatically occurs when a Posit Connect
user visits the content. You may wish to refresh some content before it is visited
because it is high priority or is not visited frequently (API content, emailed reports).
In these cases, it is possible to preemptively build specific content items using
thersconnect content buildsubcommands. This way the user does not have to pay
the build cost when the content is accessed next.The following are some common scenarios where performing a content build might be necessary:OS upgradechanges to gcc or libc librarieschanges to Python or R installationsswitching from source to binary package repositories or vice versaNoteThecontent buildcommand is non-destructive, meaning that it does nothing to purge
existing packrat/python package caches before a build. If you have an
existing cache, it should be cleared prior to starting a content build.
See themigration documentationfor details.NoteYou may use thersconnect content searchsubcommand to help
identify high priority content items to build.rsconnectcontentbuild--help
Usage:rsconnectcontentbuild[OPTIONS]COMMAND[ARGS]...BuildcontentonPositConnect.RequiresConnect>=2021.11.1

Options:--helpShowthismessageandexit.

Commands:addMarkacontentitemforbuild.Use`buildrun`toinvokethebuildontheConnectserver.historyGetthebuildhistoryforacontentitem.logsPrintthelogsforacontentbuild.lsListthecontentitemsthatarebeingtrackedforbuildonagivenConnectserver.rmRemoveacontentitemfromthelistofcontentthataretrackedforbuild.Use`buildls`toviewthetrackedcontent.runStartbuildingcontentonagivenConnectserver.To build a specific content item, firstaddit to the list of content that is
"tracked" for building using its GUID.NoteMetadata for "tracked" content items is stored in a local directory calledrsconnect-buildwhich will be automatically created in your current working directory.
You may set the environment variableCONNECT_CONTENT_BUILD_DIRto override this directory location.rsconnectcontentbuildadd--guid4ffc819c-065c-420c-88eb-332db1133317NoteSeethis sectionfor
an example of how to add multiple content items in bulk, from the results
of arsconnect content searchcommand.To view all currently "tracked" content items, use thersconnect content build lssubcommand.rsconnectcontentbuildlsTo view only the "tracked" content items that have not yet been built, use the--status NEEDS_BUILDflag.rsconnectcontentbuildls--statusNEEDS_BUILDOnce the content items have been added, you may initiate a build
using thersconnect content build runsubcommand. This command will attempt to
build all "tracked" content that has the statusNEEDS_BUILD.To re-run failed builds, usersconnect content build run --retry. This will build
all tracked content in any of the following states:[NEEDS_BUILD, ABORTED, ERROR, RUNNING].rsconnectcontentbuildrun# [INFO] 2021-12-14T13:02:45-0500 Initializing ContentBuildStore for https://connect.example.org:3939# [INFO] 2021-12-14T13:02:45-0500 Starting content build (https://connect.example.org:3939)...# [INFO] 2021-12-14T13:02:45-0500 Starting build: 4ffc819c-065c-420c-88eb-332db1133317# [INFO] 2021-12-14T13:02:50-0500 Running = 1, Pending = 0, Success = 0, Error = 0# [INFO] 2021-12-14T13:02:50-0500 Build succeeded: 4ffc819c-065c-420c-88eb-332db1133317# [INFO] 2021-12-14T13:02:55-0500 Running = 0, Pending = 0, Success = 1, Error = 0# [INFO] 2021-12-14T13:02:55-0500 1/1 content builds completed in 0:00:10# [INFO] 2021-12-14T13:02:55-0500 Success = 1, Error = 0# [INFO] 2021-12-14T13:02:55-0500 Content build complete.Sometimes content builds will fail and require debugging by the publisher or administrator.
Use thersconnect content build lsto identify content builds that resulted in errors
and inspect the build logs with thersconnect content build logssubcommand.rsconnectcontentbuildls--statusERROR# [INFO] 2021-12-14T13:07:32-0500 Initializing ContentBuildStore for https://connect.example.org:3939# [#   {#     "rsconnect_build_status": "ERROR",#     "last_deployed_time": "2021-12-02T18:09:11Z",#     "owner_guid": "edf26318-0027-4d9d-bbbb-54703ebb1855",#     "rsconnect_last_build_log": "/Users/david/code/posit/rsconnect-python/rsconnect-build/logs/connect_example_org_3939/4ffc819c-065c-420c-88eb-332db1133317/pZoqfBoi6BgpKde5.log",#     "guid": "4ffc819c-065c-420c-88eb-332db1133317",#     "rsconnect_build_task_result": {#       "user_id": 1,#       "error": "Cannot find compatible environment: no compatible Local environment with Python version 3.9.5",#       "code": 1,#       "finished": true,#       "result": {#         "data": "An error occurred while building the content",#         "type": "build-failed-error"#       },#       "id": "pZoqfBoi6BgpKde5"#     },#     "dashboard_url": "https://connect.example.org:3939/connect/#/apps/4ffc819c-065c-420c-88eb-332db1133317",#     "name": "logs-api-python",#     "title": "logs-api-python",#     "content_url": "https://connect.example.org:3939/content/4ffc819c-065c-420c-88eb-332db1133317/",#     "bundle_id": "141",#     "rsconnect_last_build_time": "2021-12-14T18:07:16Z",#     "created_time": "2021-07-19T19:17:32Z",#     "app_mode": "python-api"#   }# ]rsconnectcontentbuildlogs--guid4ffc819c-065c-420c-88eb-332db1133317# [INFO] 2021-12-14T13:09:27-0500 Initializing ContentBuildStore for https://connect.example.org:3939# Building Python API...# Cannot find compatible environment: no compatible Local environment with Python version 3.9.5# Task failed. Task exited with status 1.Common Usage ExamplesSearching for contentThe following are some examples of how publishers might use thersconnect content searchsubcommand to find content on Posit Connect.
By default, thersconnect content searchcommand will return metadata for ALL
of the content on a Posit Connect server, both published and unpublished content.NoteWhen using the--r-versionand--py-versionflags, users should
make sure to quote the arguments to avoid conflicting with your shell. For
example, bash would interpret--py-version >3.0.0as a shell redirect because of the
unquoted>character.# return only published contentrsconnectcontentsearch--published# return only unpublished contentrsconnectcontentsearch--unpublished# return published content where the python version is at least 3.9.0rsconnectcontentsearch--published--py-version">=3.9.0"# return published content where the R version is exactly 3.6.3rsconnectcontentsearch--published--r-version"==3.6.3"# return published content where the content type is a static RMDrsconnectcontentsearch--content-typermd-static# return published content where the content type is either shiny OR fast-apirsconnectcontentsearch--content-typeshiny--content-typepython-fastapi# return all content, published or unpublished, where the title contains the# text "Stock Report"rsconnectcontentsearch--title-contains"Stock Report"# return published content, results are ordered by when the content was last# deployedrsconnectcontentsearch--published--order-bylast_deployed# return published content, results are ordered by when the content was# createdrsconnectcontentsearch--published--order-bycreatedFinding r and python versionsOne common use for thesearchcommand might be to find the versions of
r and python that are currently in use on your Posit Connect server before a migration.# search for all published content and print the unique r and python version# combinationsrsconnectcontentsearch--published|jq-c'.[] | {py_version,r_version}'|sort|uniq# {"py_version":"3.8.2","r_version":"3.5.3"}# {"py_version":"3.8.2","r_version":"3.6.3"}# {"py_version":"3.8.2","r_version":null}# {"py_version":null,"r_version":"3.5.3"}# {"py_version":null,"r_version":"3.6.3"}# {"py_version":null,"r_version":null}Finding recently deployed content# return only the 10 most recently deployed content itemsrsconnectcontentsearch\--order-bylast_deployed\--published|jq-c'limit(10; .[]) | { guid, last_deployed_time }'# {"guid":"4ffc819c-065c-420c-88eb-332db1133317","last_deployed_time":"2021-12-02T18:09:11Z"}# {"guid":"aa2603f8-1988-484f-a335-193f2c57e6c4","last_deployed_time":"2021-12-01T20:56:07Z"}# {"guid":"051252f0-4f70-438f-9be1-d818a3b5f8d9","last_deployed_time":"2021-12-01T20:37:01Z"}# {"guid":"015143da-b75f-407c-81b1-99c4a724341e","last_deployed_time":"2021-11-30T16:56:21Z"}# {"guid":"bcc74209-3a81-4b9c-acd5-d24a597c256c","last_deployed_time":"2021-11-30T15:51:07Z"}# {"guid":"f21d7767-c99e-4dd4-9b00-ff8ec9ae2f53","last_deployed_time":"2021-11-23T18:46:28Z"}# {"guid":"da4f709c-c383-4fbc-89e2-f032b2d7e91d","last_deployed_time":"2021-11-23T18:46:28Z"}# {"guid":"9180809d-38fd-4730-a0e0-8568c45d87b7","last_deployed_time":"2021-11-23T15:16:19Z"}# {"guid":"2b1d2ab8-927d-4956-bbf9-29798d039bc5","last_deployed_time":"2021-11-22T18:33:17Z"}# {"guid":"c96db3f3-87a1-4df5-9f58-eb109c397718","last_deployed_time":"2021-11-19T20:25:33Z"}Add to build from search resultsOne common use case might be torsconnect content build addcontent for build
based on the results of arsconnect content search. For example:# search for all API type content, then# for each guid, add it to the "tracked" content itemsforguidin$(rsconnectcontentsearch\--published\--content-typepython-api\--content-typeapi|jq-r'.[].guid');dorsconnectcontentbuildadd--guid$guiddoneAdding content items one at a time can be a slow operation. This is becausersconnect content build addmust fetch metadata for each content item before it
is added to the "tracked" content items. By providing multiple--guidarguments
to thersconnect content build addsubcommand, we can fetch metadata for multiple content items
in a single api call, which speeds up the operation significantly.# write the guid of every published content item to a file called guids.txtrsconnectcontentsearch--published|jq'.[].guid'>guids.txt# bulk-add from the guids.txt with a single `rsconnect content build add` commandxargsprintf--'-g %s\n'<guids.txt|xargsrsconnectcontentbuildaddProgrammatic ProvisioningPosit Connect supports the programmatic bootstrapping of an administrator API key
for scripted provisioning tasks. This process is supported by thersconnect bootstrapcommand,
which uses a JSON Web Token to request an initial API key from a fresh Connect instance.WarningThis featurerequires Python version 3.6 or higher.rsconnectbootstrap\--serverhttps://connect.example.org:3939\--jwt-keypath/path/to/secret.keyA full description on how to usersconnect bootstrapin a provisioning workflow is provided in the Connect administrator guide'sprogrammatic provisioningdocumentation.Server Administration TasksStarting with the 2023.05 edition of Posit Connect,rsconnect-pythoncan be
used to perform certain server administration tasks, such as instance managing
runtime caches. For more information on runtime caches in Posit Connect, see the
Connect Admin Guide's section onruntime
caches.Examples in this section will use--name myserverto stand in for your Connect
server information. SeeManaging Server
Informationabove for more details.Enumerate Runtime CachesNew in Connect 2023.05Use the command below to enumerate runtime caches on a Connect server. The
command will output a JSON object containing a list of runtime caches . Each
cache entry will contain the following information:language: The language of content that uses the cache, either R or Python.version: The language version of the content that uses the cache.image_name: The execution environment of the cache. The stringLocaldenotes native execution. For Connect instances that use off-host execution,
the name of the image that uses the cache will be displayed.rsconnectsystemcacheslist--namemyserver# {#   "caches": [#     {#       "language": "R",#       "version": "3.6.3",#       "image_name": "Local"#     },#     {#       "language": "Python",#       "version": "3.9.5",#       "image_name": "Local"#     },#         {#       "language": "R",#       "version": "3.6.3",#       "image_name": "rstudio/content-base:r3.6.3-py3.9.5-bionic"#     },#     {#       "language": "Python",#       "version": "3.9.5",#       "image_name": "rstudio/content-base:r3.6.3-py3.9.5-bionic"#     }#   ]# }NoteTheimage_namefield returned by the server will use sanitized versions
of names.Delete Runtime CachesNew in Connect 2023.05When Connect's execution environment changes, runtime caches may be invalidated.
In these cases, you will need to delete the affected runtime caches using thesystem caches deletecommand.WarningAfter deleting a cache, the first time affected content is visited, Connect
will need to reconstruct its environment. This can take a long time. To
mitigate this, you can use thecontent buildcommand to
rebuild affected content ahead of time. You may want to do this just for
high-priority content, or for all content.To delete a runtime cache, call thesystem caches deletecommand, specifying a
Connect server, as well as the language (-l, --language), version (-V, --version), and image name (-I, --image-name) for the cache you wish to
delete. Deleting a large cache might take a while. The command will wait for
Connect to finish the task.Use the following parameters specify the target cache:language(required) must nameRorPython. It is case-insensitive.version(required) must be a three-part version number, e.g.3.8.12.image-name(optional) defaults toLocal, which targets caches used for
natively-executed content. Off-host images can be specified using either the
literal image name or the sanitized name returned by thelistcommand.Use the dry run flag (-d, --dry-run) to surface any errors ahead of
deletion.rsconnectsystemcachesdelete\--namemyserver\--languagePython\--version3.9.5\--image-namerstudio/content-base:r3.6.3-py3.9.5-bionic\--dry-run# Dry run finishedrsconnectsystemcachesdelete\--namemyserver\--languagePython\--version3.9.5\--image-namerstudio/content-base:r3.6.3-py3.9.5-bionic# Deleting runtime cache...# Successfully deleted runtime cacheYou should run these commands for each cache you wish to delete.