sweatstack 0.54.0__py3-none-any.whl → 0.56.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
sweatstack/client.py CHANGED
@@ -51,8 +51,16 @@ AUTH_SUCCESSFUL_RESPONSE = """<!DOCTYPE html>
51
51
  OAUTH2_CLIENT_ID = "5382f68b0d254378"
52
52
 
53
53
 
54
- class LocalCacheMixin:
55
- """Mixin for handling local filesystem caching of API responses."""
54
+ class _LocalCacheMixin:
55
+ """Mixin for handling local filesystem caching of API responses.
56
+
57
+ Caching is controlled via environment variables:
58
+
59
+ - :envvar:`SWEATSTACK_LOCAL_CACHE` - Enable/disable caching
60
+ - :envvar:`SWEATSTACK_CACHE_DIR` - Custom cache directory location
61
+
62
+ Use :meth:`clear_cache` to remove all cached data for the current user.
63
+ """
56
64
 
57
65
  def _cache_enabled(self) -> bool:
58
66
  """Check if local caching is enabled."""
@@ -155,7 +163,7 @@ class LocalCacheMixin:
155
163
  self._log_cache_error("clear", e)
156
164
 
157
165
 
158
- class TokenStorageMixin:
166
+ class _TokenStorageMixin:
159
167
  """Mixin for handling persistent token storage using platformdirs."""
160
168
 
161
169
  def _get_token_file_path(self) -> Path:
@@ -200,7 +208,9 @@ except ImportError:
200
208
  __version__ = "unknown"
201
209
 
202
210
 
203
- class OAuth2Mixin:
211
+ class _OAuth2Mixin:
212
+ """OAuth2 authentication methods for the Client class."""
213
+
204
214
  def generate_pkce_params(self) -> tuple[str, str]:
205
215
  """Generate PKCE parameters for OAuth2 authorization.
206
216
 
@@ -436,7 +446,9 @@ class OAuth2Mixin:
436
446
  self.login(persist_api_key=persist_api_key)
437
447
 
438
448
 
439
- class DelegationMixin:
449
+ class _DelegationMixin:
450
+ """User delegation methods for accessing data on behalf of other users."""
451
+
440
452
  def _validate_user(self, user: str | UserSummary):
441
453
  if isinstance(user, UserSummary):
442
454
  return user.id
@@ -639,30 +651,61 @@ class DelegationMixin:
639
651
  )
640
652
 
641
653
 
642
- class Client(OAuth2Mixin, DelegationMixin, TokenStorageMixin, LocalCacheMixin):
654
+ class Client(_OAuth2Mixin, _DelegationMixin, _TokenStorageMixin, _LocalCacheMixin):
655
+ """SweatStack API client for accessing activities, traces, and user data.
656
+
657
+ The Client handles authentication, API requests, and data retrieval from SweatStack.
658
+ You can initialize it with credentials or use authenticate()/login() for OAuth2.
659
+
660
+ Example:
661
+ client = Client()
662
+ client.authenticate()
663
+ activities = client.get_activities(limit=10)
664
+ """
665
+
643
666
  def __init__(
644
667
  self,
645
668
  api_key: str | None = None,
646
669
  refresh_token: str | None = None,
647
670
  url: str | None = None,
648
671
  streamlit_compatible: bool = False,
672
+ client_id: str | None = None,
673
+ client_secret: str | None = None,
649
674
  ):
675
+ """Initialize a SweatStack client.
676
+
677
+ Args:
678
+ api_key: Optional API access token. If not provided, will check environment or storage.
679
+ refresh_token: Optional refresh token for automatic token renewal.
680
+ url: Optional SweatStack instance URL. Defaults to production.
681
+ streamlit_compatible: Set to True when using in Streamlit apps.
682
+ """
650
683
  self.api_key = api_key
651
684
  self.refresh_token = refresh_token
652
685
  self.url = url
653
686
  self.streamlit_compatible = streamlit_compatible
687
+ self.client_id = client_id or OAUTH2_CLIENT_ID
688
+ self.client_secret = client_secret
654
689
 
655
690
  def _do_token_refresh(self, tz: str) -> str:
656
- with self._http_client() as client:
691
+ refresh_token = self.refresh_token
692
+ if refresh_token is None:
693
+ raise ValueError(
694
+ "Cannot refresh token: no refresh_token available. "
695
+ "If using Streamlit, ensure you're using StreamlitAuth which handles token refresh automatically."
696
+ )
697
+
698
+ with self._http_client(skip_token_check=True) as client:
657
699
  response = client.post(
658
700
  "/api/v1/oauth/token",
659
- json={
701
+ data={
660
702
  "grant_type": "refresh_token",
661
- "refresh_token": self.refresh_token,
703
+ "refresh_token": refresh_token,
662
704
  "tz": tz,
705
+ "client_id": self.client_id,
706
+ "client_secret": self.client_secret,
663
707
  },
664
708
  )
665
-
666
709
  self._raise_for_status(response)
667
710
  return response.json()["access_token"]
668
711
 
@@ -670,12 +713,13 @@ class Client(OAuth2Mixin, DelegationMixin, TokenStorageMixin, LocalCacheMixin):
670
713
  try:
671
714
  body = decode_jwt_body(token)
672
715
  # Margin in seconds to account for time to token validation of the next request
673
- TOKEN_EXPIRY_MARGIN = 5
716
+ TOKEN_EXPIRY_MARGIN = 5 # 5 seconds. Meaning that if the token is within 5 seconds of expiring, it will be refreshed.
674
717
  if body["exp"] - TOKEN_EXPIRY_MARGIN < time.time():
675
718
  # Token is (almost) expired, refresh it
676
719
  token = self._do_token_refresh(body["tz"])
677
720
  self._api_key = token
678
- except Exception:
721
+ except Exception as exception:
722
+ logging.warning("Exception checking token expiry: %s", exception)
679
723
  # If token can't be decoded, just return as-is
680
724
  # @TODO: This probably should be handled differently
681
725
  pass
@@ -684,6 +728,11 @@ class Client(OAuth2Mixin, DelegationMixin, TokenStorageMixin, LocalCacheMixin):
684
728
 
685
729
  @property
686
730
  def api_key(self) -> str:
731
+ """The current API access token.
732
+
733
+ Automatically loads from instance, environment (SWEATSTACK_API_KEY),
734
+ or persistent storage. Refreshes expired tokens automatically.
735
+ """
687
736
  if self._api_key is not None:
688
737
  value = self._api_key
689
738
  elif value := os.getenv("SWEATSTACK_API_KEY"):
@@ -703,6 +752,10 @@ class Client(OAuth2Mixin, DelegationMixin, TokenStorageMixin, LocalCacheMixin):
703
752
 
704
753
  @property
705
754
  def refresh_token(self) -> str:
755
+ """The refresh token used for automatic token renewal.
756
+
757
+ Loads from instance, environment (SWEATSTACK_REFRESH_TOKEN), or persistent storage.
758
+ """
706
759
  if self._refresh_token is not None:
707
760
  return self._refresh_token
708
761
  elif value := os.getenv("SWEATSTACK_REFRESH_TOKEN"):
@@ -736,16 +789,27 @@ class Client(OAuth2Mixin, DelegationMixin, TokenStorageMixin, LocalCacheMixin):
736
789
  self._url = value
737
790
 
738
791
  @contextlib.contextmanager
739
- def _http_client(self):
792
+ def _http_client(self, skip_token_check: bool = False):
740
793
  """
741
794
  Creates an httpx client with the base URL and authentication headers pre-configured.
795
+
796
+ Args:
797
+ skip_token_check: If True, uses the raw _api_key without triggering token expiry check.
798
+ This prevents recursive token refresh attempts.
742
799
  """
743
800
  headers = {
744
801
  "User-Agent": f"python-sweatstack/{__version__}",
745
802
  }
746
- if self.api_key:
747
- headers["Authorization"] = f"Bearer {self.api_key}"
748
-
803
+ if skip_token_check:
804
+ # Use raw token without triggering expiry check (used during refresh)
805
+ token = self._api_key
806
+ else:
807
+ # Normal path: may trigger token refresh
808
+ token = self.api_key
809
+
810
+ if token:
811
+ headers["Authorization"] = f"Bearer {token}"
812
+
749
813
  with httpx.Client(base_url=self.url, headers=headers, timeout=60) as client:
750
814
  yield client
751
815
 
@@ -1042,6 +1106,41 @@ class Client(OAuth2Mixin, DelegationMixin, TokenStorageMixin, LocalCacheMixin):
1042
1106
  df = pd.read_parquet(BytesIO(response.content))
1043
1107
  return self._postprocess_dataframe(df)
1044
1108
 
1109
+ def get_activity_awd(
1110
+ self,
1111
+ activity_id: str,
1112
+ metric: Literal[Metric.power, Metric.speed] | Literal["power", "speed"] | None = None,
1113
+ ) -> pd.DataFrame:
1114
+ """Gets the accumulated work duration (AWD) for a specific activity.
1115
+
1116
+ This method retrieves accumulated work duration metrics for a specific activity.
1117
+ AWD represents the total duration spent at each intensity level by sorting
1118
+ activity data by intensity.
1119
+
1120
+ Args:
1121
+ activity_id: The unique identifier of the activity.
1122
+ metric: Optional metric type. Defaults to power for cycling, speed for other sports.
1123
+ Can be either "power" or "speed".
1124
+
1125
+ Returns:
1126
+ pd.DataFrame: A pandas DataFrame containing the AWD data.
1127
+
1128
+ Raises:
1129
+ HTTPStatusError: If the API request fails.
1130
+ """
1131
+ params = {}
1132
+ if metric is not None:
1133
+ params["metric"] = self._enums_to_strings([metric])[0]
1134
+
1135
+ with self._http_client() as client:
1136
+ response = client.get(
1137
+ url=f"/api/v1/activities/{activity_id}/accumulated-work-duration",
1138
+ params=params,
1139
+ )
1140
+ self._raise_for_status(response)
1141
+ df = pd.read_parquet(BytesIO(response.content))
1142
+ return self._postprocess_dataframe(df)
1143
+
1045
1144
  def get_latest_activity_data(
1046
1145
  self,
1047
1146
  sport: Sport | str | None = None,
@@ -1215,6 +1314,57 @@ class Client(OAuth2Mixin, DelegationMixin, TokenStorageMixin, LocalCacheMixin):
1215
1314
  df = pd.read_parquet(BytesIO(response.content))
1216
1315
  return self._postprocess_dataframe(df)
1217
1316
 
1317
+ def get_longitudinal_awd(
1318
+ self,
1319
+ *,
1320
+ sport: Sport | str,
1321
+ metric: Literal[Metric.power, Metric.speed] | Literal["power", "speed"],
1322
+ date: date | str | None = None,
1323
+ window_days: int | None = None,
1324
+ ) -> pd.DataFrame:
1325
+ """Gets the longitudinal accumulated work duration (AWD) for a specific sport and metric.
1326
+
1327
+ This method retrieves AWD values across four intensity levels: max (highest daily AWD),
1328
+ hard, medium, and easy (sustainable durations for respective workout intensities).
1329
+
1330
+ Note: This endpoint is in development and subject to change.
1331
+
1332
+ Args:
1333
+ sport: The sport to get AWD data for. Can be a Sport enum or string ID.
1334
+ metric: The metric to calculate AWD for. Must be either "power" or "speed".
1335
+ date: Optional reference date for the AWD calculation. If provided,
1336
+ the AWD will be calculated up to this date. Can be a date object
1337
+ or string in ISO format.
1338
+ window_days: Optional number of days to include in the calculation window
1339
+ before the reference date. If None, all available data is used.
1340
+
1341
+ Returns:
1342
+ pd.DataFrame: A pandas DataFrame containing the longitudinal AWD data with intensity levels.
1343
+
1344
+ Raises:
1345
+ HTTPStatusError: If the API request fails.
1346
+ """
1347
+ sport = self._enums_to_strings([sport])[0]
1348
+ metric = self._enums_to_strings([metric])[0]
1349
+
1350
+ params = {
1351
+ "sport": sport,
1352
+ "metric": metric,
1353
+ }
1354
+ if date is not None:
1355
+ params["date"] = date
1356
+ if window_days is not None:
1357
+ params["window_days"] = window_days
1358
+
1359
+ with self._http_client() as client:
1360
+ response = client.get(
1361
+ url="/api/v1/activities/longitudinal-accumulated-work-duration",
1362
+ params=params,
1363
+ )
1364
+ self._raise_for_status(response)
1365
+ df = pd.read_parquet(BytesIO(response.content))
1366
+ return self._postprocess_dataframe(df)
1367
+
1218
1368
  def _get_traces_generator(
1219
1369
  self,
1220
1370
  *,
@@ -1621,6 +1771,7 @@ _generate_singleton_methods(
1621
1771
  "get_activity",
1622
1772
  "get_activity_data",
1623
1773
  "get_activity_mean_max",
1774
+ "get_activity_awd",
1624
1775
 
1625
1776
  "get_latest_activity",
1626
1777
  "get_latest_activity_data",
@@ -1628,6 +1779,7 @@ _generate_singleton_methods(
1628
1779
 
1629
1780
  "get_longitudinal_data",
1630
1781
  "get_longitudinal_mean_max",
1782
+ "get_longitudinal_awd",
1631
1783
 
1632
1784
  "get_traces",
1633
1785
  "create_trace",
sweatstack/schemas.py CHANGED
@@ -1,3 +1,15 @@
1
+ """SweatStack data schemas and utilities.
2
+
3
+ This module re-exports Pydantic models from openapi_schemas and extends
4
+ the Sport and Metric enums with convenient utility methods.
5
+
6
+ Example:
7
+ sport = Sport.cycling_road
8
+ print(sport.display_name()) # "cycling (road)"
9
+ print(sport.root_sport()) # Sport.cycling
10
+ print(sport.is_root_sport()) # False
11
+ print(sport.is_sub_sport_of(Sport.cycling)) # True
12
+ """
1
13
  from enum import Enum
2
14
  from typing import List, Union
3
15
 
@@ -7,7 +19,7 @@ from .openapi_schemas import (
7
19
  )
8
20
 
9
21
 
10
- def parent_sport(sport: Sport) -> Sport:
22
+ def _parent_sport(sport: Sport) -> Sport:
11
23
  """Returns the parent sport of a given sport.
12
24
 
13
25
  For sports with a hierarchical structure (e.g., 'cycling.road'), returns the parent sport
@@ -25,7 +37,7 @@ def parent_sport(sport: Sport) -> Sport:
25
37
  return sport.__class__(".".join(parts[:-1]))
26
38
 
27
39
 
28
- def root_sport(sport: Sport) -> Sport:
40
+ def _root_sport(sport: Sport) -> Sport:
29
41
  """Returns the root sport of a given sport.
30
42
 
31
43
  For sports with a hierarchical structure (e.g., 'cycling.road' or 'cycling.road.gravel'),
@@ -40,7 +52,7 @@ def root_sport(sport: Sport) -> Sport:
40
52
  return sport.__class__(sport.value.split(".")[0])
41
53
 
42
54
 
43
- def is_root_sport(sport: Sport) -> bool:
55
+ def _is_root_sport(sport: Sport) -> bool:
44
56
  """Determines if a sport is a root sport.
45
57
 
46
58
  A root sport is one that doesn't have a parent sport in the hierarchy
@@ -52,10 +64,10 @@ def is_root_sport(sport: Sport) -> bool:
52
64
  Returns:
53
65
  bool: True if the sport is a root sport, False otherwise.
54
66
  """
55
- return sport == root_sport(sport)
67
+ return sport == _root_sport(sport)
56
68
 
57
69
 
58
- def is_sub_sport_of(sport: Sport, sport_or_sports: Union[Sport, List[Sport]]) -> bool:
70
+ def _is_sub_sport_of(sport: Sport, sport_or_sports: Union[Sport, List[Sport]]) -> bool:
59
71
  """Determines if a sport is a sub-sport of another sport or list of sports.
60
72
 
61
73
  For example, 'cycling.road' is a sub-sport of 'cycling', but not of 'running'.
@@ -73,12 +85,12 @@ def is_sub_sport_of(sport: Sport, sport_or_sports: Union[Sport, List[Sport]]) ->
73
85
  if isinstance(sport_or_sports, Sport):
74
86
  return sport.value.startswith(sport_or_sports.value)
75
87
  elif isinstance(sport_or_sports, (list, tuple)):
76
- return any(is_sub_sport_of(sport, sport) for sport in sport_or_sports)
88
+ return any(_is_sub_sport_of(sport, s) for s in sport_or_sports)
77
89
  else:
78
90
  raise ValueError(f"Invalid type for sport_or_sports: {type(sport_or_sports)}")
79
91
 
80
92
 
81
- def display_name(sport: Sport) -> str:
93
+ def _display_name(sport: Sport) -> str:
82
94
  """Returns a human-readable display name for a sport.
83
95
 
84
96
  This function converts a Sport enum value into a formatted string suitable for display.
@@ -98,13 +110,23 @@ def display_name(sport: Sport) -> str:
98
110
  return f"{base_sport} ({the_rest})"
99
111
 
100
112
 
101
- Sport.root_sport = root_sport
102
- Sport.parent_sport = parent_sport
103
- Sport.is_sub_sport_of = is_sub_sport_of
104
- Sport.display_name = display_name
113
+ Sport.root_sport = _root_sport
114
+ Sport.root_sport.__doc__ = _root_sport.__doc__
105
115
 
116
+ Sport.parent_sport = _parent_sport
117
+ Sport.parent_sport.__doc__ = _parent_sport.__doc__
106
118
 
107
- def metric_display_name(metric: Metric) -> str:
119
+ Sport.is_sub_sport_of = _is_sub_sport_of
120
+ Sport.is_sub_sport_of.__doc__ = _is_sub_sport_of.__doc__
121
+
122
+ Sport.is_root_sport = _is_root_sport
123
+ Sport.is_root_sport.__doc__ = _is_root_sport.__doc__
124
+
125
+ Sport.display_name = _display_name
126
+ Sport.display_name.__doc__ = _display_name.__doc__
127
+
128
+
129
+ def _metric_display_name(metric: Metric) -> str:
108
130
  """Returns a human-readable display name for a metric.
109
131
 
110
132
  This function converts a Metric enum value into a formatted string suitable for display.
@@ -112,4 +134,5 @@ def metric_display_name(metric: Metric) -> str:
112
134
  return metric.value.replace("_", " ")
113
135
 
114
136
 
115
- Metric.display_name = metric_display_name
137
+ Metric.display_name = _metric_display_name
138
+ Metric.display_name.__doc__ = _metric_display_name.__doc__
sweatstack/streamlit.py CHANGED
@@ -1,3 +1,29 @@
1
+ """Streamlit integration for SweatStack authentication and UI components.
2
+
3
+ This module provides authentication and UI helper components for building
4
+ Streamlit applications with SweatStack. The StreamlitAuth class handles
5
+ OAuth2 authentication flow and provides convenient selector components.
6
+
7
+ Example:
8
+ import streamlit as st
9
+ from sweatstack.streamlit import StreamlitAuth
10
+
11
+ auth = StreamlitAuth(
12
+ client_id="YOUR_APPLICATION_ID",
13
+ client_secret="YOUR_APPLICATION_SECRET",
14
+ redirect_uri="http://localhost:8501",
15
+ )
16
+
17
+ with st.sidebar:
18
+ auth.authenticate()
19
+
20
+ if not auth.is_authenticated():
21
+ st.stop()
22
+
23
+ st.write("Welcome!")
24
+ latest = auth.client.get_latest_activity()
25
+ st.write(f"Latest: {latest.sport}")
26
+ """
1
27
  import os
2
28
  import urllib.parse
3
29
  from datetime import date
@@ -18,6 +44,46 @@ from .schemas import Metric, Scope, Sport
18
44
 
19
45
 
20
46
  class StreamlitAuth:
47
+ """Handles SweatStack authentication and provides UI components for Streamlit apps.
48
+
49
+ This class manages OAuth2 authentication flow for Streamlit applications and provides
50
+ convenient selector components for activities, sports, tags, and metrics. Once authenticated,
51
+ the client property provides access to the SweatStack API.
52
+
53
+ Example:
54
+ import streamlit as st
55
+ from sweatstack.streamlit import StreamlitAuth
56
+
57
+ # Initialize authentication
58
+ auth = StreamlitAuth(
59
+ client_id="YOUR_APPLICATION_ID",
60
+ client_secret="YOUR_APPLICATION_SECRET",
61
+ redirect_uri="http://localhost:8501",
62
+ )
63
+
64
+ # Add authentication to sidebar
65
+ with st.sidebar:
66
+ auth.authenticate()
67
+
68
+ # Check authentication
69
+ if not auth.is_authenticated():
70
+ st.write("Please log in to continue")
71
+ st.stop()
72
+
73
+ # Use the authenticated client
74
+ st.write("Welcome to SweatStack")
75
+ latest_activity = auth.client.get_latest_activity()
76
+ st.write(f"Latest activity: {latest_activity.sport} on {latest_activity.start}")
77
+
78
+ # Switch between accessible users (admin feature)
79
+ with st.sidebar:
80
+ auth.select_user()
81
+
82
+ Attributes:
83
+ client: The SweatStack Client instance for API access.
84
+ api_key: The current API access token.
85
+ """
86
+
21
87
  def __init__(
22
88
  self,
23
89
  client_id=None,
@@ -25,12 +91,13 @@ class StreamlitAuth:
25
91
  scopes: List[Union[str, Scope]]=None,
26
92
  redirect_uri=None,
27
93
  ):
28
- """
94
+ """Initialize the StreamlitAuth component.
95
+
29
96
  Args:
30
- client_id: The client ID to use. If not provided, the SWEATSTACK_CLIENT_ID environment variable will be used.
31
- client_secret: The client secret to use. If not provided, the SWEATSTACK_CLIENT_SECRET environment variable will be used.
32
- scopes: The scopes to use. If not provided, the SWEATSTACK_SCOPES environment variable will be used. Defaults to data:read, profile.
33
- redirect_uri: The redirect URI to use. If not provided, the SWEATSTACK_REDIRECT_URI environment variable will be used.
97
+ client_id: OAuth2 client ID. Falls back to SWEATSTACK_CLIENT_ID env var.
98
+ client_secret: OAuth2 client secret. Falls back to SWEATSTACK_CLIENT_SECRET env var.
99
+ scopes: OAuth2 scopes. Falls back to SWEATSTACK_SCOPES env var. Defaults to data:read, profile.
100
+ redirect_uri: OAuth2 redirect URI. Falls back to SWEATSTACK_REDIRECT_URI env var.
34
101
  """
35
102
  self.client_id = client_id or os.environ.get("SWEATSTACK_CLIENT_ID")
36
103
  self.client_secret = client_secret or os.environ.get("SWEATSTACK_CLIENT_SECRET")
@@ -48,19 +115,39 @@ class StreamlitAuth:
48
115
  self.redirect_uri = redirect_uri or os.environ.get("SWEATSTACK_REDIRECT_URI")
49
116
 
50
117
  self.api_key = st.session_state.get("sweatstack_api_key")
51
- self.client = Client(self.api_key, streamlit_compatible=True)
118
+ self.refresh_token = st.session_state.get("sweatstack_refresh_token")
119
+ self.client = Client(
120
+ self.api_key,
121
+ refresh_token=self.refresh_token,
122
+ streamlit_compatible=True,
123
+ client_id=self.client_id,
124
+ client_secret=self.client_secret,
125
+ )
52
126
 
53
127
  def logout_button(self):
128
+ """Displays a logout button and handles user logout.
129
+
130
+ When clicked, this button clears the stored API key from session state,
131
+ resets the client, and triggers a Streamlit rerun to update the UI.
132
+ """
54
133
  if st.button("Logout"):
55
134
  self.api_key = None
135
+ self.refresh_token = None
56
136
  self.client = Client(streamlit_compatible=True)
57
- st.session_state.pop("sweatstack_api_key")
137
+ st.session_state.pop("sweatstack_api_key", None)
138
+ st.session_state.pop("sweatstack_refresh_token", None)
58
139
  st.rerun()
59
140
 
60
141
  def _running_on_streamlit_cloud(self):
142
+ """Detects if the app is running on Streamlit Cloud."""
61
143
  return os.environ.get("HOSTNAME") == "streamlit"
62
144
 
63
145
  def _show_sweatstack_login(self, login_label: str | None = None):
146
+ """Displays the SweatStack login button with appropriate styling.
147
+
148
+ Args:
149
+ login_label: Text to display on the login button.
150
+ """
64
151
  authorization_url = self.get_authorization_url()
65
152
  login_label = login_label or "Connect with SweatStack"
66
153
  if not self._running_on_streamlit_cloud():
@@ -96,6 +183,14 @@ class StreamlitAuth:
96
183
  st.link_button(login_label, authorization_url)
97
184
 
98
185
  def get_authorization_url(self):
186
+ """Generates the OAuth2 authorization URL for SweatStack.
187
+
188
+ This method constructs the URL users will be redirected to for OAuth2 authorization.
189
+ It includes the client ID, redirect URI, scopes, and other OAuth2 parameters.
190
+
191
+ Returns:
192
+ str: The complete authorization URL.
193
+ """
99
194
  params = {
100
195
  "client_id": self.client_id,
101
196
  "redirect_uri": self.redirect_uri,
@@ -107,12 +202,31 @@ class StreamlitAuth:
107
202
 
108
203
  return authorization_url
109
204
 
110
- def _set_api_key(self, api_key):
205
+ def _set_api_key(self, api_key, refresh_token=None):
206
+ """Sets the API key and refresh token in instance and session state, then refreshes the client.
207
+
208
+ Args:
209
+ api_key: The API access token to set.
210
+ refresh_token: The refresh token to set. If None, keeps the existing refresh token.
211
+ """
111
212
  self.api_key = api_key
112
213
  st.session_state["sweatstack_api_key"] = api_key
113
- self.client = Client(self.api_key, streamlit_compatible=True)
214
+
215
+ if refresh_token is not None:
216
+ self.refresh_token = refresh_token
217
+ st.session_state["sweatstack_refresh_token"] = refresh_token
218
+
219
+ self.client = Client(self.api_key, refresh_token=self.refresh_token, streamlit_compatible=True)
114
220
 
115
221
  def _exchange_token(self, code):
222
+ """Exchanges an authorization code for an access token.
223
+
224
+ Args:
225
+ code: The authorization code from the OAuth2 callback.
226
+
227
+ Raises:
228
+ Exception: If the token exchange fails.
229
+ """
116
230
  token_data = {
117
231
  "grant_type": "authorization_code",
118
232
  "client_id": self.client_id,
@@ -131,7 +245,10 @@ class StreamlitAuth:
131
245
  raise Exception(f"SweatStack Python login failed. Please try again.") from e
132
246
  token_response = response.json()
133
247
 
134
- self._set_api_key(token_response.get("access_token"))
248
+ self._set_api_key(
249
+ token_response.get("access_token"),
250
+ refresh_token=token_response.get("refresh_token")
251
+ )
135
252
 
136
253
  return
137
254
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sweatstack
3
- Version: 0.54.0
3
+ Version: 0.56.0
4
4
  Summary: The official Python client for SweatStack
5
5
  Author-email: Aart Goossens <aart@gssns.io>
6
6
  Requires-Python: >=3.9
@@ -1,17 +1,17 @@
1
1
  sweatstack/__init__.py,sha256=tiVfgKlswRPaDMEy0gA7u8rveqEYZTA_kyB9lJ3J6Sc,21
2
2
  sweatstack/cli.py,sha256=N1NWOgEZR2yaJvIXxo9qvp_jFlypZYb0nujpbVNYQ6A,720
3
- sweatstack/client.py,sha256=rqK9MAe-gzxO3v2xPAjQhsZSNBO23GvUZ4rUtzyucyQ,60050
3
+ sweatstack/client.py,sha256=dTx7Cqpd56NH32-Ndc6vo1WnzsN1C9BfpFrchV9NTdQ,66366
4
4
  sweatstack/constants.py,sha256=fGO6ksOv5HeISv9lHRoYm4besW1GTveXS8YD3K0ljg0,41
5
5
  sweatstack/ipython_init.py,sha256=OtBB9dQvyLXklD4kA2x1swaVtU9u73fG4V4-zz4YRAg,139
6
6
  sweatstack/jupyterlab_oauth2_startup.py,sha256=YcjXvzeZ459vL_dCkFi1IxX_RNAu80ZX9rwa0OXJfTM,1023
7
7
  sweatstack/openapi_schemas.py,sha256=VvquBdbssdB9D1KeJYQCx51hy1Df4SS0PjzGWXcUaew,46221
8
8
  sweatstack/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
9
- sweatstack/schemas.py,sha256=MLC41p1iGA1HxmZSLuGifHra3r_o0pHIQzZ4ejRrYug,3698
10
- sweatstack/streamlit.py,sha256=AaVFkNN0iO3oFBMTBWra4pkaQbSZQnrgHqsab50Zm48,13295
9
+ sweatstack/schemas.py,sha256=Xh9E8DjFx5NIEBnVqS6ixFVb0E06ANZbdOlnMofCpZw,4481
10
+ sweatstack/streamlit.py,sha256=fVTgTyb8a2c7IC-lCs32ocILvyj1dFXP4iQaTV9D4Is,17287
11
11
  sweatstack/sweatshell.py,sha256=MYLNcWbOdceqKJ3S0Pe8dwHXEeYsGJNjQoYUXpMTftA,333
12
12
  sweatstack/utils.py,sha256=AwHRdC1ziOZ5o9RBIB21Uxm-DoClVRAJSVvgsmSmvps,1801
13
13
  sweatstack/Sweat Stack examples/Getting started.ipynb,sha256=k2hiSffWecoQ0VxjdpDcgFzBXDQiYEebhnAYlu8cgX8,6335204
14
- sweatstack-0.54.0.dist-info/METADATA,sha256=PzZy2wDb6CqOrSn6XhxEGn7AZGrl9X7odS_QP6FZqx4,852
15
- sweatstack-0.54.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
16
- sweatstack-0.54.0.dist-info/entry_points.txt,sha256=kCzOUQI3dqbTpEYqtgYDeiKFaqaA7BMlV6D24BMzCFU,208
17
- sweatstack-0.54.0.dist-info/RECORD,,
14
+ sweatstack-0.56.0.dist-info/METADATA,sha256=N732fwIaJz4h5uVfOCZUwSaMbaLk7CB1leB6dHpvpw4,852
15
+ sweatstack-0.56.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
16
+ sweatstack-0.56.0.dist-info/entry_points.txt,sha256=kCzOUQI3dqbTpEYqtgYDeiKFaqaA7BMlV6D24BMzCFU,208
17
+ sweatstack-0.56.0.dist-info/RECORD,,