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

Add support for synchronous RPC calls #54

Closed
aantn opened this issue Oct 2, 2021 · 2 comments · Fixed by #101
Closed

Add support for synchronous RPC calls #54

aantn opened this issue Oct 2, 2021 · 2 comments · Fixed by #101
Labels
enhancement New feature or request good first issue Good for newcomers hacktoberfest Hacktoberfest 2022

Comments

@aantn
Copy link

aantn commented Oct 2, 2021

RPC calls are asynchronous as _execute_monkey_patch doesn't effect them. This is annoying because all the other calls in supabase-py are synchronous.

@J0 J0 added hacktoberfest Hacktoberfest 2022 enhancement New feature or request good first issue Good for newcomers labels Oct 2, 2021
@J0
Copy link
Collaborator

J0 commented Oct 2, 2021

Hey @aantn,

Thanks for the feedback! We'll make the necessary adjustments -- if anyone wishes to work on this issue it is up for grabs as part of Hacktoberfest.

-JL

@aantn
Copy link
Author

aantn commented Oct 2, 2021

My pleasure. I have this working (as well as other Supabase-py features) using the following hack in my app's code:

class MyAuthClient(SupabaseAuthClient):
    def _set_timeout(*args, **kwargs):
        """Set timer task"""
        # _set_timeout isn't implemented in gotrue client. it's required for the jwt refresh token timer task
        # https://github.com/supabase/gotrue-py/blob/49c092e3a4a6d7bb5e1c08067a4c42cc2f74b5cc/gotrue/client.py#L242
        # callback, timeout_ms
        threading.Timer(args[2] / 1000, args[1]).start()


class MyClient(Client):
    def _get_auth_headers(self) -> Dict[str, str]:
        auth = getattr(self, "auth", None)
        session = auth.current_session if auth else None
        if session and session["access_token"]:
            access_token = auth.session()["access_token"]
        else:
            access_token = self.supabase_key

        headers: Dict[str, str] = {
            "apiKey": self.supabase_key,
            "Authorization": f"Bearer {access_token}",
        }
        return headers

    @staticmethod
    def _init_supabase_auth_client(
        auth_url: str,
        supabase_key: str,
        detect_session_in_url: bool,
        auto_refresh_token: bool,
        persist_session: bool,
        local_storage: Dict[str, Any],
        headers: Dict[str, str],
    ) -> MyAuthClient:
        """Creates a wrapped instance of the GoTrue Client."""
        return MyAuthClient(
            url=auth_url,
            auto_refresh_token=auto_refresh_token,
            detect_session_in_url=detect_session_in_url,
            persist_session=persist_session,
            local_storage=local_storage,
            headers=headers,
        )

    def rpc(self, fn, params):
        """Similar to _execute_monkey_patch in supabase-py - we make the async rpc call sync"""
        path = f"rpc/{fn}"
        url: str = str(self.postgrest.session.base_url).rstrip("/")
        query: str = str(self.postgrest.session.params)
        logging.warning(f"doing call {url}/{path}?{query}, with headers={self.postgrest.session.headers} and whole session is {self.postgrest.session}")
        response = requests.post(f"{url}/{path}?{query}", headers=dict(self.postgrest.session.headers) | self._get_auth_headers(), json=params)
        return {
            "data": response.json(),
            "status_code": response.status_code,
        }

Feel free to cleanup and re-use

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request good first issue Good for newcomers hacktoberfest Hacktoberfest 2022
Projects
None yet
2 participants