Skip to main content

Self-hosted Backend as a Service with real-time, events, and SQL power

Project description

๐Ÿš€ CocoBase v2.0 - Self-Hosted Backend as a Service

A production-ready, self-hosted Backend as a Service framework with real-time capabilities, event system, file uploads, and SQL power. Built with FastAPI and SQLModel for modern Python applications.

โœจ What Makes CocoBase Special

  • ๐Ÿ—„๏ธ Real SQL Tables - Traditional database architecture (not JSON storage)
  • ๐ŸŽฏ Event-Driven - 13 lifecycle hooks for custom business logic
  • ๐Ÿ“ก Real-time - WebSocket subscriptions with filtering
  • ๐Ÿ“ File Storage - Built-in with cloud provider support (S3, Cloudinary, B2)
  • ๐Ÿ’ป SQL Editor - Execute queries from the dashboard
  • ๐Ÿ”Œ Extensible - Add custom routes with full database access
  • ๐Ÿ‘ค Built-in Auth - User model with bcrypt password hashing
  • ๐Ÿ“Š Zero Config - Works immediately out of the box
  • ๐ŸŽจ Web Dashboard - Visual interface for everything
  • ๐Ÿ“– Auto Docs - Interactive API documentation

๐ŸŽ‰ New in v2.0

1. Event System

Register callbacks for lifecycle events:

@cocobase.events.on(EventType.AFTER_CREATE, collection="users")
async def on_user_created(ctx: EventContext):
    print(f"New user: {ctx.data['username']}")

2. Real-time WebSocket

Watch collections for live updates:

ws.send(
  JSON.stringify({
    action: "subscribe",
    collection: "users",
    filters: { is_admin: true },
  })
);

3. SQL Editor

Execute raw SQL from the dashboard with query history!

4. File Uploads

Built-in file handling with local/cloud storage.

5. Database Access

Use the database directly in custom routes:

@app.get("/custom")
async def my_route(session: Session = Depends(cocobase.get_db)):
    return session.exec(text("SELECT * FROM users"))

๐Ÿ“ฆ Installation

pip install cocobase

Or from source:

git clone https://github.com/lordace-coder/cocobase_framework.git
cd cocobase
pip install -e .

โšก Quick Start

1. Create app.py

from cocobase import CocoBase

cocobase = CocoBase()
app = cocobase.app

if __name__ == "__main__":
    cocobase.run()

2. Run

python app.py

3. Access


๐ŸŽฏ Core Features

Traditional Database Tables

Each collection is a real SQL table with proper columns and types:

# Create a collection via API
{
  "name": "products",
  "columns": [
    {"name": "id", "type": "integer", "primary_key": true, "auto_increment": true},
    {"name": "name", "type": "string", "required": true},
    {"name": "price", "type": "float"},
    {"name": "in_stock", "type": "boolean", "default": true}
  ]
}

Supported Types: string, integer, float, boolean, datetime, text, json, file, files

Built-in User Model

Ready-to-use authentication with password hashing:

# Create user (password auto-hashed)
POST /collections/users/documents
{
  "username": "john",
  "email": "john@example.com",
  "password": "secret123"
}

Event-Driven Architecture

Hook into document lifecycle:

from cocobase import EventType, EventContext

# Validate before save
@cocobase.events.on(EventType.BEFORE_CREATE, collection="users")
async def validate_user(ctx: EventContext):
    if not ctx.data.get('email'):
        ctx.cancel()  # Prevent creation

# Send notification after save
@cocobase.events.on(EventType.AFTER_CREATE, collection="orders")
async def send_confirmation(ctx: EventContext):
    # Send email, update inventory, etc.
    pass

Available Events:

  • APP_START, APP_SHUTDOWN
  • BEFORE_CREATE, AFTER_CREATE
  • BEFORE_UPDATE, AFTER_UPDATE
  • BEFORE_DELETE, AFTER_DELETE
  • COLLECTION_CREATED, COLLECTION_DELETED
  • FILE_UPLOADED, FILE_DELETED

Real-time Subscriptions

Watch collections with WebSocket:

const ws = new WebSocket("ws://localhost:8000/ws");

// Subscribe to collection
ws.send(
  JSON.stringify({
    action: "subscribe",
    collection: "users",
    filters: {
      age_gte: 18, // Age >= 18
      status: "active",
    },
    events: ["create", "update", "delete"],
  })
);

// Receive updates
ws.onmessage = (event) => {
  const message = JSON.parse(event.data);
  if (message.type === "event") {
    console.log("Update:", message.data);
  }
};

Filter Operators: _eq, _ne, _gt, _gte, _lt, _lte, _contains, _in

File Upload System

Upload files with automatic storage:

# Upload endpoint
POST /files/upload
Content-Type: multipart/form-data

# Collection with file field
{
  "name": "posts",
  "columns": [
    {"name": "id", "type": "integer", "primary_key": true},
    {"name": "title", "type": "string"},
    {"name": "featured_image", "type": "file"},
    {"name": "attachments", "type": "files"}  // Multiple files
  ]
}

Access files at /uploads/filename.jpg

Custom Routes with Database Access

Extend CocoBase with custom endpoints:

from sqlmodel import Session, text
from fastapi import Depends

@app.get("/api/stats")
async def get_stats(session: Session = Depends(cocobase.get_db)):
    """Custom endpoint with direct database access"""
    result = session.execute(text("""
        SELECT COUNT(*) as total_users,
               SUM(CASE WHEN is_admin THEN 1 ELSE 0 END) as admins
        FROM users
    """))
    row = result.first()
    return {"total_users": row[0], "admins": row[1]}

๐Ÿ“š API Endpoints

Collections

GET    /collections                      # List all collections
POST   /collections                      # Create collection
DELETE /collections/{name}               # Delete collection
PATCH  /collections/{name}/add-column    # Add column dynamically

Documents

GET    /collections/{name}/documents           # List documents
POST   /collections/{name}/documents           # Create document
GET    /collections/{name}/documents/{id}      # Get document
PATCH  /collections/{name}/documents/{id}      # Update document
DELETE /collections/{name}/documents/{id}      # Delete document

Files

POST   /files/upload                     # Upload file
POST   /files/upload-multiple            # Upload multiple files
GET    /files/{filename}                 # Get file
DELETE /files/{filename}                 # Delete file

Real-time

WS     /ws                              # WebSocket endpoint
GET    /realtime/stats                  # Connection statistics

SQL

POST   /sql/execute                     # Execute SQL query

๐Ÿ’ก Complete Examples

Example 1: Blog with Events

from cocobase import CocoBase, EventType, EventContext

cocobase = CocoBase()
app = cocobase.app

# Auto-generate slug from title
@cocobase.events.on(EventType.BEFORE_CREATE, collection="posts")
async def generate_slug(ctx: EventContext):
    title = ctx.data.get('title', '')
    ctx.data['slug'] = title.lower().replace(' ', '-')
    ctx.data['view_count'] = 0

# Notify followers
@cocobase.events.on(EventType.AFTER_CREATE, collection="posts")
async def notify_followers(ctx: EventContext):
    # Send notifications to followers
    print(f"New post: {ctx.data['title']}")

# Custom view counter
@app.post("/api/posts/{post_id}/view")
async def increment_views(post_id: int, session: Session = Depends(cocobase.get_db)):
    query = text("UPDATE posts SET view_count = view_count + 1 WHERE id = :id")
    session.execute(query, {"id": post_id})
    session.commit()
    return {"message": "View counted"}

if __name__ == "__main__":
    cocobase.run()

Example 2: Real-time Dashboard

<!DOCTYPE html>
<html>
  <head>
    <title>Live Dashboard</title>
  </head>
  <body>
    <h1>Live User Activity</h1>
    <div id="activity"></div>

    <script>
      const ws = new WebSocket("ws://localhost:8000/ws");

      ws.onopen = () => {
        ws.send(
          JSON.stringify({
            action: "subscribe",
            collection: "users",
            events: ["create", "update"],
          })
        );
      };

      ws.onmessage = (event) => {
        const msg = JSON.parse(event.data);
        if (msg.type === "event") {
          document
            .getElementById("activity")
            .insertAdjacentHTML(
              "afterbegin",
              `<div>${msg.event} in ${msg.collection}: ${JSON.stringify(
                msg.data
              )}</div>`
            );
        }
      };
    </script>
  </body>
</html>

Example 3: Data Validation

@cocobase.events.on(EventType.BEFORE_CREATE, collection="users")
async def validate_user(ctx: EventContext):
    email = ctx.data.get('email', '')

    # Validate email
    if '@' not in email:
        ctx.cancel()
        return

    # Check for duplicates
    with Session(cocobase.engine) as session:
        query = text("SELECT COUNT(*) FROM users WHERE email = :email")
        result = session.execute(query, {"email": email})
        if result.scalar() > 0:
            ctx.cancel()
            print(f"Email already exists: {email}")

๐Ÿ—„๏ธ Database Support

# SQLite (default)
CocoBase(database_url="sqlite:///myapp.db")

# PostgreSQL
CocoBase(database_url="postgresql://user:pass@localhost/mydb")

# MySQL
CocoBase(database_url="mysql+pymysql://user:pass@localhost/mydb")

๐Ÿ”ง Configuration

cocobase = CocoBase(
    database_url="sqlite:///myapp.db",  # Database connection
    dev_mode=True,                      # Development mode
    enable_dashboard=True,              # Enable web dashboard
    upload_dir="uploads"                # File upload directory
)

๐Ÿ“– Documentation


๐ŸŽ“ Learning Resources

  1. Start Here: Read QUICK_REFERENCE.md
  2. Run Example: python example_usage.py
  3. Deep Dive: Read docs/DEVELOPER_GUIDE.md
  4. Build Your App: Use the patterns and extend!

๐Ÿ—๏ธ Architecture

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚              CocoBase v2.0                  โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚  FastAPI + SQLModel + WebSocket + Events   โ”‚
โ”‚                                             โ”‚
โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”   โ”‚
โ”‚  โ”‚ Events  โ”‚  โ”‚Real-timeโ”‚  โ”‚ Storage  โ”‚   โ”‚
โ”‚  โ”‚ System  โ”‚  โ”‚WebSocketโ”‚  โ”‚ Service  โ”‚   โ”‚
โ”‚  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜   โ”‚
โ”‚                                             โ”‚
โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚
โ”‚  โ”‚   Real SQL Tables (Not JSON)          โ”‚ โ”‚
โ”‚  โ”‚   users | posts | products | ...     โ”‚ โ”‚
โ”‚  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

๐Ÿ” Security

โš ๏ธ For Production:

  1. Add authentication (JWT/OAuth2)
  2. Enable HTTPS
  3. Configure CORS properly
  4. Add rate limiting
  5. Validate all inputs
  6. Use strong passwords
  7. Keep dependencies updated

๐Ÿš€ Deployment

Using Uvicorn

uvicorn app:app --host 0.0.0.0 --port 8000 --workers 4

Using Docker

FROM python:3.12
WORKDIR /app
COPY . .
RUN pip install -r requirements.txt
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000"]

๐Ÿค Contributing

Contributions welcome! Areas to improve:

  • Additional storage providers (AWS S3, Azure Blob, etc.)
  • Authentication providers (OAuth2, JWT, etc.)
  • More event types
  • Performance optimizations
  • UI enhancements

๐Ÿ“„ License

MIT License - Free for personal and commercial use!


๐ŸŽ‰ Summary

CocoBase v2.0 gives you:

โœ… Traditional SQL database (not JSON storage)
โœ… Event-driven architecture (13 lifecycle hooks)
โœ… Real-time WebSocket subscriptions
โœ… File upload & storage
โœ… SQL editor in dashboard
โœ… Custom routes with database access
โœ… Built-in authentication
โœ… Zero configuration
โœ… Production ready

Build your backend in minutes, not days! ๐Ÿš€


๐Ÿ”— Links


Built with โค๏ธ using FastAPI, SQLModel, and WebSockets

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

cocobase_framework-0.1.0.tar.gz (72.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

cocobase_framework-0.1.0-py3-none-any.whl (76.9 kB view details)

Uploaded Python 3

File details

Details for the file cocobase_framework-0.1.0.tar.gz.

File metadata

  • Download URL: cocobase_framework-0.1.0.tar.gz
  • Upload date:
  • Size: 72.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.3

File hashes

Hashes for cocobase_framework-0.1.0.tar.gz
Algorithm Hash digest
SHA256 842e623e788a4aee884888ffdb1366bb7ba6c014b56378ebd5eb7d0f94accb6d
MD5 b81425b1adcb57c58ff78cc99ae54433
BLAKE2b-256 2fd9a0ffa7a939604faefe2763fc266c9f6095a4a9660cae0a8a1d8a2b3edc84

See more details on using hashes here.

File details

Details for the file cocobase_framework-0.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for cocobase_framework-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 c83b136e1af268c779c84176a8f45167f179404c847ae2ac4fada14c82b6aa50
MD5 cbe5f810da108d90eb5c028353067a49
BLAKE2b-256 992aa9366e915956446eef89225e541ff9fdcd4f3b23ecbcac5a691204301af0

See more details on using hashes here.

Supported by

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