Skip to content
Merged
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
55 changes: 53 additions & 2 deletions src/posit/connect/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,11 @@ def with_user_session_token(self, token: str) -> Client:
a user session token will not exist, which will cause this method to result in an error needing
to be handled in your application.

Depending on the type of application you are building, the user session token is retrieved in
a variety of ways. For example, in Streamlit and Shiny applications, the token is stored in the
context or session object headers using the `Posit-Connect-User-Session-Token` key. For API
applications, the token is added to the request headers.

Parameters
----------
token : str
Expand All @@ -192,10 +197,56 @@ def with_user_session_token(self, token: str) -> Client:
Client
A new Client instance authenticated with an API key exchanged for the user session token.

Raises
------
ValueError
If the provided token is `None` or empty or if the exchange response is malformed.
ClientError
If the token exchange request with the Connect Server fails.

Examples
--------
>>> from posit.connect import Client
>>> client = Client().with_user_session_token("my-user-session-token")
```python
from posit.connect import Client
client = Client().with_user_session_token("my-user-session-token")
```

Example using user session token from Shiny session:
```python
from posit.connect import Client
from shiny.express import render, session

client = Client()

@reactive.calc
def visitor_client():
## read the user session token and generate a new client
user_session_token = session.http_conn.headers.get(
"Posit-Connect-User-Session-Token"
)
return client.with_user_session_token(user_session_token)
@render.text
def user_profile():
# fetch the viewer's profile information
return visitor_client().me
```

Example of when the visitor's token could not be retrieved (for
example, if this app allows unauthenticated access) and handle
that in cases where a token is expected.
Comment on lines +234 to +236
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💯 this is great, thank you

```python
from posit.connect import Client
import requests

# Simulate request without header
mock_request = requests.Request()
visitor_client = None
token = request.headers.get("Posit-Connect-User-Session-Token")
if token:
visitor_client = Client().with_user_session_token(token)
else:
print("This app requires a user session token to operate.")
```
"""
if token is None or token == "":
raise ValueError("token must be set to non-empty string.")
Expand Down