Skip to main content

supabase-py with async synax

Project description

supabase-py-async

License: MIT CI Python Version

Downloads Open Issues Pull Requests Contributors Code Size

async-part of supabase-py Python client for Supabase-py

Installation

We recommend activating your virtual environment. For example, we like poetry and conda!

PyPi installation

Install the package (for > Python 3.9):

# with pip
pip install supabase-py-async
# with poetry (recommended)
poetry add supabase-py-async

Local installation

You can also install locally after cloning this repo. Install Development mode with pip install -e, which makes it so when you edit the source code the changes will be reflected in your python module.

Usage

Set your Supabase environment variables in a dotenv file, or using the shell:

export SUPABASE_URL="my-url-to-my-awesome-supabase-instance"
export SUPABASE_KEY="my-supa-dupa-secret-supabase-api-key"

init the client in fastapi lifespan event

import os
from contextlib import asynccontextmanager
from dotenv import load_dotenv
from fastapi import FastAPI
from supabase_py_async import create_client
from supabase_py_async.lib.client_options import ClientOptions
client = None
@asynccontextmanager
async def lifespan(app: FastAPI):
    """ life span events"""
    identify_worker = None
    try:
        # start client
        load_dotenv()
        url: str = os.getenv("SUPABASE_URL")
        key: str = os.getenv("SUPABASE_KEY")
        client = await create_client(url, key, options=ClientOptions(
            postgrest_client_timeout=10, storage_client_timeout=10))
        yield
    finally:
        pass

Use the supabase client to interface with your database.

Authenticate

async def authenticate(email: str, password: str):
    """ authenticate user """
     # Create a random user login email and password.
    random_email: str = "3hf82fijf92@supamail.com"
    random_password: str = "fqj13bnf2hiu23h"
    user = await client.auth.sign_in(email=email, password=password)

Sign-in

async def sign_in(email: str, password: str):
    """ sign in user """
    # Sign in using the user email and password.
    random_email: str = "3hf82fijf92@supamail.com"
    random_password: str = "fqj13bnf2hiu23h"
    user =  await client.auth.sign_in_with_password({ "email": random_email, "password": random_password })

Insert Data

async def insert_data():
    """ insert data """
    # Insert a new country into the 'countries' table.
    data = await client.table("countries").insert({"name":"Germany"}).execute()
    assert len(data.data) > 0

Select Data

async def select_data():
    """ select data """
    # Select all countries from the 'countries' table.
    data = await client.table("countries").select("*").execute()
    assert len(data.data) > 0

Update Data

async def update_data():
    """ update data """
    # Update the country with id of 1.
    data = await client.table("countries").update({"country": "Indonesia", "capital_city": "Jakarta"}).eq("id", 1).execute()
    assert len(data.data) > 0

Update data with duplicate keys

async def update_data_with_duplicate_keys():
    """ update data with duplicate keys """
    # Update the country with id of 1.
    data = await client.table("countries").update({"country": "Indonesia", "capital_city": "Jakarta"}).eq("id", 1).execute()

Delete Data

async def delete_data():
    """ delete data """
    # Delete the country with id of 1.
    data = await client.table("countries").delete().eq("id", 1).execute()

Call Edge Functions

async def test_func():
  try:
    resp = await client.functions.invoke("hello-world", invoke_options={'body':{}})
    return resp
  except (FunctionsRelayError, FunctionsHttpError) as exception:
    err = exception.to_dict()
    print(err.get("message"))

Download a file from Storage

async def download_file():
    """ download file """
    # Download a file from Storage.
    bucket_name: str = "photos"
    data = await client.storage.from_(bucket_name).download("photo1.png")

Upload a file

async def upload_file():
    """ upload file """
    # Upload a file to Storage.
    bucket_name: str = "photos"
    new_file = getUserFile()
    data = await client.storage.from_(bucket_name).upload("/user1/profile.png", new_file)

Remove a file

async def remove_file():
    """ remove file """
    # Remove a file from Storage.
    bucket_name: str = "photos"
    data = await client.storage.from_(bucket_name).remove(["old_photo.png", "image5.jpg"])

List all files

async def list_files():
    """ list files """
    # List all files in Storage.
    bucket_name: str = "photos"
    data = await client.storage.from_(bucket_name).list()

Move and rename files

async def move_files():
    """ move files """
    # Move and rename files in Storage.
    
    bucket_name: str = "charts"
    old_file_path: str = "generic/graph1.png"
    new_file_path: str = "important/revenue.png"
    
    data = await client.storage.from_(bucket_name).move(old_file_path, new_file_path)

Roadmap

  • Wrap Postgrest-py
    • Add remaining filters
    • Add support for EXPLAIN
    • Add proper error handling
  • Wrap Realtime-py
    • Integrate with Supabase-py
    • Support WALRUS
    • Support broadcast (to check if already supported)
  • Wrap auth-py
    • Remove references to GoTrue-js v1 and do a proper release
    • Test and document common flows (e.g. sign in with OAuth, sign in with OTP)
    • Add MFA methods and SSO methods
    • Add Proof Key for Code Exchange (PKCE) methods. Unlike the JS library, we do not currently plan to support Magic Link (PKCE). Please use the token hash in tandem with verifyOTP instead.
  • Wrap storage-py
    • Support resumable uploads
    • Setup testing environment
    • Document how to properly upload different file types (e.g. jpeg/png and download it)
  • Wrap functions-py

Overall Tasks:

  • Add async support across the entire library
  • Add FastAPI helper library (external to supabase-py)
  • Add django-supabase-postgrest (external to supabase-py)

Contributing

Contributing to the Python libraries are a great way to get involved with the Supabase community. Reach out to us on Discord if you want to get involved.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

supabase_py_async-2.5.0.tar.gz (11.6 kB view details)

Uploaded Source

Built Distribution

supabase_py_async-2.5.0-py3-none-any.whl (11.3 kB view details)

Uploaded Python 3

File details

Details for the file supabase_py_async-2.5.0.tar.gz.

File metadata

  • Download URL: supabase_py_async-2.5.0.tar.gz
  • Upload date:
  • Size: 11.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/4.0.2 CPython/3.11.7

File hashes

Hashes for supabase_py_async-2.5.0.tar.gz
Algorithm Hash digest
SHA256 7f680327154b759840ef1ba0f82f2a486dc4a69f5ba52f76deed3488618a02dd
MD5 06a17add18754c2d6dc2a7d380031801
BLAKE2b-256 6d2f073c351b77446b095ab729d07e65cb1a53a458c6c225cdee988f19914f40

See more details on using hashes here.

File details

Details for the file supabase_py_async-2.5.0-py3-none-any.whl.

File metadata

File hashes

Hashes for supabase_py_async-2.5.0-py3-none-any.whl
Algorithm Hash digest
SHA256 8368131b2391aff12f5eac0a94844d203be3cc17f25b492f36be0449c28ab3a1
MD5 c7b2b5ae4ee98a1443a9b8bc9f9e2ee2
BLAKE2b-256 cb27bf7e1cb39e1fa2f788cbfe973e39455c66f774d26231eb4219e4d77992d4

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page