Skip to content

Commit

Permalink
perf: use inheritance to improve our code base (#47)
Browse files Browse the repository at this point in the history
* fix: interpolations erros and other things reported by sourcery-ai

* feat: use inheritance to improve the code base

* fix: sourcery refactored

* chore: update pre commit rules

* fix: remove noqa F401 comments

* fix: remove duplicate and unused imports in base_client.py

* feat: use enum instance literals in base_request_builder.py

* pref: cast session only once in __init__

* pref: remove unnecesary cast

* tests: update tests

* chore: generate sync code

* feat: add support for upsert

* Rm cast from rpc in async client

* Rm cast from rpc in sync client

* Add table method as an alias for from_

Co-authored-by: dreinon <67071425+dreinon@users.noreply.github.com>
Co-authored-by: Dani Reinón <dani@dribo.es>
  • Loading branch information
3 people committed Dec 25, 2021
1 parent 3934fb2 commit 315f596
Show file tree
Hide file tree
Showing 13 changed files with 692 additions and 530 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -130,3 +130,6 @@ dmypy.json

# PyCharm
.idea/

# Visual Studio Code
.vscode/
81 changes: 48 additions & 33 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,37 +1,52 @@
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.0.1
hooks:
- id: trailing-whitespace
- id: check-added-large-files
- id: end-of-file-fixer
- id: mixed-line-ending
args: ["--fix=lf"]
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.0.1
hooks:
- id: trailing-whitespace
- id: check-added-large-files
- id: end-of-file-fixer
- id: mixed-line-ending
args: ["--fix=lf"]

- repo: https://github.com/pre-commit/mirrors-isort
rev: v5.8.0
hooks:
- id: isort
args:
[
"--multi-line=3",
"--trailing-comma",
"--force-grid-wrap=0",
"--use-parentheses",
"--line-width=88",
]
- repo: https://github.com/pycqa/isort
rev: 5.10.1
hooks:
- id: isort
args:
[
"--profile",
"black",
"--multi-line=3",
"--trailing-comma",
"--force-grid-wrap=0",
"--use-parentheses",
"--line-width=88",
]

- repo: https://github.com/humitos/mirrors-autoflake.git
rev: v1.1
hooks:
- id: autoflake
args: ["--in-place", "--remove-all-unused-imports"]
- repo: https://github.com/myint/autoflake.git
rev: v1.4
hooks:
- id: autoflake
args:
[
"--in-place",
"--remove-all-unused-imports",
"--ignore-init-module-imports",
]

- repo: https://github.com/psf/black
rev: 21.9b0
hooks:
- id: black
- repo: https://github.com/pre-commit/mirrors-prettier
rev: v2.4.1
hooks:
- id: prettier
- repo: https://github.com/ambv/black
rev: 21.11b1
hooks:
- id: black

- repo: https://github.com/asottile/pyupgrade
rev: v2.29.1
hooks:
- id: pyupgrade
args: ["--py37-plus", "--keep-runtime-typing"]

- repo: https://github.com/commitizen-tools/commitizen
rev: v2.20.0
hooks:
- id: commitizen
stages: [commit-msg]
30 changes: 17 additions & 13 deletions postgrest_py/__init__.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
from postgrest_py._async.client import AsyncPostgrestClient # noqa: F401
from postgrest_py._async.request_builder import AsyncFilterRequestBuilder # noqa: F401
from postgrest_py._async.request_builder import AsyncQueryRequestBuilder # noqa: F401
from postgrest_py._async.request_builder import AsyncRequestBuilder # noqa: F401
from postgrest_py._async.request_builder import AsyncSelectRequestBuilder # noqa: F401
from postgrest_py._sync.client import SyncPostgrestClient # noqa: F401
from postgrest_py._sync.request_builder import SyncFilterRequestBuilder # noqa: F401
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
from postgrest_py.deprecated_client import Client, PostgrestClient # noqa: F401
from postgrest_py.deprecated_get_request_builder import GetRequestBuilder # noqa: F401
from postgrest_py._async.client import AsyncPostgrestClient
from postgrest_py._async.request_builder import (
AsyncFilterRequestBuilder,
AsyncQueryRequestBuilder,
AsyncRequestBuilder,
AsyncSelectRequestBuilder,
)
from postgrest_py._sync.client import SyncPostgrestClient
from postgrest_py._sync.request_builder import (
SyncFilterRequestBuilder,
SyncQueryRequestBuilder,
SyncRequestBuilder,
SyncSelectRequestBuilder,
)
from postgrest_py.base_client import DEFAULT_POSTGREST_CLIENT_HEADERS
from postgrest_py.deprecated_client import Client, PostgrestClient
from postgrest_py.deprecated_get_request_builder import GetRequestBuilder
64 changes: 23 additions & 41 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,14 +23,17 @@ 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)
BasePostgrestClient.__init__(self, base_url, schema=schema, headers=headers)
self.session = cast(AsyncClient, self.session)

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:
Expand All @@ -36,41 +42,17 @@ async def __aexit__(self, exc_type, exc, tb) -> None:
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

def from_(self, table: str) -> AsyncRequestBuilder:
"""Perform a table operation."""
return AsyncRequestBuilder(self.session, f"/{table}")

def table(self, table: str) -> AsyncRequestBuilder:
"""Alias to self.from_()."""
return self.from_(table)

@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:
Expand Down
Loading

0 comments on commit 315f596

Please sign in to comment.