index
int64
0
731k
package
stringlengths
2
98
name
stringlengths
1
76
docstring
stringlengths
0
281k
code
stringlengths
4
1.07M
signature
stringlengths
2
42.8k
24,182
supabase._async.client
_get_auth_headers
Helper method to get auth headers.
def _get_auth_headers(self) -> Dict[str, str]: """Helper method to get auth headers.""" return { "apiKey": self.supabase_key, "Authorization": self.options.headers.get( "Authorization", self._create_auth_header(self.supabase_key) ), }
(self) -> Dict[str, str]
24,183
supabase._async.client
_init_postgrest_client
Private helper for creating an instance of the Postgrest client.
@staticmethod def _init_postgrest_client( rest_url: str, headers: Dict[str, str], schema: str, timeout: Union[int, float, Timeout] = DEFAULT_POSTGREST_CLIENT_TIMEOUT, ) -> AsyncPostgrestClient: """Private helper for creating an instance of the Postgrest client.""" return AsyncPostgrestClient( rest_url, headers=headers, schema=schema, timeout=timeout )
(rest_url: str, headers: Dict[str, str], schema: str, timeout: Union[int, float, httpx.Timeout] = 120) -> postgrest._async.client.AsyncPostgrestClient
24,184
supabase._async.client
_init_storage_client
null
@staticmethod def _init_storage_client( storage_url: str, headers: Dict[str, str], storage_client_timeout: int = DEFAULT_STORAGE_CLIENT_TIMEOUT, ) -> AsyncStorageClient: return AsyncStorageClient(storage_url, headers, storage_client_timeout)
(storage_url: str, headers: Dict[str, str], storage_client_timeout: int = 20) -> storage3._async.client.AsyncStorageClient
24,185
supabase._async.client
_init_supabase_auth_client
Creates a wrapped instance of the GoTrue Client.
@staticmethod def _init_supabase_auth_client( auth_url: str, client_options: ClientOptions, ) -> AsyncSupabaseAuthClient: """Creates a wrapped instance of the GoTrue Client.""" return AsyncSupabaseAuthClient( url=auth_url, auto_refresh_token=client_options.auto_refresh_token, persist_session=client_options.persist_session, storage=client_options.storage, headers=client_options.headers, flow_type=client_options.flow_type, )
(auth_url: str, client_options: supabase.lib.client_options.ClientOptions) -> supabase._async.auth_client.AsyncSupabaseAuthClient
24,186
supabase._async.client
_listen_to_auth_events
null
def _listen_to_auth_events( self, event: AuthChangeEvent, session: Union[Session, None] ): access_token = self.supabase_key if event in ["SIGNED_IN", "TOKEN_REFRESHED", "SIGNED_OUT"]: # reset postgrest and storage instance on event change self._postgrest = None self._storage = None self._functions = None access_token = session.access_token if session else self.supabase_key self.options.headers["Authorization"] = self._create_auth_header(access_token)
(self, event: Literal['PASSWORD_RECOVERY', 'SIGNED_IN', 'SIGNED_OUT', 'TOKEN_REFRESHED', 'USER_UPDATED', 'USER_DELETED', 'MFA_CHALLENGE_VERIFIED'], session: Optional[gotrue.types.Session])
24,187
supabase._async.client
from_
Perform a table operation. See the `table` method.
def from_(self, table_name: str) -> AsyncRequestBuilder: """Perform a table operation. See the `table` method. """ return self.postgrest.from_(table_name)
(self, table_name: str) -> postgrest._async.request_builder.AsyncRequestBuilder
24,188
supabase._async.client
rpc
Performs a stored procedure call. Parameters ---------- fn : callable The stored procedure call to be executed. params : dict of any Parameters passed into the stored procedure call. Returns ------- SyncFilterRequestBuilder Returns a filter builder. This lets you apply filters on the response of an RPC.
def rpc( self, fn: str, params: Optional[Dict[Any, Any]] = None ) -> AsyncRPCFilterRequestBuilder: """Performs a stored procedure call. Parameters ---------- fn : callable The stored procedure call to be executed. params : dict of any Parameters passed into the stored procedure call. Returns ------- SyncFilterRequestBuilder Returns a filter builder. This lets you apply filters on the response of an RPC. """ if params is None: params = {} return self.postgrest.rpc(fn, params)
(self, fn: str, params: Optional[Dict[Any, Any]] = None) -> postgrest._async.request_builder.AsyncRPCFilterRequestBuilder
24,189
supabase._async.client
table
Perform a table operation. Note that the supabase client uses the `from` method, but in Python, this is a reserved keyword, so we have elected to use the name `table`. Alternatively you can use the `.from_()` method.
def table(self, table_name: str) -> AsyncRequestBuilder: """Perform a table operation. Note that the supabase client uses the `from` method, but in Python, this is a reserved keyword, so we have elected to use the name `table`. Alternatively you can use the `.from_()` method. """ return self.from_(table_name)
(self, table_name: str) -> postgrest._async.request_builder.AsyncRequestBuilder
24,190
supabase.lib.client_options
ClientOptions
ClientOptions(schema: str = 'public', headers: Dict[str, str] = <factory>, auto_refresh_token: bool = True, persist_session: bool = True, storage: gotrue._sync.storage.SyncSupportedStorage = <factory>, realtime: Optional[Dict[str, Any]] = None, postgrest_client_timeout: Union[int, float, httpx.Timeout] = 120, storage_client_timeout: Union[int, float, httpx.Timeout] = 20, flow_type: Literal['pkce', 'implicit'] = 'implicit')
class ClientOptions: schema: str = "public" """ The Postgres schema which your tables belong to. Must be on the list of exposed schemas in Supabase. Defaults to 'public'. """ headers: Dict[str, str] = field(default_factory=DEFAULT_HEADERS.copy) """Optional headers for initializing the client.""" auto_refresh_token: bool = True """Automatically refreshes the token for logged in users.""" persist_session: bool = True """Whether to persist a logged in session to storage.""" storage: SyncSupportedStorage = field(default_factory=SyncMemoryStorage) """A storage provider. Used to store the logged in session.""" realtime: Optional[Dict[str, Any]] = None """Options passed to the realtime-py instance""" postgrest_client_timeout: Union[int, float, Timeout] = ( DEFAULT_POSTGREST_CLIENT_TIMEOUT ) """Timeout passed to the SyncPostgrestClient instance.""" storage_client_timeout: Union[int, float, Timeout] = DEFAULT_STORAGE_CLIENT_TIMEOUT """Timeout passed to the SyncStorageClient instance""" flow_type: AuthFlowType = "implicit" """flow type to use for authentication""" def replace( self, schema: Optional[str] = None, headers: Optional[Dict[str, str]] = None, auto_refresh_token: Optional[bool] = None, persist_session: Optional[bool] = None, storage: Optional[SyncSupportedStorage] = None, realtime: Optional[Dict[str, Any]] = None, postgrest_client_timeout: Union[ int, float, Timeout ] = DEFAULT_POSTGREST_CLIENT_TIMEOUT, storage_client_timeout: Union[ int, float, Timeout ] = DEFAULT_STORAGE_CLIENT_TIMEOUT, flow_type: Optional[AuthFlowType] = None, ) -> "ClientOptions": """Create a new SupabaseClientOptions with changes""" client_options = ClientOptions() client_options.schema = schema or self.schema client_options.headers = headers or self.headers client_options.auto_refresh_token = ( auto_refresh_token or self.auto_refresh_token ) client_options.persist_session = persist_session or self.persist_session client_options.storage = storage or self.storage client_options.realtime = realtime or self.realtime client_options.postgrest_client_timeout = ( postgrest_client_timeout or self.postgrest_client_timeout ) client_options.storage_client_timeout = ( storage_client_timeout or self.storage_client_timeout ) client_options.flow_type = flow_type or self.flow_type return client_options
(schema: str = 'public', headers: Dict[str, str] = <factory>, auto_refresh_token: bool = True, persist_session: bool = True, storage: gotrue._sync.storage.SyncSupportedStorage = <factory>, realtime: Optional[Dict[str, Any]] = None, postgrest_client_timeout: Union[int, float, httpx.Timeout] = 120, storage_client_timeout: Union[int, float, httpx.Timeout] = 20, flow_type: Literal['pkce', 'implicit'] = 'implicit') -> None
24,191
supabase.lib.client_options
__eq__
null
from dataclasses import dataclass, field from typing import Any, Dict, Optional, Union from gotrue import AuthFlowType, SyncMemoryStorage, SyncSupportedStorage from httpx import Timeout from postgrest.constants import DEFAULT_POSTGREST_CLIENT_TIMEOUT from storage3.constants import DEFAULT_TIMEOUT as DEFAULT_STORAGE_CLIENT_TIMEOUT from supabase import __version__ DEFAULT_HEADERS = {"X-Client-Info": f"supabase-py/{__version__}"} @dataclass class ClientOptions: schema: str = "public" """ The Postgres schema which your tables belong to. Must be on the list of exposed schemas in Supabase. Defaults to 'public'. """ headers: Dict[str, str] = field(default_factory=DEFAULT_HEADERS.copy) """Optional headers for initializing the client.""" auto_refresh_token: bool = True """Automatically refreshes the token for logged in users.""" persist_session: bool = True """Whether to persist a logged in session to storage.""" storage: SyncSupportedStorage = field(default_factory=SyncMemoryStorage) """A storage provider. Used to store the logged in session.""" realtime: Optional[Dict[str, Any]] = None """Options passed to the realtime-py instance""" postgrest_client_timeout: Union[int, float, Timeout] = ( DEFAULT_POSTGREST_CLIENT_TIMEOUT ) """Timeout passed to the SyncPostgrestClient instance.""" storage_client_timeout: Union[int, float, Timeout] = DEFAULT_STORAGE_CLIENT_TIMEOUT """Timeout passed to the SyncStorageClient instance""" flow_type: AuthFlowType = "implicit" """flow type to use for authentication""" def replace( self, schema: Optional[str] = None, headers: Optional[Dict[str, str]] = None, auto_refresh_token: Optional[bool] = None, persist_session: Optional[bool] = None, storage: Optional[SyncSupportedStorage] = None, realtime: Optional[Dict[str, Any]] = None, postgrest_client_timeout: Union[ int, float, Timeout ] = DEFAULT_POSTGREST_CLIENT_TIMEOUT, storage_client_timeout: Union[ int, float, Timeout ] = DEFAULT_STORAGE_CLIENT_TIMEOUT, flow_type: Optional[AuthFlowType] = None, ) -> "ClientOptions": """Create a new SupabaseClientOptions with changes""" client_options = ClientOptions() client_options.schema = schema or self.schema client_options.headers = headers or self.headers client_options.auto_refresh_token = ( auto_refresh_token or self.auto_refresh_token ) client_options.persist_session = persist_session or self.persist_session client_options.storage = storage or self.storage client_options.realtime = realtime or self.realtime client_options.postgrest_client_timeout = ( postgrest_client_timeout or self.postgrest_client_timeout ) client_options.storage_client_timeout = ( storage_client_timeout or self.storage_client_timeout ) client_options.flow_type = flow_type or self.flow_type return client_options
(self, other)
24,194
supabase.lib.client_options
replace
Create a new SupabaseClientOptions with changes
def replace( self, schema: Optional[str] = None, headers: Optional[Dict[str, str]] = None, auto_refresh_token: Optional[bool] = None, persist_session: Optional[bool] = None, storage: Optional[SyncSupportedStorage] = None, realtime: Optional[Dict[str, Any]] = None, postgrest_client_timeout: Union[ int, float, Timeout ] = DEFAULT_POSTGREST_CLIENT_TIMEOUT, storage_client_timeout: Union[ int, float, Timeout ] = DEFAULT_STORAGE_CLIENT_TIMEOUT, flow_type: Optional[AuthFlowType] = None, ) -> "ClientOptions": """Create a new SupabaseClientOptions with changes""" client_options = ClientOptions() client_options.schema = schema or self.schema client_options.headers = headers or self.headers client_options.auto_refresh_token = ( auto_refresh_token or self.auto_refresh_token ) client_options.persist_session = persist_session or self.persist_session client_options.storage = storage or self.storage client_options.realtime = realtime or self.realtime client_options.postgrest_client_timeout = ( postgrest_client_timeout or self.postgrest_client_timeout ) client_options.storage_client_timeout = ( storage_client_timeout or self.storage_client_timeout ) client_options.flow_type = flow_type or self.flow_type return client_options
(self, schema: Optional[str] = None, headers: Optional[Dict[str, str]] = None, auto_refresh_token: Optional[bool] = None, persist_session: Optional[bool] = None, storage: Optional[gotrue._sync.storage.SyncSupportedStorage] = None, realtime: Optional[Dict[str, Any]] = None, postgrest_client_timeout: Union[int, float, httpx.Timeout] = 120, storage_client_timeout: Union[int, float, httpx.Timeout] = 20, flow_type: Optional[Literal['pkce', 'implicit']] = None) -> supabase.lib.client_options.ClientOptions
24,195
supabase._async.auth_client
AsyncSupabaseAuthClient
SupabaseAuthClient
class AsyncSupabaseAuthClient(AsyncGoTrueClient): """SupabaseAuthClient""" def __init__( self, *, url: str, headers: Optional[Dict[str, str]] = None, storage_key: Optional[str] = None, auto_refresh_token: bool = True, persist_session: bool = True, storage: AsyncSupportedStorage = AsyncMemoryStorage(), http_client: Optional[AsyncClient] = None, flow_type: AuthFlowType = "implicit" ): """Instantiate SupabaseAuthClient instance.""" if headers is None: headers = {} AsyncGoTrueClient.__init__( self, url=url, headers=headers, storage_key=storage_key, auto_refresh_token=auto_refresh_token, persist_session=persist_session, storage=storage, http_client=http_client, flow_type=flow_type, )
(*, url: str, headers: Optional[Dict[str, str]] = None, storage_key: Optional[str] = None, auto_refresh_token: bool = True, persist_session: bool = True, storage: gotrue._async.storage.AsyncSupportedStorage = <gotrue._async.storage.AsyncMemoryStorage object at 0x7f3ffe96f280>, http_client: Optional[httpx.AsyncClient] = None, flow_type: Literal['pkce', 'implicit'] = 'implicit')
24,196
gotrue._async.gotrue_base_api
__aenter__
null
def __init__( self, *, url: str, headers: Dict[str, str], http_client: Union[AsyncClient, None], ): self._url = url self._headers = headers self._http_client = http_client or AsyncClient()
(self) -> typing_extensions.Self
24,198
supabase._async.auth_client
__init__
Instantiate SupabaseAuthClient instance.
def __init__( self, *, url: str, headers: Optional[Dict[str, str]] = None, storage_key: Optional[str] = None, auto_refresh_token: bool = True, persist_session: bool = True, storage: AsyncSupportedStorage = AsyncMemoryStorage(), http_client: Optional[AsyncClient] = None, flow_type: AuthFlowType = "implicit" ): """Instantiate SupabaseAuthClient instance.""" if headers is None: headers = {} AsyncGoTrueClient.__init__( self, url=url, headers=headers, storage_key=storage_key, auto_refresh_token=auto_refresh_token, persist_session=persist_session, storage=storage, http_client=http_client, flow_type=flow_type, )
(self, *, url: str, headers: Optional[Dict[str, str]] = None, storage_key: Optional[str] = None, auto_refresh_token: bool = True, persist_session: bool = True, storage: gotrue._async.storage.AsyncSupportedStorage = <gotrue._async.storage.AsyncMemoryStorage object at 0x7f3ffe96f280>, http_client: Optional[httpx.AsyncClient] = None, flow_type: Literal['pkce', 'implicit'] = 'implicit')
24,199
gotrue._async.gotrue_client
_call_refresh_token
null
def on_auth_state_change( self, callback: Callable[[AuthChangeEvent, Union[Session, None]], None], ) -> Subscription: """ Receive a notification every time an auth event happens. """ unique_id = str(uuid4()) def _unsubscribe() -> None: self._state_change_emitters.pop(unique_id) subscription = Subscription( id=unique_id, callback=callback, unsubscribe=_unsubscribe, ) self._state_change_emitters[unique_id] = subscription return subscription
(self, refresh_token: str) -> gotrue.types.Session
24,202
gotrue._async.gotrue_client
_decode_jwt
Decodes a JWT (without performing any validation).
def _decode_jwt(self, jwt: str) -> DecodedJWTDict: """ Decodes a JWT (without performing any validation). """ return decode_jwt_payload(jwt)
(self, jwt: str) -> gotrue.types.DecodedJWTDict
24,205
gotrue._async.gotrue_client
_get_param
null
def _get_param( self, query_params: Dict[str, List[str]], name: str, ) -> Union[str, None]: return query_params[name][0] if name in query_params else None
(self, query_params: Dict[str, List[str]], name: str) -> Optional[str]
24,207
gotrue._async.gotrue_client
_get_url_for_provider
null
def _is_implicit_grant_flow(self, url: str) -> bool: result = urlparse(url) params = parse_qs(result.query) return "access_token" in params or "error_description" in params
(self, provider: Literal['apple', 'azure', 'bitbucket', 'discord', 'facebook', 'figma', 'github', 'gitlab', 'google', 'kakao', 'keycloak', 'linkedin', 'notion', 'slack', 'spotify', 'twitch', 'twitter', 'workos', 'zoom'], params: Dict[str, str]) -> str
24,208
gotrue._async.gotrue_client
_get_valid_session
null
def _get_valid_session( self, raw_session: Union[str, None], ) -> Union[Session, None]: if not raw_session: return None data = loads(raw_session) if not data: return None if not data.get("access_token"): return None if not data.get("refresh_token"): return None if not data.get("expires_at"): return None try: expires_at = int(data["expires_at"]) data["expires_at"] = expires_at except ValueError: return None try: return model_validate(Session, data) except Exception: return None
(self, raw_session: Optional[str]) -> Optional[gotrue.types.Session]
24,211
gotrue._async.gotrue_client
_notify_all_subscribers
null
def _notify_all_subscribers( self, event: AuthChangeEvent, session: Union[Session, None], ) -> None: for subscription in self._state_change_emitters.values(): subscription.callback(event, session)
(self, event: Literal['PASSWORD_RECOVERY', 'SIGNED_IN', 'SIGNED_OUT', 'TOKEN_REFRESHED', 'USER_UPDATED', 'USER_DELETED', 'MFA_CHALLENGE_VERIFIED'], session: Optional[gotrue.types.Session]) -> NoneType
24,215
gotrue._async.gotrue_base_api
_request
null
@overload async def _request( self, method: Literal["GET", "OPTIONS", "HEAD", "POST", "PUT", "PATCH", "DELETE"], path: str, *, jwt: Union[str, None] = None, redirect_to: Union[str, None] = None, headers: Union[Dict[str, str], None] = None, query: Union[Dict[str, str], None] = None, body: Union[Any, None] = None, no_resolve_json: bool = False, ) -> None: ... # pragma: no cover
(self, method: Literal['GET', 'OPTIONS', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE'], path: str, *, jwt: Optional[str] = None, redirect_to: Optional[str] = None, headers: Optional[Dict[str, str]] = None, query: Optional[Dict[str, str]] = None, body: Optional[Any] = None, no_resolve_json: bool = False, xform: Optional[Callable[[Any], ~T]] = None) -> Optional[~T]
24,221
gotrue._async.gotrue_client
exchange_code_for_session
null
def _decode_jwt(self, jwt: str) -> DecodedJWTDict: """ Decodes a JWT (without performing any validation). """ return decode_jwt_payload(jwt)
(self, params: gotrue.types.CodeExchangeParams)
24,222
gotrue._async.gotrue_client
get_session
Returns the session, refreshing it if necessary. The session returned can be null if the session is not detected which can happen in the event a user is not signed-in or has logged out.
def __init__( self, *, url: Union[str, None] = None, headers: Union[Dict[str, str], None] = None, storage_key: Union[str, None] = None, auto_refresh_token: bool = True, persist_session: bool = True, storage: Union[AsyncSupportedStorage, None] = None, http_client: Union[AsyncClient, None] = None, flow_type: AuthFlowType = "implicit", ) -> None: AsyncGoTrueBaseAPI.__init__( self, url=url or GOTRUE_URL, headers=headers or DEFAULT_HEADERS, http_client=http_client, ) self._storage_key = storage_key or STORAGE_KEY self._auto_refresh_token = auto_refresh_token self._persist_session = persist_session self._storage = storage or AsyncMemoryStorage() self._in_memory_session: Union[Session, None] = None self._refresh_token_timer: Union[Timer, None] = None self._network_retries = 0 self._state_change_emitters: Dict[str, Subscription] = {} self._flow_type = flow_type self.admin = AsyncGoTrueAdminAPI( url=self._url, headers=self._headers, http_client=self._http_client, ) self.mfa = AsyncGoTrueMFAAPI() self.mfa.challenge = self._challenge self.mfa.challenge_and_verify = self._challenge_and_verify self.mfa.enroll = self._enroll self.mfa.get_authenticator_assurance_level = ( self._get_authenticator_assurance_level ) self.mfa.list_factors = self._list_factors self.mfa.unenroll = self._unenroll self.mfa.verify = self._verify
(self) -> Optional[gotrue.types.Session]
24,223
gotrue._async.gotrue_client
get_user
Gets the current user details if there is an existing session. Takes in an optional access token `jwt`. If no `jwt` is provided, `get_user()` will attempt to get the `jwt` from the current session.
def __init__( self, *, url: Union[str, None] = None, headers: Union[Dict[str, str], None] = None, storage_key: Union[str, None] = None, auto_refresh_token: bool = True, persist_session: bool = True, storage: Union[AsyncSupportedStorage, None] = None, http_client: Union[AsyncClient, None] = None, flow_type: AuthFlowType = "implicit", ) -> None: AsyncGoTrueBaseAPI.__init__( self, url=url or GOTRUE_URL, headers=headers or DEFAULT_HEADERS, http_client=http_client, ) self._storage_key = storage_key or STORAGE_KEY self._auto_refresh_token = auto_refresh_token self._persist_session = persist_session self._storage = storage or AsyncMemoryStorage() self._in_memory_session: Union[Session, None] = None self._refresh_token_timer: Union[Timer, None] = None self._network_retries = 0 self._state_change_emitters: Dict[str, Subscription] = {} self._flow_type = flow_type self.admin = AsyncGoTrueAdminAPI( url=self._url, headers=self._headers, http_client=self._http_client, ) self.mfa = AsyncGoTrueMFAAPI() self.mfa.challenge = self._challenge self.mfa.challenge_and_verify = self._challenge_and_verify self.mfa.enroll = self._enroll self.mfa.get_authenticator_assurance_level = ( self._get_authenticator_assurance_level ) self.mfa.list_factors = self._list_factors self.mfa.unenroll = self._unenroll self.mfa.verify = self._verify
(self, jwt: Optional[str] = None) -> Optional[gotrue.types.UserResponse]
24,224
gotrue._async.gotrue_client
get_user_identities
null
def __init__( self, *, url: Union[str, None] = None, headers: Union[Dict[str, str], None] = None, storage_key: Union[str, None] = None, auto_refresh_token: bool = True, persist_session: bool = True, storage: Union[AsyncSupportedStorage, None] = None, http_client: Union[AsyncClient, None] = None, flow_type: AuthFlowType = "implicit", ) -> None: AsyncGoTrueBaseAPI.__init__( self, url=url or GOTRUE_URL, headers=headers or DEFAULT_HEADERS, http_client=http_client, ) self._storage_key = storage_key or STORAGE_KEY self._auto_refresh_token = auto_refresh_token self._persist_session = persist_session self._storage = storage or AsyncMemoryStorage() self._in_memory_session: Union[Session, None] = None self._refresh_token_timer: Union[Timer, None] = None self._network_retries = 0 self._state_change_emitters: Dict[str, Subscription] = {} self._flow_type = flow_type self.admin = AsyncGoTrueAdminAPI( url=self._url, headers=self._headers, http_client=self._http_client, ) self.mfa = AsyncGoTrueMFAAPI() self.mfa.challenge = self._challenge self.mfa.challenge_and_verify = self._challenge_and_verify self.mfa.enroll = self._enroll self.mfa.get_authenticator_assurance_level = ( self._get_authenticator_assurance_level ) self.mfa.list_factors = self._list_factors self.mfa.unenroll = self._unenroll self.mfa.verify = self._verify
(self)
24,229
gotrue._async.gotrue_client
on_auth_state_change
Receive a notification every time an auth event happens.
def on_auth_state_change( self, callback: Callable[[AuthChangeEvent, Union[Session, None]], None], ) -> Subscription: """ Receive a notification every time an auth event happens. """ unique_id = str(uuid4()) def _unsubscribe() -> None: self._state_change_emitters.pop(unique_id) subscription = Subscription( id=unique_id, callback=callback, unsubscribe=_unsubscribe, ) self._state_change_emitters[unique_id] = subscription return subscription
(self, callback: Callable[[Literal['PASSWORD_RECOVERY', 'SIGNED_IN', 'SIGNED_OUT', 'TOKEN_REFRESHED', 'USER_UPDATED', 'USER_DELETED', 'MFA_CHALLENGE_VERIFIED'], Optional[gotrue.types.Session]], NoneType]) -> gotrue.types.Subscription
24,230
gotrue._async.gotrue_client
refresh_session
Returns a new session, regardless of expiry status. Takes in an optional current session. If not passed in, then refreshSession() will attempt to retrieve it from getSession(). If the current session's refresh token is invalid, an error will be thrown.
def __init__( self, *, url: Union[str, None] = None, headers: Union[Dict[str, str], None] = None, storage_key: Union[str, None] = None, auto_refresh_token: bool = True, persist_session: bool = True, storage: Union[AsyncSupportedStorage, None] = None, http_client: Union[AsyncClient, None] = None, flow_type: AuthFlowType = "implicit", ) -> None: AsyncGoTrueBaseAPI.__init__( self, url=url or GOTRUE_URL, headers=headers or DEFAULT_HEADERS, http_client=http_client, ) self._storage_key = storage_key or STORAGE_KEY self._auto_refresh_token = auto_refresh_token self._persist_session = persist_session self._storage = storage or AsyncMemoryStorage() self._in_memory_session: Union[Session, None] = None self._refresh_token_timer: Union[Timer, None] = None self._network_retries = 0 self._state_change_emitters: Dict[str, Subscription] = {} self._flow_type = flow_type self.admin = AsyncGoTrueAdminAPI( url=self._url, headers=self._headers, http_client=self._http_client, ) self.mfa = AsyncGoTrueMFAAPI() self.mfa.challenge = self._challenge self.mfa.challenge_and_verify = self._challenge_and_verify self.mfa.enroll = self._enroll self.mfa.get_authenticator_assurance_level = ( self._get_authenticator_assurance_level ) self.mfa.list_factors = self._list_factors self.mfa.unenroll = self._unenroll self.mfa.verify = self._verify
(self, refresh_token: Optional[str] = None) -> gotrue.types.AuthResponse
24,231
gotrue._async.gotrue_client
reset_password_email
Sends a password reset request to an email address.
def on_auth_state_change( self, callback: Callable[[AuthChangeEvent, Union[Session, None]], None], ) -> Subscription: """ Receive a notification every time an auth event happens. """ unique_id = str(uuid4()) def _unsubscribe() -> None: self._state_change_emitters.pop(unique_id) subscription = Subscription( id=unique_id, callback=callback, unsubscribe=_unsubscribe, ) self._state_change_emitters[unique_id] = subscription return subscription
(self, email: str, options: gotrue.types.Options = {}) -> NoneType
24,232
gotrue._async.gotrue_client
set_session
Sets the session data from the current session. If the current session is expired, `set_session` will take care of refreshing it to obtain a new session. If the refresh token in the current session is invalid and the current session has expired, an error will be thrown. If the current session does not contain at `expires_at` field, `set_session` will use the exp claim defined in the access token. The current session that minimally contains an access token, refresh token and a user.
def __init__( self, *, url: Union[str, None] = None, headers: Union[Dict[str, str], None] = None, storage_key: Union[str, None] = None, auto_refresh_token: bool = True, persist_session: bool = True, storage: Union[AsyncSupportedStorage, None] = None, http_client: Union[AsyncClient, None] = None, flow_type: AuthFlowType = "implicit", ) -> None: AsyncGoTrueBaseAPI.__init__( self, url=url or GOTRUE_URL, headers=headers or DEFAULT_HEADERS, http_client=http_client, ) self._storage_key = storage_key or STORAGE_KEY self._auto_refresh_token = auto_refresh_token self._persist_session = persist_session self._storage = storage or AsyncMemoryStorage() self._in_memory_session: Union[Session, None] = None self._refresh_token_timer: Union[Timer, None] = None self._network_retries = 0 self._state_change_emitters: Dict[str, Subscription] = {} self._flow_type = flow_type self.admin = AsyncGoTrueAdminAPI( url=self._url, headers=self._headers, http_client=self._http_client, ) self.mfa = AsyncGoTrueMFAAPI() self.mfa.challenge = self._challenge self.mfa.challenge_and_verify = self._challenge_and_verify self.mfa.enroll = self._enroll self.mfa.get_authenticator_assurance_level = ( self._get_authenticator_assurance_level ) self.mfa.list_factors = self._list_factors self.mfa.unenroll = self._unenroll self.mfa.verify = self._verify
(self, access_token: str, refresh_token: str) -> gotrue.types.AuthResponse
24,233
gotrue._async.gotrue_client
sign_in_with_oauth
Log in an existing user via a third-party provider.
def __init__( self, *, url: Union[str, None] = None, headers: Union[Dict[str, str], None] = None, storage_key: Union[str, None] = None, auto_refresh_token: bool = True, persist_session: bool = True, storage: Union[AsyncSupportedStorage, None] = None, http_client: Union[AsyncClient, None] = None, flow_type: AuthFlowType = "implicit", ) -> None: AsyncGoTrueBaseAPI.__init__( self, url=url or GOTRUE_URL, headers=headers or DEFAULT_HEADERS, http_client=http_client, ) self._storage_key = storage_key or STORAGE_KEY self._auto_refresh_token = auto_refresh_token self._persist_session = persist_session self._storage = storage or AsyncMemoryStorage() self._in_memory_session: Union[Session, None] = None self._refresh_token_timer: Union[Timer, None] = None self._network_retries = 0 self._state_change_emitters: Dict[str, Subscription] = {} self._flow_type = flow_type self.admin = AsyncGoTrueAdminAPI( url=self._url, headers=self._headers, http_client=self._http_client, ) self.mfa = AsyncGoTrueMFAAPI() self.mfa.challenge = self._challenge self.mfa.challenge_and_verify = self._challenge_and_verify self.mfa.enroll = self._enroll self.mfa.get_authenticator_assurance_level = ( self._get_authenticator_assurance_level ) self.mfa.list_factors = self._list_factors self.mfa.unenroll = self._unenroll self.mfa.verify = self._verify
(self, credentials: gotrue.types.SignInWithOAuthCredentials) -> gotrue.types.OAuthResponse
24,234
gotrue._async.gotrue_client
sign_in_with_otp
Log in a user using magiclink or a one-time password (OTP). If the `{{ .ConfirmationURL }}` variable is specified in the email template, a magiclink will be sent. If the `{{ .Token }}` variable is specified in the email template, an OTP will be sent. If you're using phone sign-ins, only an OTP will be sent. You won't be able to send a magiclink for phone sign-ins.
def __init__( self, *, url: Union[str, None] = None, headers: Union[Dict[str, str], None] = None, storage_key: Union[str, None] = None, auto_refresh_token: bool = True, persist_session: bool = True, storage: Union[AsyncSupportedStorage, None] = None, http_client: Union[AsyncClient, None] = None, flow_type: AuthFlowType = "implicit", ) -> None: AsyncGoTrueBaseAPI.__init__( self, url=url or GOTRUE_URL, headers=headers or DEFAULT_HEADERS, http_client=http_client, ) self._storage_key = storage_key or STORAGE_KEY self._auto_refresh_token = auto_refresh_token self._persist_session = persist_session self._storage = storage or AsyncMemoryStorage() self._in_memory_session: Union[Session, None] = None self._refresh_token_timer: Union[Timer, None] = None self._network_retries = 0 self._state_change_emitters: Dict[str, Subscription] = {} self._flow_type = flow_type self.admin = AsyncGoTrueAdminAPI( url=self._url, headers=self._headers, http_client=self._http_client, ) self.mfa = AsyncGoTrueMFAAPI() self.mfa.challenge = self._challenge self.mfa.challenge_and_verify = self._challenge_and_verify self.mfa.enroll = self._enroll self.mfa.get_authenticator_assurance_level = ( self._get_authenticator_assurance_level ) self.mfa.list_factors = self._list_factors self.mfa.unenroll = self._unenroll self.mfa.verify = self._verify
(self, credentials: Union[gotrue.types.SignInWithEmailAndPasswordlessCredentials, gotrue.types.SignInWithPhoneAndPasswordlessCredentials]) -> gotrue.types.AuthOtpResponse
24,235
gotrue._async.gotrue_client
sign_in_with_password
Log in an existing user with an email or phone and password.
def __init__( self, *, url: Union[str, None] = None, headers: Union[Dict[str, str], None] = None, storage_key: Union[str, None] = None, auto_refresh_token: bool = True, persist_session: bool = True, storage: Union[AsyncSupportedStorage, None] = None, http_client: Union[AsyncClient, None] = None, flow_type: AuthFlowType = "implicit", ) -> None: AsyncGoTrueBaseAPI.__init__( self, url=url or GOTRUE_URL, headers=headers or DEFAULT_HEADERS, http_client=http_client, ) self._storage_key = storage_key or STORAGE_KEY self._auto_refresh_token = auto_refresh_token self._persist_session = persist_session self._storage = storage or AsyncMemoryStorage() self._in_memory_session: Union[Session, None] = None self._refresh_token_timer: Union[Timer, None] = None self._network_retries = 0 self._state_change_emitters: Dict[str, Subscription] = {} self._flow_type = flow_type self.admin = AsyncGoTrueAdminAPI( url=self._url, headers=self._headers, http_client=self._http_client, ) self.mfa = AsyncGoTrueMFAAPI() self.mfa.challenge = self._challenge self.mfa.challenge_and_verify = self._challenge_and_verify self.mfa.enroll = self._enroll self.mfa.get_authenticator_assurance_level = ( self._get_authenticator_assurance_level ) self.mfa.list_factors = self._list_factors self.mfa.unenroll = self._unenroll self.mfa.verify = self._verify
(self, credentials: Union[gotrue.types.SignInWithEmailAndPasswordCredentials, gotrue.types.SignInWithPhoneAndPasswordCredentials]) -> gotrue.types.AuthResponse
24,236
gotrue._async.gotrue_client
sign_in_with_sso
Attempts a single-sign on using an enterprise Identity Provider. A successful SSO attempt will redirect the current page to the identity provider authorization page. The redirect URL is implementation and SSO protocol specific. You can use it by providing a SSO domain. Typically you can extract this domain by asking users for their email address. If this domain is registered on the Auth instance the redirect will use that organization's currently active SSO Identity Provider for the login. If you have built an organization-specific login page, you can use the organization's SSO Identity Provider UUID directly instead.
def __init__( self, *, url: Union[str, None] = None, headers: Union[Dict[str, str], None] = None, storage_key: Union[str, None] = None, auto_refresh_token: bool = True, persist_session: bool = True, storage: Union[AsyncSupportedStorage, None] = None, http_client: Union[AsyncClient, None] = None, flow_type: AuthFlowType = "implicit", ) -> None: AsyncGoTrueBaseAPI.__init__( self, url=url or GOTRUE_URL, headers=headers or DEFAULT_HEADERS, http_client=http_client, ) self._storage_key = storage_key or STORAGE_KEY self._auto_refresh_token = auto_refresh_token self._persist_session = persist_session self._storage = storage or AsyncMemoryStorage() self._in_memory_session: Union[Session, None] = None self._refresh_token_timer: Union[Timer, None] = None self._network_retries = 0 self._state_change_emitters: Dict[str, Subscription] = {} self._flow_type = flow_type self.admin = AsyncGoTrueAdminAPI( url=self._url, headers=self._headers, http_client=self._http_client, ) self.mfa = AsyncGoTrueMFAAPI() self.mfa.challenge = self._challenge self.mfa.challenge_and_verify = self._challenge_and_verify self.mfa.enroll = self._enroll self.mfa.get_authenticator_assurance_level = ( self._get_authenticator_assurance_level ) self.mfa.list_factors = self._list_factors self.mfa.unenroll = self._unenroll self.mfa.verify = self._verify
(self, credentials: 'SignInWithSSOCredentials')
24,237
gotrue._async.gotrue_client
sign_out
Inside a browser context, `sign_out` will remove the logged in user from the browser session and log them out - removing all items from localstorage and then trigger a `"SIGNED_OUT"` event. For server-side management, you can revoke all refresh tokens for a user by passing a user's JWT through to `api.sign_out`. There is no way to revoke a user's access token jwt until it expires. It is recommended to set a shorter expiry on the jwt for this reason.
def __init__( self, *, url: Union[str, None] = None, headers: Union[Dict[str, str], None] = None, storage_key: Union[str, None] = None, auto_refresh_token: bool = True, persist_session: bool = True, storage: Union[AsyncSupportedStorage, None] = None, http_client: Union[AsyncClient, None] = None, flow_type: AuthFlowType = "implicit", ) -> None: AsyncGoTrueBaseAPI.__init__( self, url=url or GOTRUE_URL, headers=headers or DEFAULT_HEADERS, http_client=http_client, ) self._storage_key = storage_key or STORAGE_KEY self._auto_refresh_token = auto_refresh_token self._persist_session = persist_session self._storage = storage or AsyncMemoryStorage() self._in_memory_session: Union[Session, None] = None self._refresh_token_timer: Union[Timer, None] = None self._network_retries = 0 self._state_change_emitters: Dict[str, Subscription] = {} self._flow_type = flow_type self.admin = AsyncGoTrueAdminAPI( url=self._url, headers=self._headers, http_client=self._http_client, ) self.mfa = AsyncGoTrueMFAAPI() self.mfa.challenge = self._challenge self.mfa.challenge_and_verify = self._challenge_and_verify self.mfa.enroll = self._enroll self.mfa.get_authenticator_assurance_level = ( self._get_authenticator_assurance_level ) self.mfa.list_factors = self._list_factors self.mfa.unenroll = self._unenroll self.mfa.verify = self._verify
(self, options: gotrue.types.SignOutOptions = {'scope': 'global'}) -> NoneType
24,238
gotrue._async.gotrue_client
sign_up
Creates a new user.
def __init__( self, *, url: Union[str, None] = None, headers: Union[Dict[str, str], None] = None, storage_key: Union[str, None] = None, auto_refresh_token: bool = True, persist_session: bool = True, storage: Union[AsyncSupportedStorage, None] = None, http_client: Union[AsyncClient, None] = None, flow_type: AuthFlowType = "implicit", ) -> None: AsyncGoTrueBaseAPI.__init__( self, url=url or GOTRUE_URL, headers=headers or DEFAULT_HEADERS, http_client=http_client, ) self._storage_key = storage_key or STORAGE_KEY self._auto_refresh_token = auto_refresh_token self._persist_session = persist_session self._storage = storage or AsyncMemoryStorage() self._in_memory_session: Union[Session, None] = None self._refresh_token_timer: Union[Timer, None] = None self._network_retries = 0 self._state_change_emitters: Dict[str, Subscription] = {} self._flow_type = flow_type self.admin = AsyncGoTrueAdminAPI( url=self._url, headers=self._headers, http_client=self._http_client, ) self.mfa = AsyncGoTrueMFAAPI() self.mfa.challenge = self._challenge self.mfa.challenge_and_verify = self._challenge_and_verify self.mfa.enroll = self._enroll self.mfa.get_authenticator_assurance_level = ( self._get_authenticator_assurance_level ) self.mfa.list_factors = self._list_factors self.mfa.unenroll = self._unenroll self.mfa.verify = self._verify
(self, credentials: Union[gotrue.types.SignUpWithEmailAndPasswordCredentials, gotrue.types.SignUpWithPhoneAndPasswordCredentials]) -> gotrue.types.AuthResponse
24,240
gotrue._async.gotrue_client
update_user
Updates user data, if there is a logged in user.
def __init__( self, *, url: Union[str, None] = None, headers: Union[Dict[str, str], None] = None, storage_key: Union[str, None] = None, auto_refresh_token: bool = True, persist_session: bool = True, storage: Union[AsyncSupportedStorage, None] = None, http_client: Union[AsyncClient, None] = None, flow_type: AuthFlowType = "implicit", ) -> None: AsyncGoTrueBaseAPI.__init__( self, url=url or GOTRUE_URL, headers=headers or DEFAULT_HEADERS, http_client=http_client, ) self._storage_key = storage_key or STORAGE_KEY self._auto_refresh_token = auto_refresh_token self._persist_session = persist_session self._storage = storage or AsyncMemoryStorage() self._in_memory_session: Union[Session, None] = None self._refresh_token_timer: Union[Timer, None] = None self._network_retries = 0 self._state_change_emitters: Dict[str, Subscription] = {} self._flow_type = flow_type self.admin = AsyncGoTrueAdminAPI( url=self._url, headers=self._headers, http_client=self._http_client, ) self.mfa = AsyncGoTrueMFAAPI() self.mfa.challenge = self._challenge self.mfa.challenge_and_verify = self._challenge_and_verify self.mfa.enroll = self._enroll self.mfa.get_authenticator_assurance_level = ( self._get_authenticator_assurance_level ) self.mfa.list_factors = self._list_factors self.mfa.unenroll = self._unenroll self.mfa.verify = self._verify
(self, attributes: gotrue.types.UserAttributes) -> gotrue.types.UserResponse
24,241
gotrue._async.gotrue_client
verify_otp
Log in a user given a User supplied OTP received via mobile.
def __init__( self, *, url: Union[str, None] = None, headers: Union[Dict[str, str], None] = None, storage_key: Union[str, None] = None, auto_refresh_token: bool = True, persist_session: bool = True, storage: Union[AsyncSupportedStorage, None] = None, http_client: Union[AsyncClient, None] = None, flow_type: AuthFlowType = "implicit", ) -> None: AsyncGoTrueBaseAPI.__init__( self, url=url or GOTRUE_URL, headers=headers or DEFAULT_HEADERS, http_client=http_client, ) self._storage_key = storage_key or STORAGE_KEY self._auto_refresh_token = auto_refresh_token self._persist_session = persist_session self._storage = storage or AsyncMemoryStorage() self._in_memory_session: Union[Session, None] = None self._refresh_token_timer: Union[Timer, None] = None self._network_retries = 0 self._state_change_emitters: Dict[str, Subscription] = {} self._flow_type = flow_type self.admin = AsyncGoTrueAdminAPI( url=self._url, headers=self._headers, http_client=self._http_client, ) self.mfa = AsyncGoTrueMFAAPI() self.mfa.challenge = self._challenge self.mfa.challenge_and_verify = self._challenge_and_verify self.mfa.enroll = self._enroll self.mfa.get_authenticator_assurance_level = ( self._get_authenticator_assurance_level ) self.mfa.list_factors = self._list_factors self.mfa.unenroll = self._unenroll self.mfa.verify = self._verify
(self, params: Union[gotrue.types.VerifyEmailOtpParams, gotrue.types.VerifyMobileOtpParams, gotrue.types.VerifyTokenHashParams]) -> gotrue.types.AuthResponse
24,242
storage3._async.client
AsyncStorageClient
Manage storage buckets and files.
class AsyncStorageClient(AsyncStorageBucketAPI): """Manage storage buckets and files.""" def __init__( self, url: str, headers: dict[str, str], timeout: int = DEFAULT_TIMEOUT ) -> None: headers = { "User-Agent": f"supabase-py/storage3 v{__version__}", **headers, } self.session = self._create_session(url, headers, timeout) super().__init__(self.session) def _create_session( self, base_url: str, headers: dict[str, str], timeout: int ) -> AsyncClient: return AsyncClient(base_url=base_url, headers=headers, timeout=timeout) async def __aenter__(self) -> AsyncStorageClient: return self async def __aexit__(self, exc_type, exc, tb) -> None: await self.aclose() async def aclose(self) -> None: await self.session.aclose() def from_(self, id: str) -> AsyncBucketProxy: """Run a storage file operation. Parameters ---------- id The unique identifier of the bucket """ return AsyncBucketProxy(id, self._client)
(url: 'str', headers: 'dict[str, str]', timeout: 'int' = 20) -> 'None'
24,243
storage3._async.client
__aenter__
null
def _create_session( self, base_url: str, headers: dict[str, str], timeout: int ) -> AsyncClient: return AsyncClient(base_url=base_url, headers=headers, timeout=timeout)
(self) -> storage3._async.client.AsyncStorageClient
24,245
storage3._async.client
__init__
null
def __init__( self, url: str, headers: dict[str, str], timeout: int = DEFAULT_TIMEOUT ) -> None: headers = { "User-Agent": f"supabase-py/storage3 v{__version__}", **headers, } self.session = self._create_session(url, headers, timeout) super().__init__(self.session)
(self, url: str, headers: dict[str, str], timeout: int = 20) -> NoneType
24,247
storage3._async.bucket
_request
null
def __init__(self, session: AsyncClient) -> None: self._client = session
(self, method: Literal['GET', 'POST', 'DELETE', 'PUT', 'HEAD'], url: str, json: Optional[dict[Any, Any]] = None) -> httpx.Response
24,249
storage3._async.bucket
create_bucket
Creates a new storage bucket. Parameters ---------- id A unique identifier for the bucket you are creating. name A name for the bucket you are creating. If not passed, the id is used as the name as well. options Extra options to send while creating the bucket. Valid options are `public`, `file_size_limit` and `allowed_mime_types`.
def __init__(self, session: AsyncClient) -> None: self._client = session
(self, id: str, name: Optional[str] = None, options: Optional[storage3.types.CreateOrUpdateBucketOptions] = None) -> dict[str, str]
24,250
storage3._async.bucket
delete_bucket
Deletes an existing bucket. Note that you cannot delete buckets with existing objects inside. You must first `empty()` the bucket. Parameters ---------- id The unique identifier of the bucket you would like to delete.
def __init__(self, session: AsyncClient) -> None: self._client = session
(self, id: str) -> dict[str, str]
24,251
storage3._async.bucket
empty_bucket
Removes all objects inside a single bucket. Parameters ---------- id The unique identifier of the bucket you would like to empty.
def __init__(self, session: AsyncClient) -> None: self._client = session
(self, id: str) -> dict[str, str]
24,252
storage3._async.client
from_
Run a storage file operation. Parameters ---------- id The unique identifier of the bucket
def from_(self, id: str) -> AsyncBucketProxy: """Run a storage file operation. Parameters ---------- id The unique identifier of the bucket """ return AsyncBucketProxy(id, self._client)
(self, id: str) -> storage3._async.file_api.AsyncBucketProxy
24,253
storage3._async.bucket
get_bucket
Retrieves the details of an existing storage bucket. Parameters ---------- id The unique identifier of the bucket you would like to retrieve.
def __init__(self, session: AsyncClient) -> None: self._client = session
(self, id: str) -> storage3._async.file_api.AsyncBucket
24,254
storage3._async.bucket
list_buckets
Retrieves the details of all storage buckets within an existing product.
def __init__(self, session: AsyncClient) -> None: self._client = session
(self) -> list[storage3._async.file_api.AsyncBucket]
24,255
storage3._async.bucket
update_bucket
Update a storage bucket. Parameters ---------- id The unique identifier of the bucket you would like to update. options The properties you want to update. Valid options are `public`, `file_size_limit` and `allowed_mime_types`.
def __init__(self, session: AsyncClient) -> None: self._client = session
(self, id: str, options: storage3.types.CreateOrUpdateBucketOptions) -> dict[str, str]
24,256
supabase._sync.client
SyncClient
Supabase client class.
class SyncClient: """Supabase client class.""" def __init__( self, supabase_url: str, supabase_key: str, options: Union[ClientOptions, None] = None, ): """Instantiate the client. Parameters ---------- supabase_url: str The URL to the Supabase instance that should be connected to. supabase_key: str The API key to the Supabase instance that should be connected to. **options Any extra settings to be optionally specified - also see the `DEFAULT_OPTIONS` dict. """ if not supabase_url: raise SupabaseException("supabase_url is required") if not supabase_key: raise SupabaseException("supabase_key is required") # Check if the url and key are valid if not re.match(r"^(https?)://.+", supabase_url): raise SupabaseException("Invalid URL") # Check if the key is a valid JWT if not re.match( r"^[A-Za-z0-9-_=]+\.[A-Za-z0-9-_=]+\.?[A-Za-z0-9-_.+/=]*$", supabase_key ): raise SupabaseException("Invalid API key") if options is None: options = ClientOptions(storage=SyncMemoryStorage()) self.supabase_url = supabase_url self.supabase_key = supabase_key self.options = options options.headers.update(self._get_auth_headers()) self.rest_url = f"{supabase_url}/rest/v1" self.realtime_url = f"{supabase_url}/realtime/v1".replace("http", "ws") self.auth_url = f"{supabase_url}/auth/v1" self.storage_url = f"{supabase_url}/storage/v1" self.functions_url = f"{supabase_url}/functions/v1" self.schema = options.schema # Instantiate clients. self.auth = self._init_supabase_auth_client( auth_url=self.auth_url, client_options=options, ) # TODO: Bring up to parity with JS client. # self.realtime: SupabaseRealtimeClient = self._init_realtime_client( # realtime_url=self.realtime_url, # supabase_key=self.supabase_key, # ) self.realtime = None self._postgrest = None self._storage = None self._functions = None self.auth.on_auth_state_change(self._listen_to_auth_events) @classmethod def create( cls, supabase_url: str, supabase_key: str, options: Union[ClientOptions, None] = None, ): return cls(supabase_url, supabase_key, options) def table(self, table_name: str) -> SyncRequestBuilder: """Perform a table operation. Note that the supabase client uses the `from` method, but in Python, this is a reserved keyword, so we have elected to use the name `table`. Alternatively you can use the `.from_()` method. """ return self.from_(table_name) def from_(self, table_name: str) -> SyncRequestBuilder: """Perform a table operation. See the `table` method. """ return self.postgrest.from_(table_name) def rpc( self, fn: str, params: Optional[Dict[Any, Any]] = None ) -> SyncRPCFilterRequestBuilder: """Performs a stored procedure call. Parameters ---------- fn : callable The stored procedure call to be executed. params : dict of any Parameters passed into the stored procedure call. Returns ------- SyncFilterRequestBuilder Returns a filter builder. This lets you apply filters on the response of an RPC. """ if params is None: params = {} return self.postgrest.rpc(fn, params) @property def postgrest(self): if self._postgrest is None: self._postgrest = self._init_postgrest_client( rest_url=self.rest_url, headers=self.options.headers, schema=self.options.schema, timeout=self.options.postgrest_client_timeout, ) return self._postgrest @property def storage(self): if self._storage is None: self._storage = self._init_storage_client( storage_url=self.storage_url, headers=self.options.headers, storage_client_timeout=self.options.storage_client_timeout, ) return self._storage @property def functions(self): if self._functions is None: self._functions = SyncFunctionsClient( self.functions_url, self.options.headers ) return self._functions # async def remove_subscription_helper(resolve): # try: # await self._close_subscription(subscription) # open_subscriptions = len(self.get_subscriptions()) # if not open_subscriptions: # error = await self.realtime.disconnect() # if error: # return {"error": None, "data": { open_subscriptions}} # except Exception as e: # raise e # return remove_subscription_helper(subscription) # async def _close_subscription(self, subscription): # """Close a given subscription # Parameters # ---------- # subscription # The name of the channel # """ # if not subscription.closed: # await self._closeChannel(subscription) # def get_subscriptions(self): # """Return all channels the client is subscribed to.""" # return self.realtime.channels # @staticmethod # def _init_realtime_client( # realtime_url: str, supabase_key: str # ) -> SupabaseRealtimeClient: # """Private method for creating an instance of the realtime-py client.""" # return SupabaseRealtimeClient( # realtime_url, {"params": {"apikey": supabase_key}} # ) @staticmethod def _init_storage_client( storage_url: str, headers: Dict[str, str], storage_client_timeout: int = DEFAULT_STORAGE_CLIENT_TIMEOUT, ) -> SyncStorageClient: return SyncStorageClient(storage_url, headers, storage_client_timeout) @staticmethod def _init_supabase_auth_client( auth_url: str, client_options: ClientOptions, ) -> SyncSupabaseAuthClient: """Creates a wrapped instance of the GoTrue Client.""" return SyncSupabaseAuthClient( url=auth_url, auto_refresh_token=client_options.auto_refresh_token, persist_session=client_options.persist_session, storage=client_options.storage, headers=client_options.headers, flow_type=client_options.flow_type, ) @staticmethod def _init_postgrest_client( rest_url: str, headers: Dict[str, str], schema: str, timeout: Union[int, float, Timeout] = DEFAULT_POSTGREST_CLIENT_TIMEOUT, ) -> SyncPostgrestClient: """Private helper for creating an instance of the Postgrest client.""" return SyncPostgrestClient( rest_url, headers=headers, schema=schema, timeout=timeout ) def _create_auth_header(self, token: str): return f"Bearer {token}" def _get_auth_headers(self) -> Dict[str, str]: """Helper method to get auth headers.""" return { "apiKey": self.supabase_key, "Authorization": self.options.headers.get( "Authorization", self._create_auth_header(self.supabase_key) ), } def _listen_to_auth_events( self, event: AuthChangeEvent, session: Union[Session, None] ): access_token = self.supabase_key if event in ["SIGNED_IN", "TOKEN_REFRESHED", "SIGNED_OUT"]: # reset postgrest and storage instance on event change self._postgrest = None self._storage = None self._functions = None access_token = session.access_token if session else self.supabase_key self.options.headers["Authorization"] = self._create_auth_header(access_token)
(supabase_url: str, supabase_key: str, options: Optional[supabase.lib.client_options.ClientOptions] = None)
24,257
supabase._sync.client
__init__
Instantiate the client. Parameters ---------- supabase_url: str The URL to the Supabase instance that should be connected to. supabase_key: str The API key to the Supabase instance that should be connected to. **options Any extra settings to be optionally specified - also see the `DEFAULT_OPTIONS` dict.
def __init__( self, supabase_url: str, supabase_key: str, options: Union[ClientOptions, None] = None, ): """Instantiate the client. Parameters ---------- supabase_url: str The URL to the Supabase instance that should be connected to. supabase_key: str The API key to the Supabase instance that should be connected to. **options Any extra settings to be optionally specified - also see the `DEFAULT_OPTIONS` dict. """ if not supabase_url: raise SupabaseException("supabase_url is required") if not supabase_key: raise SupabaseException("supabase_key is required") # Check if the url and key are valid if not re.match(r"^(https?)://.+", supabase_url): raise SupabaseException("Invalid URL") # Check if the key is a valid JWT if not re.match( r"^[A-Za-z0-9-_=]+\.[A-Za-z0-9-_=]+\.?[A-Za-z0-9-_.+/=]*$", supabase_key ): raise SupabaseException("Invalid API key") if options is None: options = ClientOptions(storage=SyncMemoryStorage()) self.supabase_url = supabase_url self.supabase_key = supabase_key self.options = options options.headers.update(self._get_auth_headers()) self.rest_url = f"{supabase_url}/rest/v1" self.realtime_url = f"{supabase_url}/realtime/v1".replace("http", "ws") self.auth_url = f"{supabase_url}/auth/v1" self.storage_url = f"{supabase_url}/storage/v1" self.functions_url = f"{supabase_url}/functions/v1" self.schema = options.schema # Instantiate clients. self.auth = self._init_supabase_auth_client( auth_url=self.auth_url, client_options=options, ) # TODO: Bring up to parity with JS client. # self.realtime: SupabaseRealtimeClient = self._init_realtime_client( # realtime_url=self.realtime_url, # supabase_key=self.supabase_key, # ) self.realtime = None self._postgrest = None self._storage = None self._functions = None self.auth.on_auth_state_change(self._listen_to_auth_events)
(self, supabase_url: str, supabase_key: str, options: Optional[supabase.lib.client_options.ClientOptions] = None)
24,260
supabase._sync.client
_init_postgrest_client
Private helper for creating an instance of the Postgrest client.
@staticmethod def _init_postgrest_client( rest_url: str, headers: Dict[str, str], schema: str, timeout: Union[int, float, Timeout] = DEFAULT_POSTGREST_CLIENT_TIMEOUT, ) -> SyncPostgrestClient: """Private helper for creating an instance of the Postgrest client.""" return SyncPostgrestClient( rest_url, headers=headers, schema=schema, timeout=timeout )
(rest_url: str, headers: Dict[str, str], schema: str, timeout: Union[int, float, httpx.Timeout] = 120) -> postgrest._sync.client.SyncPostgrestClient
24,261
supabase._sync.client
_init_storage_client
null
@staticmethod def _init_storage_client( storage_url: str, headers: Dict[str, str], storage_client_timeout: int = DEFAULT_STORAGE_CLIENT_TIMEOUT, ) -> SyncStorageClient: return SyncStorageClient(storage_url, headers, storage_client_timeout)
(storage_url: str, headers: Dict[str, str], storage_client_timeout: int = 20) -> storage3._sync.client.SyncStorageClient
24,262
supabase._sync.client
_init_supabase_auth_client
Creates a wrapped instance of the GoTrue Client.
@staticmethod def _init_supabase_auth_client( auth_url: str, client_options: ClientOptions, ) -> SyncSupabaseAuthClient: """Creates a wrapped instance of the GoTrue Client.""" return SyncSupabaseAuthClient( url=auth_url, auto_refresh_token=client_options.auto_refresh_token, persist_session=client_options.persist_session, storage=client_options.storage, headers=client_options.headers, flow_type=client_options.flow_type, )
(auth_url: str, client_options: supabase.lib.client_options.ClientOptions) -> supabase._sync.auth_client.SyncSupabaseAuthClient
24,264
supabase._sync.client
from_
Perform a table operation. See the `table` method.
def from_(self, table_name: str) -> SyncRequestBuilder: """Perform a table operation. See the `table` method. """ return self.postgrest.from_(table_name)
(self, table_name: str) -> postgrest._sync.request_builder.SyncRequestBuilder
24,265
supabase._sync.client
rpc
Performs a stored procedure call. Parameters ---------- fn : callable The stored procedure call to be executed. params : dict of any Parameters passed into the stored procedure call. Returns ------- SyncFilterRequestBuilder Returns a filter builder. This lets you apply filters on the response of an RPC.
def rpc( self, fn: str, params: Optional[Dict[Any, Any]] = None ) -> SyncRPCFilterRequestBuilder: """Performs a stored procedure call. Parameters ---------- fn : callable The stored procedure call to be executed. params : dict of any Parameters passed into the stored procedure call. Returns ------- SyncFilterRequestBuilder Returns a filter builder. This lets you apply filters on the response of an RPC. """ if params is None: params = {} return self.postgrest.rpc(fn, params)
(self, fn: str, params: Optional[Dict[Any, Any]] = None) -> postgrest._sync.request_builder.SyncRPCFilterRequestBuilder
24,266
supabase._sync.client
table
Perform a table operation. Note that the supabase client uses the `from` method, but in Python, this is a reserved keyword, so we have elected to use the name `table`. Alternatively you can use the `.from_()` method.
def table(self, table_name: str) -> SyncRequestBuilder: """Perform a table operation. Note that the supabase client uses the `from` method, but in Python, this is a reserved keyword, so we have elected to use the name `table`. Alternatively you can use the `.from_()` method. """ return self.from_(table_name)
(self, table_name: str) -> postgrest._sync.request_builder.SyncRequestBuilder
24,272
postgrest.exceptions
APIError
Base exception for all API errors.
class APIError(Exception): """ Base exception for all API errors. """ _raw_error: Dict[str, str] message: Optional[str] """The error message.""" code: Optional[str] """The error code.""" hint: Optional[str] """The error hint.""" details: Optional[str] """The error details.""" def __init__(self, error: Dict[str, str]) -> None: self._raw_error = error self.message = error.get("message") self.code = error.get("code") self.hint = error.get("hint") self.details = error.get("details") Exception.__init__(self, str(self)) def __repr__(self) -> str: error_text = f"Error {self.code}:" if self.code else "" message_text = f"\nMessage: {self.message}" if self.message else "" hint_text = f"\nHint: {self.hint}" if self.hint else "" details_text = f"\nDetails: {self.details}" if self.details else "" complete_error_text = f"{error_text}{message_text}{hint_text}{details_text}" return complete_error_text or "Empty error" def json(self) -> Dict[str, str]: """Convert the error into a dictionary. Returns: :class:`dict` """ return self._raw_error
(error: Dict[str, str]) -> None
24,273
postgrest.exceptions
__init__
null
def __init__(self, error: Dict[str, str]) -> None: self._raw_error = error self.message = error.get("message") self.code = error.get("code") self.hint = error.get("hint") self.details = error.get("details") Exception.__init__(self, str(self))
(self, error: Dict[str, str]) -> NoneType
24,274
postgrest.exceptions
__repr__
null
def __repr__(self) -> str: error_text = f"Error {self.code}:" if self.code else "" message_text = f"\nMessage: {self.message}" if self.message else "" hint_text = f"\nHint: {self.hint}" if self.hint else "" details_text = f"\nDetails: {self.details}" if self.details else "" complete_error_text = f"{error_text}{message_text}{hint_text}{details_text}" return complete_error_text or "Empty error"
(self) -> str
24,275
postgrest.exceptions
json
Convert the error into a dictionary. Returns: :class:`dict`
def json(self) -> Dict[str, str]: """Convert the error into a dictionary. Returns: :class:`dict` """ return self._raw_error
(self) -> Dict[str, str]
24,276
postgrest.base_request_builder
APIResponse
null
class APIResponse(BaseModel, Generic[_ReturnT]): data: List[_ReturnT] """The data returned by the query.""" count: Optional[int] = None """The number of rows returned.""" @field_validator("data") @classmethod def raise_when_api_error(cls: Type[Self], value: Any) -> Any: if isinstance(value, dict) and value.get("message"): raise ValueError("You are passing an API error to the data field.") return value @staticmethod def _get_count_from_content_range_header( content_range_header: str, ) -> Optional[int]: content_range = content_range_header.split("/") return None if len(content_range) < 2 else int(content_range[1]) @staticmethod def _is_count_in_prefer_header(prefer_header: str) -> bool: pattern = f"count=({'|'.join([cm.value for cm in CountMethod])})" return bool(search(pattern, prefer_header)) @classmethod def _get_count_from_http_request_response( cls: Type[Self], request_response: RequestResponse, ) -> Optional[int]: prefer_header: Optional[str] = request_response.request.headers.get("prefer") if not prefer_header: return None is_count_in_prefer_header = cls._is_count_in_prefer_header(prefer_header) content_range_header: Optional[str] = request_response.headers.get( "content-range" ) return ( cls._get_count_from_content_range_header(content_range_header) if (is_count_in_prefer_header and content_range_header) else None ) @classmethod def from_http_request_response( cls: Type[Self], request_response: RequestResponse ) -> Self: try: data = request_response.json() except JSONDecodeError as e: return cls(data=[], count=0) count = cls._get_count_from_http_request_response(request_response) # the type-ignore here is as pydantic needs us to pass the type parameter # here explicitly, but pylance already knows that cls is correctly parametrized return cls[_ReturnT](data=data, count=count) # type: ignore @classmethod def from_dict(cls: Type[Self], dict: Dict[str, Any]) -> Self: keys = dict.keys() assert len(keys) == 3 and "data" in keys and "count" in keys and "error" in keys return cls[_ReturnT]( # type: ignore data=dict.get("data"), count=dict.get("count"), error=dict.get("error") )
(*, data: List[~_ReturnT], count: Optional[int] = None) -> None
24,283
pydantic.main
__init__
Create a new model by parsing and validating input data from keyword arguments. Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model. `self` is explicitly positional-only to allow `self` as a field name.
def __init__(self, /, **data: Any) -> None: # type: ignore """Create a new model by parsing and validating input data from keyword arguments. Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model. `self` is explicitly positional-only to allow `self` as a field name. """ # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks __tracebackhide__ = True self.__pydantic_validator__.validate_python(data, self_instance=self)
(self, /, **data: Any) -> NoneType
24,291
pydantic.main
__setattr__
null
def __setattr__(self, name: str, value: Any) -> None: if name in self.__class_vars__: raise AttributeError( f'{name!r} is a ClassVar of `{self.__class__.__name__}` and cannot be set on an instance. ' f'If you want to set a value on the class, use `{self.__class__.__name__}.{name} = value`.' ) elif not _fields.is_valid_field_name(name): if self.__pydantic_private__ is None or name not in self.__private_attributes__: _object_setattr(self, name, value) else: attribute = self.__private_attributes__[name] if hasattr(attribute, '__set__'): attribute.__set__(self, value) # type: ignore else: self.__pydantic_private__[name] = value return self._check_frozen(name, value) attr = getattr(self.__class__, name, None) if isinstance(attr, property): attr.__set__(self, value) elif self.model_config.get('validate_assignment', None): self.__pydantic_validator__.validate_assignment(self, name, value) elif self.model_config.get('extra') != 'allow' and name not in self.model_fields: # TODO - matching error raise ValueError(f'"{self.__class__.__name__}" object has no field "{name}"') elif self.model_config.get('extra') == 'allow' and name not in self.model_fields: if self.model_extra and name in self.model_extra: self.__pydantic_extra__[name] = value # type: ignore else: try: getattr(self, name) except AttributeError: # attribute does not already exist on instance, so put it in extra self.__pydantic_extra__[name] = value # type: ignore else: # attribute _does_ already exist on instance, and was not in extra, so update it _object_setattr(self, name, value) else: self.__dict__[name] = value self.__pydantic_fields_set__.add(name)
(self, name: str, value: Any) -> NoneType
24,297
postgrest.base_request_builder
_get_count_from_content_range_header
null
@staticmethod def _get_count_from_content_range_header( content_range_header: str, ) -> Optional[int]: content_range = content_range_header.split("/") return None if len(content_range) < 2 else int(content_range[1])
(content_range_header: str) -> Optional[int]
24,298
postgrest.base_request_builder
_is_count_in_prefer_header
null
@staticmethod def _is_count_in_prefer_header(prefer_header: str) -> bool: pattern = f"count=({'|'.join([cm.value for cm in CountMethod])})" return bool(search(pattern, prefer_header))
(prefer_header: str) -> bool
24,307
storage3.utils
StorageException
Error raised when an operation on the storage API fails.
class StorageException(Exception): """Error raised when an operation on the storage API fails."""
null
24,308
supabase._sync.auth_client
SyncSupabaseAuthClient
SupabaseAuthClient
class SyncSupabaseAuthClient(SyncGoTrueClient): """SupabaseAuthClient""" def __init__( self, *, url: str, headers: Optional[Dict[str, str]] = None, storage_key: Optional[str] = None, auto_refresh_token: bool = True, persist_session: bool = True, storage: SyncSupportedStorage = SyncMemoryStorage(), http_client: Optional[SyncClient] = None, flow_type: AuthFlowType = "implicit" ): """Instantiate SupabaseAuthClient instance.""" if headers is None: headers = {} SyncGoTrueClient.__init__( self, url=url, headers=headers, storage_key=storage_key, auto_refresh_token=auto_refresh_token, persist_session=persist_session, storage=storage, http_client=http_client, flow_type=flow_type, )
(*, url: str, headers: Optional[Dict[str, str]] = None, storage_key: Optional[str] = None, auto_refresh_token: bool = True, persist_session: bool = True, storage: gotrue._sync.storage.SyncSupportedStorage = <gotrue._sync.storage.SyncMemoryStorage object at 0x7f3ffdde7250>, http_client: Optional[gotrue.http_clients.SyncClient] = None, flow_type: Literal['pkce', 'implicit'] = 'implicit')
24,310
gotrue._sync.gotrue_base_api
__exit__
null
def __exit__(self, exc_t, exc_v, exc_tb) -> None: self.close()
(self, exc_t, exc_v, exc_tb) -> NoneType
24,311
supabase._sync.auth_client
__init__
Instantiate SupabaseAuthClient instance.
def __init__( self, *, url: str, headers: Optional[Dict[str, str]] = None, storage_key: Optional[str] = None, auto_refresh_token: bool = True, persist_session: bool = True, storage: SyncSupportedStorage = SyncMemoryStorage(), http_client: Optional[SyncClient] = None, flow_type: AuthFlowType = "implicit" ): """Instantiate SupabaseAuthClient instance.""" if headers is None: headers = {} SyncGoTrueClient.__init__( self, url=url, headers=headers, storage_key=storage_key, auto_refresh_token=auto_refresh_token, persist_session=persist_session, storage=storage, http_client=http_client, flow_type=flow_type, )
(self, *, url: str, headers: Optional[Dict[str, str]] = None, storage_key: Optional[str] = None, auto_refresh_token: bool = True, persist_session: bool = True, storage: gotrue._sync.storage.SyncSupportedStorage = <gotrue._sync.storage.SyncMemoryStorage object at 0x7f3ffdde7250>, http_client: Optional[gotrue.http_clients.SyncClient] = None, flow_type: Literal['pkce', 'implicit'] = 'implicit')
24,312
gotrue._sync.gotrue_client
_call_refresh_token
null
def _call_refresh_token(self, refresh_token: str) -> Session: if not refresh_token: raise AuthSessionMissingError() response = self._refresh_access_token(refresh_token) if not response.session: raise AuthSessionMissingError() self._save_session(response.session) self._notify_all_subscribers("TOKEN_REFRESHED", response.session) return response.session
(self, refresh_token: str) -> gotrue.types.Session
24,313
gotrue._sync.gotrue_client
_challenge
null
def _challenge(self, params: MFAChallengeParams) -> AuthMFAChallengeResponse: session = self.get_session() if not session: raise AuthSessionMissingError() return self._request( "POST", f"factors/{params.get('factor_id')}/challenge", jwt=session.access_token, xform=partial(model_validate, AuthMFAChallengeResponse), )
(self, params: gotrue.types.MFAChallengeParams) -> gotrue.types.AuthMFAChallengeResponse
24,314
gotrue._sync.gotrue_client
_challenge_and_verify
null
def _challenge_and_verify( self, params: MFAChallengeAndVerifyParams, ) -> AuthMFAVerifyResponse: response = self._challenge( { "factor_id": params.get("factor_id"), } ) return self._verify( { "factor_id": params.get("factor_id"), "challenge_id": response.id, "code": params.get("code"), } )
(self, params: gotrue.types.MFAChallengeAndVerifyParams) -> gotrue.types.AuthMFAVerifyResponse
24,316
gotrue._sync.gotrue_client
_enroll
null
def _enroll(self, params: MFAEnrollParams) -> AuthMFAEnrollResponse: session = self.get_session() if not session: raise AuthSessionMissingError() response = self._request( "POST", "factors", body=params, jwt=session.access_token, xform=partial(model_validate, AuthMFAEnrollResponse), ) if response.totp.qr_code: response.totp.qr_code = f"data:image/svg+xml;utf-8,{response.totp.qr_code}" return response
(self, params: gotrue.types.MFAEnrollParams) -> gotrue.types.AuthMFAEnrollResponse
24,317
gotrue._sync.gotrue_client
_get_authenticator_assurance_level
null
def _get_authenticator_assurance_level( self, ) -> AuthMFAGetAuthenticatorAssuranceLevelResponse: session = self.get_session() if not session: return AuthMFAGetAuthenticatorAssuranceLevelResponse( current_level=None, next_level=None, current_authentication_methods=[], ) payload = self._decode_jwt(session.access_token) current_level: Union[AuthenticatorAssuranceLevels, None] = None if payload.get("aal"): current_level = payload.get("aal") verified_factors = [ f for f in session.user.factors or [] if f.status == "verified" ] next_level = "aal2" if verified_factors else current_level current_authentication_methods = payload.get("amr") or [] return AuthMFAGetAuthenticatorAssuranceLevelResponse( current_level=current_level, next_level=next_level, current_authentication_methods=current_authentication_methods, )
(self) -> gotrue.types.AuthMFAGetAuthenticatorAssuranceLevelResponse
24,319
gotrue._sync.gotrue_client
_get_session_from_url
null
def _get_session_from_url( self, url: str, ) -> Tuple[Session, Union[str, None]]: if not self._is_implicit_grant_flow(url): raise AuthImplicitGrantRedirectError("Not a valid implicit grant flow url.") result = urlparse(url) params = parse_qs(result.query) error_description = self._get_param(params, "error_description") if error_description: error_code = self._get_param(params, "error_code") error = self._get_param(params, "error") if not error_code: raise AuthImplicitGrantRedirectError("No error_code detected.") if not error: raise AuthImplicitGrantRedirectError("No error detected.") raise AuthImplicitGrantRedirectError( error_description, {"code": error_code, "error": error}, ) provider_token = self._get_param(params, "provider_token") provider_refresh_token = self._get_param(params, "provider_refresh_token") access_token = self._get_param(params, "access_token") if not access_token: raise AuthImplicitGrantRedirectError("No access_token detected.") expires_in = self._get_param(params, "expires_in") if not expires_in: raise AuthImplicitGrantRedirectError("No expires_in detected.") refresh_token = self._get_param(params, "refresh_token") if not refresh_token: raise AuthImplicitGrantRedirectError("No refresh_token detected.") token_type = self._get_param(params, "token_type") if not token_type: raise AuthImplicitGrantRedirectError("No token_type detected.") time_now = round(time()) expires_at = time_now + int(expires_in) user = self.get_user(access_token) session = Session( provider_token=provider_token, provider_refresh_token=provider_refresh_token, access_token=access_token, expires_in=int(expires_in), expires_at=expires_at, refresh_token=refresh_token, token_type=token_type, user=user.user, ) redirect_type = self._get_param(params, "type") return session, redirect_type
(self, url: str) -> Tuple[gotrue.types.Session, Optional[str]]
24,320
gotrue._sync.gotrue_client
_get_url_for_provider
null
def _get_url_for_provider( self, provider: Provider, params: Dict[str, str], ) -> str: if self._flow_type == "pkce": code_verifier = generate_pkce_verifier() code_challenge = generate_pkce_challenge(code_verifier) self._storage.set_item( f"{self._storage_key}-code-verifier", code_verifier ) code_challenge_method = ( "plain" if code_verifier == code_challenge else "s256" ) params["code_challenge"] = code_challenge params["code_challenge_method"] = code_challenge_method params["provider"] = provider query = urlencode(params) return f"{self._url}/authorize?{query}"
(self, provider: Literal['apple', 'azure', 'bitbucket', 'discord', 'facebook', 'figma', 'github', 'gitlab', 'google', 'kakao', 'keycloak', 'linkedin', 'notion', 'slack', 'spotify', 'twitch', 'twitter', 'workos', 'zoom'], params: Dict[str, str]) -> str
24,323
gotrue._sync.gotrue_client
_list_factors
null
def _list_factors(self) -> AuthMFAListFactorsResponse: response = self.get_user() all = response.user.factors or [] totp = [f for f in all if f.factor_type == "totp" and f.status == "verified"] return AuthMFAListFactorsResponse(all=all, totp=totp)
(self) -> gotrue.types.AuthMFAListFactorsResponse
24,325
gotrue._sync.gotrue_client
_recover_and_refresh
null
def _recover_and_refresh(self) -> None: raw_session = self._storage.get_item(self._storage_key) current_session = self._get_valid_session(raw_session) if not current_session: if raw_session: self._remove_session() return time_now = round(time()) expires_at = current_session.expires_at if expires_at and expires_at < time_now + EXPIRY_MARGIN: refresh_token = current_session.refresh_token if self._auto_refresh_token and refresh_token: self._network_retries += 1 try: self._call_refresh_token(refresh_token) self._network_retries = 0 except Exception as e: if ( isinstance(e, AuthRetryableError) and self._network_retries < MAX_RETRIES ): if self._refresh_token_timer: self._refresh_token_timer.cancel() self._refresh_token_timer = Timer( (RETRY_INTERVAL ** (self._network_retries * 100)), self._recover_and_refresh, ) self._refresh_token_timer.start() return self._remove_session() return if self._persist_session: self._save_session(current_session) self._notify_all_subscribers("SIGNED_IN", current_session)
(self) -> NoneType
24,326
gotrue._sync.gotrue_client
_refresh_access_token
null
def _refresh_access_token(self, refresh_token: str) -> AuthResponse: return self._request( "POST", "token", query={"grant_type": "refresh_token"}, body={"refresh_token": refresh_token}, xform=parse_auth_response, )
(self, refresh_token: str) -> gotrue.types.AuthResponse
24,327
gotrue._sync.gotrue_client
_remove_session
null
def _remove_session(self) -> None: if self._persist_session: self._storage.remove_item(self._storage_key) else: self._in_memory_session = None if self._refresh_token_timer: self._refresh_token_timer.cancel() self._refresh_token_timer = None
(self) -> NoneType
24,328
gotrue._sync.gotrue_base_api
_request
null
def _request( self, method: Literal["GET", "OPTIONS", "HEAD", "POST", "PUT", "PATCH", "DELETE"], path: str, *, jwt: Union[str, None] = None, redirect_to: Union[str, None] = None, headers: Union[Dict[str, str], None] = None, query: Union[Dict[str, str], None] = None, body: Union[Any, None] = None, no_resolve_json: bool = False, xform: Union[Callable[[Any], T], None] = None, ) -> Union[T, None]: url = f"{self._url}/{path}" headers = {**self._headers, **(headers or {})} if "Content-Type" not in headers: headers["Content-Type"] = "application/json;charset=UTF-8" if jwt: headers["Authorization"] = f"Bearer {jwt}" query = query or {} if redirect_to: query["redirect_to"] = redirect_to try: response = self._http_client.request( method, url, headers=headers, params=query, json=model_dump(body) if isinstance(body, BaseModel) else body, ) response.raise_for_status() result = response if no_resolve_json else response.json() if xform: return xform(result) except Exception as e: raise handle_exception(e)
(self, method: Literal['GET', 'OPTIONS', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE'], path: str, *, jwt: Optional[str] = None, redirect_to: Optional[str] = None, headers: Optional[Dict[str, str]] = None, query: Optional[Dict[str, str]] = None, body: Optional[Any] = None, no_resolve_json: bool = False, xform: Optional[Callable[[Any], ~T]] = None) -> Optional[~T]
24,329
gotrue._sync.gotrue_client
_save_session
null
def _save_session(self, session: Session) -> None: if not self._persist_session: self._in_memory_session = session expire_at = session.expires_at if expire_at: time_now = round(time()) expire_in = expire_at - time_now refresh_duration_before_expires = ( EXPIRY_MARGIN if expire_in > EXPIRY_MARGIN else 0.5 ) value = (expire_in - refresh_duration_before_expires) * 1000 self._start_auto_refresh_token(value) if self._persist_session and session.expires_at: self._storage.set_item(self._storage_key, model_dump_json(session))
(self, session: gotrue.types.Session) -> NoneType
24,330
gotrue._sync.gotrue_client
_start_auto_refresh_token
null
def _start_auto_refresh_token(self, value: float) -> None: if self._refresh_token_timer: self._refresh_token_timer.cancel() self._refresh_token_timer = None if value <= 0 or not self._auto_refresh_token: return def refresh_token_function(): self._network_retries += 1 try: session = self.get_session() if session: self._call_refresh_token(session.refresh_token) self._network_retries = 0 except Exception as e: if ( isinstance(e, AuthRetryableError) and self._network_retries < MAX_RETRIES ): self._start_auto_refresh_token( RETRY_INTERVAL ** (self._network_retries * 100) ) self._refresh_token_timer = Timer(value, refresh_token_function) self._refresh_token_timer.start()
(self, value: float) -> NoneType
24,331
gotrue._sync.gotrue_client
_unenroll
null
def _unenroll(self, params: MFAUnenrollParams) -> AuthMFAUnenrollResponse: session = self.get_session() if not session: raise AuthSessionMissingError() return self._request( "DELETE", f"factors/{params.get('factor_id')}", jwt=session.access_token, xform=partial(AuthMFAUnenrollResponse, model_validate), )
(self, params: gotrue.types.MFAUnenrollParams) -> gotrue.types.AuthMFAUnenrollResponse
24,332
gotrue._sync.gotrue_client
_verify
null
def _verify(self, params: MFAVerifyParams) -> AuthMFAVerifyResponse: session = self.get_session() if not session: raise AuthSessionMissingError() response = self._request( "POST", f"factors/{params.get('factor_id')}/verify", body=params, jwt=session.access_token, xform=partial(model_validate, AuthMFAVerifyResponse), ) session = model_validate(Session, model_dump(response)) self._save_session(session) self._notify_all_subscribers("MFA_CHALLENGE_VERIFIED", session) return response
(self, params: gotrue.types.MFAVerifyParams) -> gotrue.types.AuthMFAVerifyResponse
24,333
gotrue._sync.gotrue_base_api
close
null
def close(self) -> None: self._http_client.aclose()
(self) -> NoneType
24,334
gotrue._sync.gotrue_client
exchange_code_for_session
null
def exchange_code_for_session(self, params: CodeExchangeParams): code_verifier = params.get("code_verifier") or self._storage.get_item( f"{self._storage_key}-code-verifier" ) response = self._request( "POST", "token?grant_type=pkce", body={ "auth_code": params.get("auth_code"), "code_verifier": code_verifier, }, redirect_to=params.get("redirect_to"), xform=parse_auth_response, ) self._storage.remove_item(f"{self._storage_key}-code-verifier") if response.session: self._save_session(response.session) self._notify_all_subscribers("SIGNED_IN", response.session) return response
(self, params: gotrue.types.CodeExchangeParams)
24,335
gotrue._sync.gotrue_client
get_session
Returns the session, refreshing it if necessary. The session returned can be null if the session is not detected which can happen in the event a user is not signed-in or has logged out.
def get_session(self) -> Union[Session, None]: """ Returns the session, refreshing it if necessary. The session returned can be null if the session is not detected which can happen in the event a user is not signed-in or has logged out. """ current_session: Union[Session, None] = None if self._persist_session: maybe_session = self._storage.get_item(self._storage_key) current_session = self._get_valid_session(maybe_session) if not current_session: self._remove_session() else: current_session = self._in_memory_session if not current_session: return None time_now = round(time()) has_expired = ( current_session.expires_at <= time_now + EXPIRY_MARGIN if current_session.expires_at else False ) return ( self._call_refresh_token(current_session.refresh_token) if has_expired else current_session )
(self) -> Optional[gotrue.types.Session]
24,336
gotrue._sync.gotrue_client
get_user
Gets the current user details if there is an existing session. Takes in an optional access token `jwt`. If no `jwt` is provided, `get_user()` will attempt to get the `jwt` from the current session.
def get_user(self, jwt: Union[str, None] = None) -> Union[UserResponse, None]: """ Gets the current user details if there is an existing session. Takes in an optional access token `jwt`. If no `jwt` is provided, `get_user()` will attempt to get the `jwt` from the current session. """ if not jwt: session = self.get_session() if session: jwt = session.access_token else: return None return self._request("GET", "user", jwt=jwt, xform=parse_user_response)
(self, jwt: Optional[str] = None) -> Optional[gotrue.types.UserResponse]
24,337
gotrue._sync.gotrue_client
get_user_identities
null
def get_user_identities(self): response = self.get_user() return ( IdentitiesResponse(identities=response.user.identities) if response.user else AuthSessionMissingError() )
(self)
24,338
gotrue._sync.gotrue_client
initialize
null
def initialize(self, *, url: Union[str, None] = None) -> None: if url and self._is_implicit_grant_flow(url): self.initialize_from_url(url) else: self.initialize_from_storage()
(self, *, url: Optional[str] = None) -> NoneType
24,339
gotrue._sync.gotrue_client
initialize_from_storage
null
def initialize_from_storage(self) -> None: return self._recover_and_refresh()
(self) -> NoneType
24,340
gotrue._sync.gotrue_client
initialize_from_url
null
def initialize_from_url(self, url: str) -> None: try: if self._is_implicit_grant_flow(url): session, redirect_type = self._get_session_from_url(url) self._save_session(session) self._notify_all_subscribers("SIGNED_IN", session) if redirect_type == "recovery": self._notify_all_subscribers("PASSWORD_RECOVERY", session) except Exception as e: self._remove_session() raise e
(self, url: str) -> NoneType
24,341
gotrue._sync.gotrue_client
link_identity
null
def link_identity(self, credentials): provider = credentials.get("provider") options = credentials.get("options", {}) redirect_to = options.get("redirect_to") scopes = options.get("scopes") params = options.get("query_params", {}) if redirect_to: params["redirect_to"] = redirect_to if scopes: params["scopes"] = scopes params["skip_browser_redirect"] = True url = self._get_url_for_provider(provider, params) return OAuthResponse(provider=provider, url=url)
(self, credentials)
24,343
gotrue._sync.gotrue_client
refresh_session
Returns a new session, regardless of expiry status. Takes in an optional current session. If not passed in, then refreshSession() will attempt to retrieve it from getSession(). If the current session's refresh token is invalid, an error will be thrown.
def refresh_session( self, refresh_token: Union[str, None] = None ) -> AuthResponse: """ Returns a new session, regardless of expiry status. Takes in an optional current session. If not passed in, then refreshSession() will attempt to retrieve it from getSession(). If the current session's refresh token is invalid, an error will be thrown. """ if not refresh_token: session = self.get_session() if session: refresh_token = session.refresh_token if not refresh_token: raise AuthSessionMissingError() session = self._call_refresh_token(refresh_token) return AuthResponse(session=session, user=session.user)
(self, refresh_token: Optional[str] = None) -> gotrue.types.AuthResponse
24,344
gotrue._sync.gotrue_client
reset_password_email
Sends a password reset request to an email address.
def reset_password_email( self, email: str, options: Options = {}, ) -> None: """ Sends a password reset request to an email address. """ self._request( "POST", "recover", body={ "email": email, "gotrue_meta_security": { "captcha_token": options.get("captcha_token"), }, }, redirect_to=options.get("redirect_to"), )
(self, email: str, options: gotrue.types.Options = {}) -> NoneType
24,345
gotrue._sync.gotrue_client
set_session
Sets the session data from the current session. If the current session is expired, `set_session` will take care of refreshing it to obtain a new session. If the refresh token in the current session is invalid and the current session has expired, an error will be thrown. If the current session does not contain at `expires_at` field, `set_session` will use the exp claim defined in the access token. The current session that minimally contains an access token, refresh token and a user.
def set_session(self, access_token: str, refresh_token: str) -> AuthResponse: """ Sets the session data from the current session. If the current session is expired, `set_session` will take care of refreshing it to obtain a new session. If the refresh token in the current session is invalid and the current session has expired, an error will be thrown. If the current session does not contain at `expires_at` field, `set_session` will use the exp claim defined in the access token. The current session that minimally contains an access token, refresh token and a user. """ time_now = round(time()) expires_at = time_now has_expired = True session: Union[Session, None] = None if access_token and access_token.split(".")[1]: payload = self._decode_jwt(access_token) exp = payload.get("exp") if exp: expires_at = int(exp) has_expired = expires_at <= time_now if has_expired: if not refresh_token: raise AuthSessionMissingError() response = self._refresh_access_token(refresh_token) if not response.session: return AuthResponse() session = response.session else: response = self.get_user(access_token) session = Session( access_token=access_token, refresh_token=refresh_token, user=response.user, token_type="bearer", expires_in=expires_at - time_now, expires_at=expires_at, ) self._save_session(session) self._notify_all_subscribers("TOKEN_REFRESHED", session) return AuthResponse(session=session, user=response.user)
(self, access_token: str, refresh_token: str) -> gotrue.types.AuthResponse
24,346
gotrue._sync.gotrue_client
sign_in_with_oauth
Log in an existing user via a third-party provider.
def sign_in_with_oauth( self, credentials: SignInWithOAuthCredentials, ) -> OAuthResponse: """ Log in an existing user via a third-party provider. """ self._remove_session() provider = credentials.get("provider") options = credentials.get("options", {}) redirect_to = options.get("redirect_to") scopes = options.get("scopes") params = options.get("query_params", {}) if redirect_to: params["redirect_to"] = redirect_to if scopes: params["scopes"] = scopes url = self._get_url_for_provider(provider, params) return OAuthResponse(provider=provider, url=url)
(self, credentials: gotrue.types.SignInWithOAuthCredentials) -> gotrue.types.OAuthResponse
24,347
gotrue._sync.gotrue_client
sign_in_with_otp
Log in a user using magiclink or a one-time password (OTP). If the `{{ .ConfirmationURL }}` variable is specified in the email template, a magiclink will be sent. If the `{{ .Token }}` variable is specified in the email template, an OTP will be sent. If you're using phone sign-ins, only an OTP will be sent. You won't be able to send a magiclink for phone sign-ins.
def sign_in_with_otp( self, credentials: SignInWithPasswordlessCredentials, ) -> AuthOtpResponse: """ Log in a user using magiclink or a one-time password (OTP). If the `{{ .ConfirmationURL }}` variable is specified in the email template, a magiclink will be sent. If the `{{ .Token }}` variable is specified in the email template, an OTP will be sent. If you're using phone sign-ins, only an OTP will be sent. You won't be able to send a magiclink for phone sign-ins. """ self._remove_session() email = credentials.get("email") phone = credentials.get("phone") options = credentials.get("options", {}) email_redirect_to = options.get("email_redirect_to") should_create_user = options.get("create_user", True) data = options.get("data") captcha_token = options.get("captcha_token") if email: return self._request( "POST", "otp", body={ "email": email, "data": data, "create_user": should_create_user, "gotrue_meta_security": { "captcha_token": captcha_token, }, }, redirect_to=email_redirect_to, xform=parse_auth_otp_response, ) if phone: return self._request( "POST", "otp", body={ "phone": phone, "data": data, "create_user": should_create_user, "gotrue_meta_security": { "captcha_token": captcha_token, }, }, xform=parse_auth_otp_response, ) raise AuthInvalidCredentialsError( "You must provide either an email or phone number" )
(self, credentials: Union[gotrue.types.SignInWithEmailAndPasswordlessCredentials, gotrue.types.SignInWithPhoneAndPasswordlessCredentials]) -> gotrue.types.AuthOtpResponse
24,348
gotrue._sync.gotrue_client
sign_in_with_password
Log in an existing user with an email or phone and password.
def sign_in_with_password( self, credentials: SignInWithPasswordCredentials, ) -> AuthResponse: """ Log in an existing user with an email or phone and password. """ self._remove_session() email = credentials.get("email") phone = credentials.get("phone") password = credentials.get("password") options = credentials.get("options", {}) data = options.get("data") or {} captcha_token = options.get("captcha_token") if email: response = self._request( "POST", "token", body={ "email": email, "password": password, "data": data, "gotrue_meta_security": { "captcha_token": captcha_token, }, }, query={ "grant_type": "password", }, xform=parse_auth_response, ) elif phone: response = self._request( "POST", "token", body={ "phone": phone, "password": password, "data": data, "gotrue_meta_security": { "captcha_token": captcha_token, }, }, query={ "grant_type": "password", }, xform=parse_auth_response, ) else: raise AuthInvalidCredentialsError( "You must provide either an email or phone number and a password" ) if response.session: self._save_session(response.session) self._notify_all_subscribers("SIGNED_IN", response.session) return response
(self, credentials: Union[gotrue.types.SignInWithEmailAndPasswordCredentials, gotrue.types.SignInWithPhoneAndPasswordCredentials]) -> gotrue.types.AuthResponse