Skip to content

Commit

Permalink
Merge pull request #83 from leynier/feat/unify-http-client-to-be-httpx
Browse files Browse the repository at this point in the history
feat: unify http client to be httpx
  • Loading branch information
dreinon authored Nov 17, 2021
2 parents de2027e + 269dfad commit 55e8f84
Show file tree
Hide file tree
Showing 5 changed files with 36 additions and 32 deletions.
6 changes: 2 additions & 4 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,9 @@ license = "MIT"

[tool.poetry.dependencies]
python = "^3.7.1"
postgrest-py = {git = "https://github.com/supabase-community/postgrest-py.git", rev = "master"}
postgrest-py = {git = "https://github.com/supabase-community/postgrest-py.git", rev = "ba83ba43c6cfba906fbb710d3913e5dc070fdde3"}
realtime-py = "^0.1.2"
gotrue = "0.2.0"
requests = "2.25.1"
requests-toolbelt = "^0.9.1"
gotrue = {git = "https://github.com/supabase-community/gotrue-py.git", rev = "9ba3192dbdccd2f02a4819b52dd6cf51095af7e7"}
httpx = "^0.19.0"

[tool.poetry.dev-dependencies]
Expand Down
4 changes: 2 additions & 2 deletions supabase/lib/auth_client.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Any, Dict, Optional
from typing import Any, Dict

import gotrue

Expand All @@ -12,7 +12,7 @@ def __init__(
detect_session_in_url: bool = False,
auto_refresh_token: bool = False,
persist_session: bool = False,
local_storage: Optional[Dict[str, Any]] = None,
local_storage: Dict[str, Any] = {},
headers: Dict[str, str] = {},
):
"""Instanciate SupabaseAuthClient instance."""
Expand Down
14 changes: 7 additions & 7 deletions supabase/lib/query_builder.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from typing import Any, Dict

import requests
import httpx
from httpx import AsyncClient
from postgrest_py.client import PostgrestClient
from postgrest_py.request_builder import QueryRequestBuilder
Expand All @@ -11,19 +11,19 @@ def _execute_monkey_patch(self) -> Dict[str, Any]:
method: str = self.http_method.lower()
additional_kwargs: Dict[str, Any] = {}
if method == "get":
func = requests.get
func = httpx.get
elif method == "post":
func = requests.post
func = httpx.post
# Additionally requires the json body (e.g on insert, self.json==row).
additional_kwargs = {"json": self.json}
elif method == "put":
func = requests.put
func = httpx.put
additional_kwargs = {"json": self.json}
elif method == "patch":
func = requests.patch
func = httpx.patch
additional_kwargs = {"json": self.json}
elif method == "delete":
func = requests.delete
func = httpx.delete
else:
raise NotImplementedError(f"Method '{method}' not recognised.")
url: str = str(self.session.base_url).rstrip("/")
Expand All @@ -36,7 +36,7 @@ def _execute_monkey_patch(self) -> Dict[str, Any]:


# NOTE(fedden): Here we monkey patch the otherwise async method and use the
# requests module instead. Hopefully cleans things up a little
# httpx sync methods. Hopefully cleans things up a little
# for the user as they are now not bound to async methods.
QueryRequestBuilder.execute = _execute_monkey_patch

Expand Down
38 changes: 20 additions & 18 deletions supabase/lib/storage/storage_file_api.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import requests
from requests import HTTPError
from requests_toolbelt import MultipartEncoder
from typing import Any

import httpx
from httpx import HTTPError


class StorageFileAPI:
Expand Down Expand Up @@ -46,7 +47,7 @@ def create_signed_url(self, path: str, expires_in: int):
"""
try:
_path = self._get_final_path(path)
response = requests.post(
response = httpx.post(
f"{self.url}/object/sign/{_path}",
json={"expiresIn": str(expires_in)},
headers=self.headers,
Expand Down Expand Up @@ -86,7 +87,7 @@ def move(self, from_path: str, to_path: str):
The new file path, including the new file name. For example `folder/image-copy.png`.
"""
try:
response = requests.post(
response = httpx.post(
f"{self.url}/object/move",
json={
"bucketId": self.bucket_id,
Expand All @@ -112,9 +113,10 @@ def remove(self, paths: list):
An array or list of files to be deletes, including the path and file name. For example [`folder/image.png`].
"""
try:
response = requests.delete(
response = httpx.request(
"DELETE",
f"{self.url}/object/{self.bucket_id}",
data={"prefixes": paths},
json={"prefixes": paths},
headers=self.headers,
)
response.raise_for_status()
Expand All @@ -139,9 +141,10 @@ def list(self, path: str = None, options: dict = {}):
body = dict(self.DEFAULT_SEARCH_OPTIONS, **options)
headers = dict(self.headers, **{"Content-Type": "application/json"})
body["prefix"] = path if path else ""

getdata = requests.post(
f"{self.url}/object/list/{self.bucket_id}", json=body, headers=headers
getdata = httpx.post(
f"{self.url}/object/list/{self.bucket_id}",
json=body,
headers=headers,
)
getdata.raise_for_status()
except HTTPError as http_err:
Expand All @@ -160,7 +163,7 @@ def download(self, path: str):
"""
try:
_path = self._get_final_path(path)
response = requests.get(f"{self.url}/object/{_path}", headers=self.headers)
response = httpx.get(f"{self.url}/object/{_path}", headers=self.headers)

except HTTPError as http_err:
print(f"HTTP error occurred: {http_err}") # Python 3.6
Expand All @@ -169,7 +172,7 @@ def download(self, path: str):
else:
return response.content

def upload(self, path: str, file: any, file_options: dict = None):
def upload(self, path: str, file: Any, file_options: dict = None):
"""
Uploads a file to an existing bucket.
Parameters
Expand All @@ -186,14 +189,13 @@ def upload(self, path: str, file: any, file_options: dict = None):
headers = dict(self.headers, **self.DEFAULT_FILE_OPTIONS)
headers.update(file_options)
filename = path.rsplit("/", maxsplit=1)[-1]
files = MultipartEncoder(
fields={"file": (filename, open(file, "rb"), headers["contentType"])}
)
headers["Content-Type"] = files.content_type
files = {"file": (filename, open(file, "rb"), headers["contentType"])}
_path = self._get_final_path(path)
try:
resp = requests.post(
f"{self.url}/object/{_path}", data=files, headers=headers
resp = httpx.post(
f"{self.url}/object/{_path}",
files=files,
headers=headers,
)
except HTTPError as http_err:
print(f"HTTP error occurred: {http_err}") # Python 3.6
Expand Down
6 changes: 5 additions & 1 deletion tests/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,11 @@ def test_client_auth(supabase: Client) -> None:
random_email: str = f"{_random_string(10)}@supamail.com"
random_password: str = _random_string(20)
# Sign up (and sign in).
user = supabase.auth.sign_up(email=random_email, password=random_password)
user = supabase.auth.sign_up(
email=random_email,
password=random_password,
phone=None,
)
_assert_authenticated_user(user)
# Sign out.
supabase.auth.sign_out()
Expand Down

0 comments on commit 55e8f84

Please sign in to comment.