Storage / Supabase

Storage Menager

This is detailed, didactic documentation for the Supabase Storage integration module. The code was designed following Object-Oriented Programming (OOP) principles to make maintenance and connection reuse easier.

On this page

    #1. Overview

    The module is made up of two main classes that work together to abstract the complexity of the Supabase API. The central idea is to separate the connection configuration (infrastructure) from file handling (business logic).

    • SupabaseConnection: Ensures the connection to the server is established correctly using environment variables.
    • StorageManager: Offers a simplified interface to upload, delete and retrieve file links inside a specific "bucket" (container/repository).

    #2. Execution Flow

    To understand how the classes interact, picture the following flow:

    1. Environment Loading: The script reads the .env file to capture the project URL and Key.
    2. Instantiation: When you create a StorageManager, it checks whether you already have a connection. If not, it calls SupabaseConnection automatically.
    3. Bucket Access: The client connects to the specific bucket given at the start.
    4. Operation: You call simple methods (such as upload_bytes), and the class handles the internal logic of the official Supabase library.

    #3. Methods Summary

    MethodClassShort Description
    __init__SupabaseConnectionValidates credentials and creates the Client client.
    __init__StorageManagerSets the target bucket and ensures an active client exists.
    upload_bytesStorageManagerUploads binary files (bytes) to the storage.
    delete_filesStorageManagerRemoves a list of files at once.
    get_urlStorageManagerGenerates the public link to view the file.

    #4. Architecture and Insights

    • Implicit Singleton vs Dependency Injection: The StorageManager class accepts an optional supabase_client. This is great for unit tests or for reusing a connection already open elsewhere in the system, avoiding unnecessary multiple connections.
    • Error Handling: Using try/except blocks in the write methods (upload/delete) keeps the application from crashing when a network or permission failure occurs.
    • Security: Using dotenv and os.getenv ensures sensitive keys are never exposed directly in the source code.

    #5. Detailed Documentation

    #Class SupabaseConnection

    Description

    Responsible for centralizing authentication. It works as a connection "factory", making sure the Supabase client is properly configured before any operation.

    Arguments

    • It has no direct arguments (it uses .env environment variables).

    Methods

    #1. __init__

    • Description: Locates the SUPABASE_URL and SUPABASE_SECRET_KEY variables, validating them before instantiating the official client.
    • Arguments: None.
    • Returns: None (initializes the self.client attribute).
    • Raises: ValueError if the keys are not found in the environment.
    • Examples:
    conn = SupabaseConnection()
    client = conn.client # Cliente pronto para uso

    #Class StorageManager

    Description

    Encapsulates the bucket handling logic. It is the "front-end" class the developer will use most of the time to manage files.

    Arguments

    • bucket_name (str): The name of the folder/repository in Supabase.
    • supabase_client (Optional[Client]): An existing instance of the Supabase client.

    Methods

    #1. upload_bytes

    • Description: Sends a file to the storage from in-memory data (bytes).
    • Arguments:
      • path_on_storage (str): Path/name of the file at the destination.
      • file_bytes (bytes): The binary content of the file.
      • content_type (str): File type (e.g. image/png).
    • Returns: dict with upload metadata or None on error.
    • Raises: Catches generic exceptions and prints them to the console.
    • Examples:
    manager.upload_bytes("docs/perfil.jpg", foto_bytes, "image/jpeg")

    #2. delete_files

    • Description: Deletes one or more files at the same time.
    • Arguments:
      • paths (List[str]): List of paths (e.g. ["img1.jpg", "img2.jpg"]).
    • Returns: dict with the removal status or None.
    • Raises: Catches network or permission exceptions.
    • Examples:
    manager.delete_files(["velho/foto1.png", "velho/foto2.png"])

    #3. get_url

    • Description: Gets the public web address to access a file.
    • Arguments:
      • path (str): Path of the file inside the bucket.
    • Returns: str containing the full URL.
    • Raises: ValueError if the path is empty.
    • Examples:
    link = manager.get_url("produtos/celular.png")
    print(link) # https://xyz.supabase.co/storage/v1/object/public/...

    Source: src/storage/supabase/storage_menager.py

    Esc
    ↑↓navigate Enteropen