Skip to content

Commit

Permalink
chore: added more docs/examples to with_user_session_token (#379)
Browse files Browse the repository at this point in the history
Added a couple more examples to make it clearer to people using the SDK
how this function works to generate a visitor client.
  • Loading branch information
mconflitti-pbc authored Jan 28, 2025
1 parent d66eb13 commit e605767
Showing 1 changed file with 53 additions and 2 deletions.
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.
```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

0 comments on commit e605767

Please sign in to comment.