Skip to content

Latest commit

 

History

History
 
 

server-python

README.md

🐍 NexaSphere Python Backend

FastAPI Microservice for Form Processing

High-performance form submission service with Google Sheets and Supabase integration



📌 Overview


Purpose

FastAPI microservice handling:

  • ✓ Form submission processing
  • ✓ Google Sheets integration
  • ✓ Supabase database synchronization
  • ✓ CORS-enabled API endpoints
  • ✓ Real-time data persistence

Key Specifications

Specification Details
Runtime Python 3.11+
Framework FastAPI
Server Uvicorn ASGI
Port 8000
Auto Docs Swagger UI & ReDoc


⚙️ System Requirements


Requirement Version Purpose
Python 3.11+ Runtime environment
pip Latest Package manager
Google Cloud - Form storage
Supabase Latest Database backup


🚀 Quick Start


Step 1️⃣: Create Virtual Environment


macOS/Linux:

cd server-python
python -m venv venv
source venv/bin/activate

Windows:

cd server-python
python -m venv venv
venv\Scripts\activate



Step 2️⃣: Install Dependencies


pip install -r requirements.txt

Key Dependencies:

  • fastapi — Web framework
  • uvicorn — ASGI server
  • pydantic — Data validation
  • google-cloud-sheets — Google integration
  • supabase — Database client
  • python-dotenv — Environment management



Step 3️⃣: Configure Environment


Create .env file in server-python/:

# Google Cloud Setup
GOOGLE_PROJECT_ID=your-project-id
GOOGLE_SERVICE_ACCOUNT_EMAIL=your-sa@project.iam.gserviceaccount.com
GOOGLE_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n"
GOOGLE_SHEET_ID=your-sheet-id

# Supabase Setup
SUPABASE_URL=https://your-project.supabase.co
SUPABASE_SERVICE_ROLE_KEY=your-service-role-key

# Server Configuration
CORS_ORIGIN=http://localhost:5173,https://nexasphere-glbajaj.vercel.app
DEBUG=True

# Certificate Management (required)
# Set a strong random value — without this the server will refuse to start
ADMIN_SECRET=your-strong-random-secret



Step 4️⃣: Run Development Server


uvicorn main:app --reload --port 8000

✅ Server Running on: http://localhost:8000


📚 Interactive Documentation:



🔑 Environment Variables Guide


Google Cloud Authentication


Getting Credentials:

  1. Go to Google Cloud Console
  2. Create new project or select existing
  3. Enable Google Sheets API
  4. Create Service Account
  5. Generate JSON key file
  6. Share Google Sheet with service account email

Required Variables:

GOOGLE_PROJECT_ID=your-gcp-project-id
GOOGLE_SERVICE_ACCOUNT_EMAIL=serviceaccount@project.iam.gserviceaccount.com
GOOGLE_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n"
GOOGLE_SHEET_ID=1a2b3c4d5e6f7g8h9i0j



Supabase Configuration


Getting Credentials:

  1. Create account at Supabase
  2. Create new project
  3. Get project URL from settings
  4. Get service role key from API settings
  5. Create required tables

Required Variables:

SUPABASE_URL=https://projectid.supabase.co
SUPABASE_SERVICE_ROLE_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...


📁 Project Structure


server-python/
│
├── main.py                         ← Application Entry Point
├── requirements.txt                ← Python Dependencies
├── .env.example                    ← Environment Template
├── .env                            ← Local Environment (gitignored)
│
├── routers/                        ← API Routes
│   ├── __init__.py
│   └── forms.py                    ← Form submission endpoints
│
├── services/                       ← Business Logic
│   ├── __init__.py
│   ├── sheets.py                   ← Google Sheets integration
│   └── supabase.py                 ← Supabase operations
│
├── models/                         ← Data Models
│   ├── __init__.py
│   └── forms.py                    ← Pydantic schemas
│
├── README.md
└── seed_db.py                      ← Dummy Data Seeder

<br/>

---

## 🤖 Recommendation Engine

<br/>

The Python backend also powers a highly intelligent **Hybrid Recommendation Engine** using `scikit-learn` (TF-IDF Vectorizer and Cosine Similarity).

### How to Run:
1. Ensure `scikit-learn`, `pandas`, `redis`, and `SQLAlchemy` are installed (already in `requirements.txt`).
2. Run the server using `uvicorn main:app --reload`.
3. Open `http://localhost:8000/docs` to test `GET /recommend/events/{user_id}`.

### Robust Caching (Built-in Redis Fallback)
The engine automatically attempts to connect to Redis using the `REDIS_URL` environment variable for performance optimization.
**If Redis is unavailable (e.g., throwing ConnectionError 10061), the system gracefully logs `Redis unavailable, using local cache` and falls back to a global in-memory Python dictionary cache.** This ensures the application never crashes during testing or deployment even without Redis installed.

### Mock Data Fallback
If you haven't configured a PostgreSQL database, the engine falls back to a realistic set of mock users (e.g., User `101` with `web, react` interests) and mock events to test the collaborative and content-based logic instantly.

<br/>

---

<br/>

## 🔗 API Endpoints

<br/>

### Health Check

GET /health GET /api/forms/status


<br/>

### Membership Form

<br/>

```http
POST /api/forms/membership
Content-Type: application/json

{
  "name": "John Doe",
  "email": "[email protected]",
  "whatsapp": "9876543210",
  "year": "3rd Year",
  "branch": "Computer Science",
  "section": "A",
  "reason": "Want to join the community"
}

Response:

{
  "id": 1,
  "status": "success",
  "message": "Form submitted successfully"
}



Recruitment Form


POST /api/forms/recruitment
Content-Type: application/json

{
  "name": "Jane Smith",
  "email": "[email protected]",
  "whatsapp": "9876543210",
  "year": "2nd Year",
  "branch": "Electronics",
  "section": "B",
  "reason": "Interested in contributing"
}



Core Team Application


POST /api/forms/core-team
Content-Type: application/json

{
  "name": "Alice Johnson",
  "email": "[email protected]",
  "whatsapp": "9876543210",
  "year": "4th Year",
  "branch": "IT",
  "section": "A",
  "reason": "Leadership experience"
}


📊 Google Sheets Integration


Sheet Structure


Create a Google Sheet with these tabs:


Tab 1: Membership Forms

Column Header
A Timestamp
B Name
C Email
D WhatsApp
E Year
F Branch
G Section
H Reason

Tab 2: Recruitment Forms (Same structure)

Tab 3: Core Team Applications (Same structure)


Setup Instructions


  1. Create Google Sheet

    • Go to Google Sheets
    • Add three tabs as shown above
    • Add headers in first row
  2. Share with Service Account

    • Get email from GOOGLE_SERVICE_ACCOUNT_EMAIL
    • Click Share → Add service account email
    • Grant Editor access
  3. Copy Sheet ID

    • Sheet URL: https://docs.google.com/spreadsheets/d/{SHEET_ID}/edit
    • Add {SHEET_ID} to .env


💾 Supabase Integration


Create Tables


Login to Supabase and run these SQL scripts:


-- Membership Forms Table
CREATE TABLE membership_forms (
  id SERIAL PRIMARY KEY,
  name VARCHAR(100) NOT NULL,
  email VARCHAR(255) NOT NULL,
  whatsapp VARCHAR(10) NOT NULL,
  year VARCHAR(20) NOT NULL,
  branch VARCHAR(100) NOT NULL,
  section VARCHAR(1) NOT NULL,
  reason TEXT,
  created_at TIMESTAMP DEFAULT NOW()
);

-- Recruitment Forms Table
CREATE TABLE recruitment_forms (
  id SERIAL PRIMARY KEY,
  name VARCHAR(100) NOT NULL,
  email VARCHAR(255) NOT NULL,
  whatsapp VARCHAR(10) NOT NULL,
  year VARCHAR(20) NOT NULL,
  branch VARCHAR(100) NOT NULL,
  section VARCHAR(1) NOT NULL,
  reason TEXT,
  created_at TIMESTAMP DEFAULT NOW()
);

-- Core Team Applications Table
CREATE TABLE core_team_applications (
  id SERIAL PRIMARY KEY,
  name VARCHAR(100) NOT NULL,
  email VARCHAR(255) NOT NULL,
  whatsapp VARCHAR(10) NOT NULL,
  year VARCHAR(20) NOT NULL,
  branch VARCHAR(100) NOT NULL,
  section VARCHAR(1) NOT NULL,
  reason TEXT,
  created_at TIMESTAMP DEFAULT NOW()
);


🧪 Testing


Run All Tests

pytest

Run with Coverage

pytest --cov=. --cov-report=html

📊 View Coverage: htmlcov/index.html


Run Specific Test

pytest tests/test_forms.py::test_membership_submission


🚀 Deployment


Production Server


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

Railway Deployment


cd server-python
railway init
railway up

Render Deployment


  1. Connect GitHub repository to Render
  2. Set Build Command: pip install -r requirements.txt
  3. Set Start Command: uvicorn main:app --host 0.0.0.0 --port 8000
  4. Add environment variables
  5. Deploy

Fly.io Deployment


fly auth login
fly launch
fly deploy

Production Environment Variables


GOOGLE_PROJECT_ID=production-project-id
GOOGLE_SERVICE_ACCOUNT_EMAIL=prod-sa@project.iam.gserviceaccount.com
GOOGLE_PRIVATE_KEY=[from-service-account-json]
GOOGLE_SHEET_ID=production-sheet-id
SUPABASE_URL=https://prod-project.supabase.co
SUPABASE_SERVICE_ROLE_KEY=production-key
CORS_ORIGIN=https://nexasphere-glbajaj.vercel.app
DEBUG=False
ADMIN_SECRET=your-production-admin-secret


🐛 Troubleshooting


Module Errors


❌ ModuleNotFoundError: No module named 'fastapi'

# Solution: Activate venv and install dependencies
source venv/bin/activate    # macOS/Linux
pip install -r requirements.txt

Google Sheets Errors


❌ 403 Forbidden when accessing Sheet

# Solution: Share sheet with service account
# 1. Copy GOOGLE_SERVICE_ACCOUNT_EMAIL
# 2. Open Google Sheet
# 3. Click Share → Add email → Editor

❌ Invalid GOOGLE_SHEET_ID

# Solution: Extract from URL
# https://docs.google.com/spreadsheets/d/{SHEET_ID}/edit
# Copy the {SHEET_ID} part

Connection Errors


❌ Connection refused to Supabase

# Solution: Verify environment variables
echo $SUPABASE_URL
echo $SUPABASE_SERVICE_ROLE_KEY

CORS Issues


❌ CORS policy error from frontend

# Solution: Check CORS_ORIGIN environment variable
# Ensure frontend URL is included
CORS_ORIGIN=https://nexasphere-glbajaj.vercel.app



📚 Resources





Questions? 📧 Contact [email protected]

Backend Version: 1.0 | Last Updated: May 2026