Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

perf: use inheritance to improve our code base #47

Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion postgrest_py/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,6 @@
from postgrest_py._sync.request_builder import SyncQueryRequestBuilder # noqa: F401
from postgrest_py._sync.request_builder import SyncRequestBuilder # noqa: F401
from postgrest_py._sync.request_builder import SyncSelectRequestBuilder # noqa: F401
from postgrest_py.config import DEFAULT_POSTGREST_CLIENT_HEADERS # noqa: F401
leynier marked this conversation as resolved.
Show resolved Hide resolved
from postgrest_py.base_client import DEFAULT_POSTGREST_CLIENT_HEADERS # noqa: F401
from postgrest_py.deprecated_client import Client, PostgrestClient # noqa: F401
from postgrest_py.deprecated_get_request_builder import GetRequestBuilder # noqa: F401
65 changes: 21 additions & 44 deletions postgrest_py/_async/client.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,19 @@
from typing import Dict, Optional, Union
from typing import Dict, cast

from deprecation import deprecated
from httpx import BasicAuth, Response
from httpx import Response

from postgrest_py.__version__ import __version__
from postgrest_py.config import DEFAULT_POSTGREST_CLIENT_HEADERS
from postgrest_py.base_client import (
DEFAULT_POSTGREST_CLIENT_HEADERS,
BasePostgrestClient,
)
from postgrest_py.utils import AsyncClient

from .request_builder import AsyncRequestBuilder


class AsyncPostgrestClient:
class AsyncPostgrestClient(BasePostgrestClient):
"""PostgREST client."""

def __init__(
Expand All @@ -20,60 +23,34 @@ def __init__(
schema: str = "public",
headers: Dict[str, str] = DEFAULT_POSTGREST_CLIENT_HEADERS,
) -> None:
headers = {
**headers,
"Accept-Profile": schema,
"Content-Profile": schema,
}
self.session = AsyncClient(base_url=base_url, headers=headers)
super().__init__(base_url, schema=schema, headers=headers)
leynier marked this conversation as resolved.
Show resolved Hide resolved

async def __aenter__(self):
def create_session(
self,
base_url: str,
headers: Dict[str, str],
) -> AsyncClient:
return AsyncClient(base_url=base_url, headers=headers)

async def __aenter__(self) -> "AsyncPostgrestClient":
return self

async def __aexit__(self, exc_type, exc, tb) -> None:
await self.aclose()

async def aclose(self) -> None:
await self.session.aclose()

def auth(
self,
token: Optional[str],
*,
username: Union[str, bytes, None] = None,
password: Union[str, bytes] = "",
):
"""
Authenticate the client with either bearer token or basic authentication.

Raise `ValueError` if neither authentication scheme is provided.
Bearer token is preferred if both ones are provided.
"""
if token:
self.session.headers["Authorization"] = f"Bearer {token}"
elif username:
self.session.auth = BasicAuth(username, password)
else:
raise ValueError(
"Neither bearer token or basic authentication scheme is provided"
)
return self

def schema(self, schema: str):
"""Switch to another schema."""
self.session.headers.update({"Accept-Profile": schema, "Content-Profile": schema})
return self
await cast(AsyncClient, self.session).aclose()
leynier marked this conversation as resolved.
Show resolved Hide resolved

def from_(self, table: str) -> AsyncRequestBuilder:
"""Perform a table operation."""
return AsyncRequestBuilder(self.session, f"/{table}")
return AsyncRequestBuilder(cast(AsyncClient, self.session), f"/{table}")
leynier marked this conversation as resolved.
Show resolved Hide resolved

@deprecated("0.2.0", "1.0.0", __version__, "Use PostgrestClient.from_() instead")
@deprecated("0.2.0", "1.0.0", __version__, "Use self.from_() instead")
def from_table(self, table: str) -> AsyncRequestBuilder:
"""Alias to Self.from_()."""
"""Alias to self.from_()."""
return self.from_(table)

async def rpc(self, func: str, params: dict) -> Response:
"""Perform a stored procedure call."""
path = f"/rpc/{func}"
return await self.session.post(path, json=params)
return await cast(AsyncClient, self.session).post(path, json=params)
leynier marked this conversation as resolved.
Show resolved Hide resolved
Loading