目录

windows中部署supabase与测试

windows中部署supabase与测试

Supabase 介绍

Supabase 是一个开源的 Firebase 替代品,提供基于 PostgreSQL 数据库的后端即服务(BaaS)解决方案。

核心特性:

🔧 主要组件

  • PostgreSQL 数据库 - 完全功能的关系型数据库
  • 身份认证 - 完整的用户管理系统
  • 即时 API - 自动生成 RESTful API
  • 实时订阅 - 数据库变更的实时监听
  • 存储 - 文件存储和管理
  • Edge Functions - 服务器端函数

🚀 技术优势

  • 开源 - 可自行部署,避免供应商锁定
  • PostgreSQL 强大功能 - 支持 SQL、触发器、存储过程等
  • 自动生成 API - 无需手动编写 CRUD 接口
  • 实时能力 - 内置 WebSocket 支持
  • 扩展性强 - 基于成熟的 PostgreSQL 生态

🔄 与 Firebase 对比

  • 使用 SQL 而非 NoSQL
  • 更强大的查询能力
  • 更好的数据关系处理
  • 开源且可自托管

🎯 适用场景

  • 需要快速原型的项目
  • 实时应用(聊天、协作工具)
  • 需要复杂查询的应用程序
  • 希望避免供应商锁定的项目

Supabase 让开发者能够快速构建后端服务,同时保持对数据的完全控制和灵活性。

部署supabase

# 获取源代码
git clone --depth 1 https://github.com/supabase/supabase

# 创建新的Supabase项目目录
mkdir supabase-project

# 目录结构应如下所示:
# .
# ├── supabase
# └── supabase-project

# 将compose文件复制到您的项目中
# cp -rf supabase/docker/* supabase-project ## Linux系统命令
Copy-Item -Path supabase/docker/* -Destination supabase-project -Recurse -Force
# 复制环境变量示例文件
cp supabase/docker/.env.example supabase-project/.env

# 切换到项目目录
cd supabase-project

# 拉取最新的Docker镜像
docker compose pull

# 启动所有服务(后台模式)
docker compose up -d

https://i-blog.csdnimg.cn/direct/085f50950a3b4710bd1017a6a8e60b03.png

https://i-blog.csdnimg.cn/direct/23027c1cb6344da18c5ffc759b3173e9.png

登录

您可以通过8000端口上的API网关访问Supabase Studio。例如:http://<您的IP地址>:8000,若在本地运行Docker则可使用localhost:8000。

系统将提示您输入用户名和密码。默认登录凭证为:

用户名:supabase
密码:this_password_is_insecure_and_should_be_updated

创建表

CREATE TABLE users_example (
    id SERIAL PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    email VARCHAR(100) UNIQUE NOT NULL,
    created_at TIMESTAMP DEFAULT NOW()
);

https://i-blog.csdnimg.cn/direct/be94a525c9cb453c94282ee535961a19.png

python测试

1、requirements.txt文件

# Supabase Python 客户端依赖

# Supabase Python 客户端
supabase

# 环境变量管理
python-dotenv

# HTTP 请求库(supabase 的依赖)
httpx

# PostgreSQL 适配器(可选,用于直接数据库连接)
psycopg2-binary

# 异步支持(可选)
asyncio

# JSON 处理(通常已内置,但确保兼容性)
ujson

2、环境配置:

uv init
uv venv --python 3.12
.\.venv\Scripts\activate
uv pip install -r .\requirements.txt

3、Supabase Python 客户端示例文件

"""
Supabase Python 客户端示例
这个脚本演示如何使用 Python 连接和操作 Supabase 数据库
"""

import os
from supabase import create_client, Client
from dotenv import load_dotenv

# 加载环境变量
load_dotenv()

class SupabaseClient:
    def __init__(self):
        """初始化 Supabase 客户端"""
        # 从环境变量获取配置
        self.url = os.getenv('SUPABASE_PUBLIC_URL', 'http://localhost:8000')
        self.anon_key = os.getenv('ANON_KEY')
        self.service_role_key = os.getenv('SERVICE_ROLE_KEY')
        if not self.anon_key:
            raise ValueError("ANON_KEY 环境变量未设置")
        
        # 创建客户端(使用匿名密钥进行一般操作)
        self.supabase: Client = create_client(self.url, self.anon_key)
        
        # 创建服务角色客户端(用于管理员操作)
        if self.service_role_key:
            self.admin_client: Client = create_client(self.url, self.service_role_key)
        else:
            self.admin_client = None
    
    def test_connection(self):
        """测试连接:先建表,再查询"""
        try:
            response = self.supabase.table("users_example").select("*").limit(1).execute()
            print(f"✅ 连接成功!示例数据: {response.data}")
            return True
        except Exception as e:
            print(f"❌ 连接失败: {e}")
            return False
    
    def create_table_example(self):
        """创建示例表"""
        try:
            # 首先检查表是否已存在
            try:
                response = self.supabase.table('users_example').select('*').limit(1).execute()
                print("✅ 表 'users_example' 已存在")
                return True
            except:
                # 表不存在,需要创建
                print("⚠️  表 'users_example' 不存在")
                print("请在 Supabase Studio (http://localhost:3000) 中手动创建表:")
                print("""
CREATE TABLE users_example (
    id SERIAL PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    email VARCHAR(100) UNIQUE NOT NULL,
    created_at TIMESTAMP DEFAULT NOW()
);
                """)
                
                # 等待用户创建表后再次检查
                input("创建表后按 Enter 键继续...")
                
                try:
                    response = self.supabase.table('users_example').select('*').limit(1).execute()
                    print("✅ 表创建成功!")
                    return True
                except:
                    print("❌ 表仍然不存在,跳过数据操作")
                    return False
                    
        except Exception as e:
            print(f"❌ 检查表失败: {e}")
            return False
    
    def insert_data_example(self, name: str, email: str):
        """插入数据示例"""
        try:
            data = {
                "name": name,
                "email": email
            }
            
            response = self.supabase.table('users_example').insert(data).execute()
            print(f"✅ 数据插入成功: {response.data}")
            return response.data
        except Exception as e:
            print(f"❌ 插入数据失败: {e}")
            return None
    
    def select_data_example(self):
        """查询数据示例"""
        try:
            response = self.supabase.table('users_example').select("*").execute()
            print(f"✅ 查询成功,找到 {len(response.data)} 条记录:")
            for record in response.data:
                print(f"  - ID: {record['id']}, 姓名: {record['name']}, 邮箱: {record['email']}")
            return response.data
        except Exception as e:
            print(f"❌ 查询失败: {e}")
            return None
    
    def update_data_example(self, user_id: int, new_name: str):
        """更新数据示例"""
        try:
            response = self.supabase.table('users_example').update(
                {"name": new_name}
            ).eq('id', user_id).execute()
            print(f"✅ 更新成功: {response.data}")
            return response.data
        except Exception as e:
            print(f"❌ 更新失败: {e}")
            return None
    
    def delete_data_example(self, user_id: int):
        """删除数据示例"""
        try:
            response = self.supabase.table('users_example').delete().eq('id', user_id).execute()
            print(f"✅ 删除成功: {response.data}")
            return response.data
        except Exception as e:
            print(f"❌ 删除失败: {e}")
            return None

def main():
    """主函数 - 演示基本操作"""
    print("🚀 Supabase Python 客户端示例")
    print("=" * 50)
    
    try:
        # 初始化客户端
        client = SupabaseClient()
        
        # 测试连接
        print("\n1. 测试连接...")
        if not client.test_connection():
            return
        
        # 创建示例表
        print("\n2. 创建示例表...")
        client.create_table_example()
        
        # 插入数据
        print("\n3. 插入示例数据...")
        client.insert_data_example("张三", "zhangsan@example.com")
        client.insert_data_example("李四", "lisi@example.com")
        
        # 查询数据
        print("\n4. 查询所有数据...")
        client.select_data_example()
        
        # 更新数据
        print("\n5. 更新数据...")
        client.update_data_example(1, "张三(已更新)")
        
        # 再次查询
        print("\n6. 查询更新后的数据...")
        client.select_data_example()
        
        print("\n✅ 所有操作完成!")
        
    except Exception as e:
        print(f"❌ 程序执行出错: {e}")

if __name__ == "__main__":
    main()

输出
https://i-blog.csdnimg.cn/direct/593778da2aa84933af39a203348cf158.png