eheguy commited on
Commit
deebf60
·
1 Parent(s): bc5f44d

Fix pool disconnect issues: recreate Supabase client session per request

Browse files
Files changed (1) hide show
  1. usage.py +22 -13
usage.py CHANGED
@@ -8,24 +8,33 @@ PLAN_LIMITS = {
8
  "pro": float("inf"), # unlimited
9
  }
10
 
11
- _supabase_client = None
12
-
13
  def get_supabase() -> Client:
14
- global _supabase_client
15
- if _supabase_client is None:
16
- url = os.getenv("SUPABASE_URL")
17
- key = os.getenv("SUPABASE_SERVICE_ROLE_KEY") or os.getenv("SUPABASE_SERVICE_KEY")
18
- if not url or not key:
19
- raise ValueError("Supabase credentials not set.")
20
- _supabase_client = create_client(url, key)
21
- return _supabase_client
22
 
 
23
 
24
  def get_user_profile(user_id: str) -> dict:
25
- """Fetch user profile from Supabase."""
26
  client = get_supabase()
27
- result = client.table("profiles").select("*").eq("id", user_id).single().execute()
28
- return result.data
 
 
 
 
 
 
 
 
 
 
 
 
29
 
30
 
31
  def check_usage_limit(user_id: str) -> dict:
 
8
  "pro": float("inf"), # unlimited
9
  }
10
 
 
 
11
  def get_supabase() -> Client:
12
+ url = os.getenv("SUPABASE_URL")
13
+ key = os.getenv("SUPABASE_SERVICE_ROLE_KEY") or os.getenv("SUPABASE_SERVICE_KEY")
14
+ if not url or not key:
15
+ raise ValueError("Supabase credentials not set.")
16
+ return create_client(url, key)
17
+
 
 
18
 
19
+ from postgrest.exceptions import APIError
20
 
21
  def get_user_profile(user_id: str) -> dict:
22
+ """Fetch user profile from Supabase, creating a default one if it doesn't exist."""
23
  client = get_supabase()
24
+ try:
25
+ result = client.table("profiles").select("*").eq("id", user_id).single().execute()
26
+ return result.data
27
+ except APIError as e:
28
+ if e.code == "PGRST116":
29
+ new_profile = {
30
+ "id": user_id,
31
+ "plan": "free",
32
+ "humanization_count": 0,
33
+ "razorpay_subscription_id": None
34
+ }
35
+ client.table("profiles").insert(new_profile).execute()
36
+ return new_profile
37
+ raise e
38
 
39
 
40
  def check_usage_limit(user_id: str) -> dict: