Skip to content

Commit 97f9162

Browse files
committed
cleaning up a little and making more pythonic
1 parent 7edf954 commit 97f9162

File tree

7 files changed

+75
-90
lines changed

7 files changed

+75
-90
lines changed

Diff for: supabase_py/__init__.py

+5-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
1-
from lib import supabase_auth_client, supabase_query_builder, supabase_realtime_client
1+
# Retain module level imports for structured imports in tests etc.
2+
from . import lib
3+
from . import client
4+
# Open up the client as an easy import.
25
from client import Client
36

47

5-
__VERSION__ = "0.0.1"
8+
__version__ = "0.0.1"

Diff for: supabase_py/client.py

+43-69
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
11
import gotrue
22

33
from postgrest_py import PostgrestClient
4-
from .lib.supabase_auth_client import SupabaseAuthClient
5-
from .lib.supabase_realtime_client import SupabaseRealtimeClient
6-
from .lib.supabase_query_builder import SupabaseQueryBuilder
7-
from typing import Optional
4+
from lib.auth_client import SupabaseAuthClient
5+
from lib.realtime_client import SupabaseRealtimeClient
6+
from lib.query_builder import SupabaseQueryBuilder
7+
8+
from typing import Any, Dict
89

910

1011
DEFAULT_OPTIONS = {
@@ -18,56 +19,41 @@
1819

1920
class Client:
2021
def __init__(
21-
self, supabaseUrl: str, supabaseKey: str, options: Optional[dict] = {}
22+
self, supabase_url: str, supabase_key: str, **options,
2223
):
23-
"""
24-
Initialize a Supabase Client
24+
"""Instanciate the client.
25+
2526
Parameters
2627
----------
27-
SupabaseUrl
28-
URL of the Supabase instance that we are acting on
29-
SupabaseKey
30-
API key for the Supabase instance that we are acting on
31-
Options
32-
Any other settings that we wish to override
33-
34-
Returns
35-
None
36-
-------
37-
"""
38-
if not supabaseUrl:
39-
raise Exception("supabaseUrl is required")
40-
if not supabaseKey:
41-
raise Exception("supabaseKey is required")
42-
43-
settings = {**DEFAULT_OPTIONS, **options}
44-
self.restUrl = f"{supabaseUrl}/rest/v1"
45-
self.realtimeUrl = f"{supabaseUrl}/realtime/v1".replace("http", "ws")
46-
self.authUrl = f"{supabaseUrl}/auth/v1"
28+
supabase_url: str
29+
The URL to the Supabase instance that should be connected to.
30+
supabase_key: str
31+
The API key to the Supabase instance that should be connected to.
32+
**options
33+
Any extra settings to be optionally specified - also see the
34+
`DEFAULT_OPTIONS` dict.
35+
"""
36+
if not supabase_url:
37+
raise Exception("supabase_url is required")
38+
if not supabase_key:
39+
raise Exception("supabase_key is required")
40+
settings: Dict[str, Any] = {**DEFAULT_OPTIONS, **options}
41+
self.restUrl = f"{supabase_url}/rest/v1"
42+
self.realtimeUrl = f"{supabase_url}/realtime/v1".replace("http", "ws")
43+
self.authUrl = f"{supabase_url}/auth/v1"
4744
self.schema = settings["schema"]
48-
self.supabaseUrl = supabaseUrl
49-
self.supabaseKey = supabaseKey
50-
self.auth = self._initSupabaseAuthClient(*settings)
51-
# TODO: Fix this once Realtime-py is working
52-
# self.realtime = self._initRealtimeClient()
45+
self.supabaseUrl = supabase_url
46+
self.supabaseKey = supabase_key
47+
self.auth = self._init_supabase_auth_client(*settings)
48+
self.realtime = self._init_realtime_client()
5349

5450
def _from(self, table: str):
55-
"""
56-
Perform a table operation on a given table
57-
Parameters
58-
----------
59-
table
60-
Name of table to execute operations on
61-
Returns
62-
-------
63-
SupabaseQueryBuilder
64-
Wrapper for Postgrest-py client which we can perform operations(e.g. select/update) with
65-
"""
66-
url = f"{self.restUrl}/{table}"
51+
"""Perform a table operation."""
52+
url = f"{self.rest_url}/{table}"
6753
return SupabaseQueryBuilder(
6854
url,
6955
{
70-
"headers": self._getAuthHeaders(),
56+
"headers": self._get_auth_headers(),
7157
"schema": self.schema,
7258
"realtime": self.realtime,
7359
},
@@ -95,22 +81,19 @@ def rpc(self, fn, params):
9581
rest = self._initPostgrestClient()
9682
return rest.rpc(fn, params)
9783

98-
# TODO: Fix this segment after realtime-py is working
99-
# def removeSubscription(self, subscription):
10084
# async def remove_subscription_helper(resolve):
10185
# try:
102-
# await self._closeSubscription(subscription)
103-
# openSubscriptions = len(self.getSubscriptions())
104-
# if not openSubscriptions:
86+
# await self._close_subscription(subscription)
87+
# open_subscriptions = len(self.get_subscriptions())
88+
# if not open_subscriptions:
10589
# error = await self.realtime.disconnect()
10690
# if error:
107-
# return {"error": None, "data": { openSubscriptions}}
108-
# except Error as e:
109-
# return {error}
110-
91+
# return {"error": None, "data": { open_subscriptions}}
92+
# except Exception as e:
93+
# raise e
11194
# return remove_subscription_helper(subscription)
11295

113-
async def _closeSubscription(self, subscription):
96+
async def _close_subscription(self, subscription):
11497
"""
11598
Close a given subscription
11699
@@ -122,19 +105,19 @@ async def _closeSubscription(self, subscription):
122105
if not subscription.closed:
123106
await self._closeChannel(subscription)
124107

125-
def getSubscriptions(self):
108+
def get_subscriptions(self):
126109
"""
127110
Return all channels the the client is subscribed to.
128111
"""
129112
return self.realtime.channels
130113

131-
def _initRealtimeClient(self):
114+
def _init_realtime_client(self):
132115
"""
133116
Private method for creating an instance of the realtime-py client.
134117
"""
135118
return RealtimeClient(self.realtimeUrl, {"params": {apikey: self.supabaseKey}})
136119

137-
def _initSupabaseAuthClient(
120+
def _init_supabase_auth_client(
138121
self,
139122
schema,
140123
autoRefreshToken,
@@ -157,13 +140,13 @@ def _initSupabaseAuthClient(
157140
},
158141
)
159142

160-
def _initPostgrestClient(self):
143+
def _init_postgrest_client(self):
161144
"""
162145
Private helper method for creating a wrapped instance of the Postgrest client.
163146
"""
164147
return PostgrestClient(self.restUrl)
165148

166-
def _getAuthHeaders(self):
149+
def _get_auth_headers(self):
167150
"""
168151
Helper method to get auth headers
169152
"""
@@ -172,12 +155,3 @@ def _getAuthHeaders(self):
172155
headers["apiKey"] = self.supabaseKey
173156
headers["Authorization"] = f"Bearer {self.supabaseKey}"
174157
return headers
175-
176-
# TODO: Fix this segment after realtime-py is working
177-
# def closeSubscription(self):
178-
# if not subscription.closed:
179-
# await self._closeChannel(subscription)
180-
181-
# def _closeChannel(self, subscription):
182-
# async def _closeChannelHelper():
183-
# subscription.unsubscribe().on('OK')

Diff for: supabase_py/lib/__init__.py

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
from . import auth_client
2+
from . import query_builder
3+
from . import realtime_client

Diff for: supabase_py/lib/auth_client.py

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import gotrue
2+
3+
from typing import Any, Dict, Optional
4+
5+
# TODO(fedden): What are the correct types here?
6+
class SupabaseAuthClient(gotrue.Client):
7+
"""SupabaseAuthClient"""
8+
9+
def __init__(
10+
self,
11+
authURL: str,
12+
detectSessionInUrl: bool = False,
13+
autoRefreshToken: bool = False,
14+
persistSession: bool = False,
15+
localStorage: Optional[Dict[str, Any]] = None,
16+
headers: Optional[Any] = None,
17+
):
18+
"""Instanciate SupabaseAuthClient instance."""
19+
super().__init__(authURL)
20+
self.headers = headers
21+
self.detectSessionInUrl = detectSessionInUrl
22+
self.autoRefreshToken = autoRefreshToken
23+
self.persistSession = persistSession
24+
self.localStorage = localStorage
File renamed without changes.
File renamed without changes.

Diff for: supabase_py/lib/supabase_auth_client.py

-19
This file was deleted.

0 commit comments

Comments
 (0)