Skip to content

Latest commit

 

History

History
423 lines (309 loc) · 12.6 KB

File metadata and controls

423 lines (309 loc) · 12.6 KB

Python Initializer - AI Assistant Guide

Project Overview

Python Initializer is a full-stack web application that generates customized Python project boilerplates for FastAPI, Django, and Flask frameworks. Users can configure their projects through an interactive UI and download ready-to-use project structures.

Tech Stack

  • Frontend: React 18, TypeScript, Vite, TailwindCSS, Radix UI, Wouter (routing)
  • Backend: Express.js, TypeScript, Node.js
  • Database: PostgreSQL with Drizzle ORM
  • Authentication: Google SSO, Apple SSO (token-based sessions)
  • Template Engine: EJS for Python code generation
  • Build Tools: Vite (frontend), esbuild (backend)
  • Code Editor: Monaco Editor for file preview

Repository Structure

python-initializer/
├── client/                      # React frontend application
│   ├── src/
│   │   ├── components/          # Reusable UI components
│   │   │   └── ui/             # Radix UI component wrappers
│   │   ├── hooks/              # Custom React hooks
│   │   ├── lib/                # Utility functions
│   │   ├── pages/              # Route pages (Home, Documentation)
│   │   ├── providers/          # React context providers
│   │   ├── App.tsx             # Main app component
│   │   ├── main.tsx            # React entry point
│   │   └── index.css           # Global styles with Tailwind
│   └── index.html              # HTML entry point
│
├── server/                      # Express backend
│   ├── generators/             # Framework-specific generators
│   │   ├── fastapi.ts          # FastAPI project generator
│   │   ├── django.ts           # Django project generator
│   │   └── flask.ts            # Flask project generator
│   ├── templates/              # EJS templates for code generation
│   │   ├── common/             # Shared templates (README, .gitignore, etc.)
│   │   ├── django/             # Django-specific templates
│   │   ├── fastapi/            # FastAPI-specific templates
│   │   └── flask/              # Flask-specific templates
│   ├── utils/                  # Server utilities
│   │   ├── templateRenderer.ts # EJS template rendering logic
│   │   └── zipGenerator.ts     # Project zip archive creation
│   ├── index.ts                # Server entry point
│   ├── routes.ts               # API route handlers
│   ├── storage.ts              # Database access layer
│   └── vite.ts                 # Vite dev server integration
│
├── shared/                      # Shared code between client/server
│   └── schema.ts               # Zod schemas, Drizzle tables, types
│
├── package.json                # Dependencies and scripts
├── tsconfig.json               # TypeScript configuration
├── vite.config.ts              # Vite configuration
├── drizzle.config.ts           # Drizzle ORM configuration
├── tailwind.config.ts          # TailwindCSS configuration
└── .gitignore

Core Concepts

1. Project Configuration Schema

Defined in shared/schema.ts, the project configuration includes:

  • projectName: String (1-100 chars)
  • framework: fastapi | django | flask
  • pythonVersion: 3.13.2 | 3.12.0 | 3.11.4 | 3.10.12 | 3.9.18
  • database: postgresql | mysql | sqlite | mongodb
  • orm: sqlalchemy | pymongo | django | none
  • features: Array of features like auth, docker, testing, migrations, cors, etc.

2. Generator Architecture

Each framework has a dedicated generator:

  • FastAPI Generator (server/generators/fastapi.ts)
  • Django Generator (server/generators/django.ts)
  • Flask Generator (server/generators/flask.ts)

Generators:

  1. Create directory structure based on config
  2. Use TemplateRenderer to render EJS templates
  3. Generate files with proper Python code
  4. Return the project directory path

3. Template System

Templates are EJS files stored in server/templates/[framework]/:

  • Variables are passed via ProjectConfig
  • Conditional rendering based on selected features
  • Templates generate Python files, configs, Dockerfiles, requirements.txt, etc.

4. Authentication System

Token-based authentication with SSO support:

  • Providers: Google, Apple (email/password planned)
  • Session Management: Bearer tokens stored in database
  • Session Expiry: 30 days
  • Middleware: authenticateUser() in routes.ts

5. Database Schema

Tables defined in shared/schema.ts:

  • users: User accounts with SSO provider info
  • user_sessions: Authentication sessions
  • generation_history: Track generated projects
  • project_templates: Pre-configured project templates

API Endpoints

Authentication

  • POST /api/auth/google - Google SSO login
  • POST /api/auth/apple - Apple SSO login
  • POST /api/auth/logout - Logout (requires auth)
  • GET /api/auth/me - Get current user (requires auth)

Project Generation

  • GET /api/templates - List project templates
  • GET /api/templates/:id - Get specific template
  • POST /api/generate - Generate and download project zip
  • POST /api/preview/structure - Get file structure preview
  • POST /api/preview/file - Get file content preview
  • GET /api/history - Get generation history

Development Workflow

Setup

# Install dependencies
npm install

# Set up environment variables
# Required: DATABASE_URL
echo "DATABASE_URL=postgresql://..." > .env

# Push database schema
npm run db:push

# Start development server
npm run dev

The dev server runs on port 5000 and serves both frontend and API.

Build

# Type check
npm run check

# Build for production
npm run build

# Start production server
npm start

Database Migrations

# Push schema changes to database
npm run db:push

Key Conventions

TypeScript Path Aliases

  • @/*client/src/*
  • @shared/*shared/*

Configured in:

  • tsconfig.json (TypeScript)
  • vite.config.ts (Vite bundler)

Code Organization

  1. Shared Code: Type definitions and schemas in shared/
  2. Server Logic: Business logic in server/routes.ts, data access in server/storage.ts
  3. Client Logic: React components in client/src/, pages use Wouter routing
  4. Validation: Zod schemas for runtime validation (from @shared/schema)

Error Handling

  • Zod validation errors return 400 with error details
  • Authentication errors return 401
  • Server errors return 500 with error message
  • Errors logged to console with context

Logging

Request logging middleware in server/index.ts:

  • Logs API requests with method, path, status, duration
  • Includes response JSON for debugging
  • Truncates long log lines to 80 characters

Generator Development

Adding a New Framework

  1. Create generator file: server/generators/[framework].ts
  2. Add templates: server/templates/[framework]/
  3. Update projectConfigSchema in shared/schema.ts
  4. Add route handler case in server/routes.ts
  5. Update frontend UI to support the framework

Adding a New Feature

  1. Add feature to featureEnum in shared/schema.ts
  2. Update generator to handle feature flag
  3. Create/update templates with conditional logic
  4. Update directory structure if needed

Template Variables

Templates receive the ProjectConfig object with all configuration:

# Example template usage
project_name = "<%= projectName %>"
python_version = "<%= pythonVersion %>"

<% if (features.includes('docker')) { %>
# Docker configuration
<% } %>

Common Tasks for AI Assistants

Adding a New API Endpoint

  1. Add route handler in server/routes.ts
  2. Use Zod for input validation
  3. Call storage methods from server/storage.ts
  4. Return appropriate HTTP status codes
  5. Handle errors with try-catch

Modifying Database Schema

  1. Update table definitions in shared/schema.ts
  2. Update insert schemas if needed
  3. Run npm run db:push to apply changes
  4. Update storage methods in server/storage.ts

Adding UI Components

  1. Create component in client/src/components/
  2. Use Radix UI primitives from client/src/components/ui/
  3. Style with TailwindCSS classes
  4. Import and use in pages

Debugging Generated Projects

  1. Check template files in server/templates/[framework]/
  2. Verify generator logic in server/generators/[framework].ts
  3. Test with /api/preview/structure and /api/preview/file
  4. Generate and inspect zip file locally

Testing

Manual Testing

# Start dev server
npm run dev

# Test project generation
curl -X POST http://localhost:5000/api/generate \
  -H "Content-Type: application/json" \
  -d '{
    "projectName": "test_project",
    "framework": "fastapi",
    "pythonVersion": "3.12.0",
    "database": "postgresql",
    "orm": "sqlalchemy",
    "features": ["auth", "docker", "testing"]
  }'

Preview Testing

Use preview endpoints to verify generated code without creating zip:

# Get file structure
curl -X POST http://localhost:5000/api/preview/structure \
  -H "Content-Type: application/json" \
  -d '{ ... config ... }'

# Get file content
curl -X POST http://localhost:5000/api/preview/file \
  -H "Content-Type: application/json" \
  -d '{
    "config": { ... },
    "filePath": "app/main.py"
  }'

Important Notes

Security

  • Passwords are stored as nullable (SSO users don't have passwords)
  • Sessions expire after 30 days
  • Bearer tokens are 64-byte random hex strings
  • Always validate input with Zod schemas
  • Sanitize file paths to prevent directory traversal

Performance

  • Temporary files cleaned up after download/preview
  • Template rendering is synchronous (may block for large projects)
  • Zip creation happens in temp directories
  • Frontend code-splitting with Vite

Environment

  • Production: Server runs on port 5000 only (not firewalled)
  • Development: Vite dev server integrated with Express
  • Required ENV: DATABASE_URL (PostgreSQL connection string)

Troubleshooting

Common Issues

  1. Database Connection: Ensure DATABASE_URL is set correctly
  2. Template Not Found: Check template path and file existence
  3. Empty Zip: Verify generator creates files before zip
  4. Type Errors: Run npm run check to verify TypeScript
  5. Port Already in Use: Port 5000 is hardcoded, ensure it's available

Development Tips

  • Use console.log in generators to debug file creation
  • Check temp directory contents if files aren't generated
  • Verify EJS template syntax with online validators
  • Test templates with minimal config first
  • Use preview endpoints before implementing download

Git Workflow

Branch Strategy

  • main: Production-ready code (currently empty)
  • feat/v1: Main development branch with full application
  • claude/*: AI assistant working branches

Working with the Codebase

  1. Always check current branch context
  2. For new features, branch from feat/v1
  3. Test changes with npm run dev
  4. Run npm run check before committing
  5. Use descriptive commit messages

Additional Resources

Dependencies of Note

  • Drizzle ORM: Type-safe SQL query builder
  • Zod: Runtime type validation
  • EJS: Embedded JavaScript templates
  • Wouter: Lightweight React router
  • Radix UI: Unstyled, accessible components
  • TailwindCSS: Utility-first CSS framework
  • Monaco Editor: VS Code editor component

Configuration Files

  • drizzle.config.ts: Database migration settings
  • vite.config.ts: Frontend build configuration
  • tsconfig.json: TypeScript compiler options
  • tailwind.config.ts: TailwindCSS theme and plugins
  • postcss.config.js: PostCSS with autoprefixer

Summary for AI Assistants

When working on this codebase:

  1. Understand the flow: Config → Generator → Templates → Zip → Download
  2. Validate inputs: Use Zod schemas from @shared/schema
  3. Test incrementally: Use preview endpoints before full generation
  4. Follow patterns: Match existing code style and structure
  5. Update related files: Changes often require updates to schema, routes, storage, and generators
  6. Consider features: Always check feature flags in config
  7. Clean up resources: Temporary files and directories must be removed
  8. Log appropriately: Use console.log for debugging, structured logging for API requests

This codebase is well-structured with clear separation of concerns. The generator pattern makes it easy to add new frameworks, and the template system provides flexibility for customization.