Convert web service from FastAPI to Django 6.1

Replace the FastAPI/SQLAlchemy/Alembic web service with a Django project
laid out like cumorah-build: manage.py at the root, settings in the
privatestudio.settings package (base/dev/production), and a
privatestudio.studio app.

- Studio model owns a unique bucket_name; access is granted through
  membership in the studio's auth Group. Assets, profiles and jobs are
  scoped to a studio; API keys and S3 credentials stay per user.
- JSON API via Django Ninja under /api/ (profiles and transcode jobs now
  live under /api/studios/{bucket}/).
- S3-compatible interface as plain class-based views under /s3/,
  supporting bearer tokens and AWS v4 signatures.
- create_studio and create_key management commands replace ps-serve.
- Fresh Django initial migration; tests ported to Django TestCase.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Shaun Kruger
2026-11-29 21:54:16 -07:00
co-authored by Claude Opus 5.5
parent 46adddd50a
commit b3b51f6cc5
60 changed files with 1776 additions and 3002 deletions
+44 -502
View File
@@ -1,541 +1,83 @@
# ps-serve Command Guide
# Running and Managing Private Studio
A comprehensive guide to using the `ps-serve` command-line interface for managing the Private Studio video transcoding service.
Private Studio is a standard Django project. All administration goes through `manage.py`, which uses `privatestudio.settings.dev` unless `DJANGO_SETTINGS_MODULE` is set.
## Overview
`ps-serve` is the command-line tool for Private Studio. It provides commands to:
- Initialize the database
- Create and manage user accounts
- Generate and manage API keys
- Start the web server
## Installation for Testing
### Quick Setup in a Virtual Environment
If you want to test the web service locally, here's the fastest way to get started:
#### 1. Clone the Repository
```bash
git clone https://github.com/yourusername/privatestudio.git
cd privatestudio
```
#### 2. Create a Virtual Environment
## Setup
```bash
python3 -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
```
#### 3. Install in Development Mode
```bash
pip install -e ".[dev]"
```
This installs the package in "editable" mode, which means:
- Changes to the code are immediately reflected
- All dependencies (FastAPI, SQLAlchemy, etc.) are installed
- Development tools (pytest, httpx) are also installed
#### 4. Verify Installation
```bash
ps-serve --help
```
You should see the help output showing all available commands.
### Virtual Environment Location
Keep your virtual environment separate from the source code:
```bash
# Recommended structure
~/projects/privatestudio/
├── venv/ # Virtual environment (git-ignored)
├── privatestudio/ # Source code
├── tests/
├── pyproject.toml
└── README.md
```
### Updating Your Installation
When you pull new changes from git:
```bash
# Activate your virtual environment
source venv/bin/activate
# Reinstall to pick up new dependencies
pip install -e ".[dev]"
# Run tests to verify everything works
pytest tests/test_web.py -v
python manage.py migrate
```
## Commands Reference
## Access Model
### ps-serve init
- **Users** are standard `django.contrib.auth` users.
- **Studios** each own one unique `bucket_name` and point to one Django **Group**.
- A user can access a studio (its S3 bucket, profiles and jobs) when they are in that studio's group. Superusers can access every studio.
- **API keys** belong to a user and authenticate as that user. Only a SHA256 hash of each key is stored.
Initialize the database for a new installation.
## Commands
**Syntax:**
```bash
ps-serve init
```
**What it does:**
- Creates a `transcoding.db` SQLite database file in the current directory
- Creates all tables (users, api_keys, assets, jobs, profiles, etc.)
- Safe to run multiple times (idempotent)
**Example:**
```bash
$ mkdir ~/transcoding-server && cd ~/transcoding-server
$ ps-serve init
Database initialized
$ ls
transcoding.db
```
**Environment Variable:**
- `DATABASE_URL`: Path to database (default: `./transcoding.db`)
### Create users
```bash
DATABASE_URL="sqlite:///var/lib/privatestudio/transcoding.db" ps-serve init
python manage.py createsuperuser # admin user
python manage.py shell -c "from django.contrib.auth.models import User; User.objects.create_user('alice')"
```
---
You can also create users in the admin at `/admin/`.
### ps-serve create-user
Create a new user account for API access.
**Syntax:**
```bash
ps-serve create-user <username>
```
**Arguments:**
- `<username>`: The username for the new account (must be unique)
**What it does:**
- Creates a new user in the database
- Returns the user ID (needed for creating API keys)
- Users can have multiple API keys
**Examples:**
```bash
$ ps-serve create-user alice
User created: alice (ID: 1)
$ ps-serve create-user bob
User created: bob (ID: 2)
```
**Error Handling:**
```bash
$ ps-serve create-user alice
Error: User 'alice' already exists
```
**Output Format:**
The command prints the username and user ID, which you'll need for the next step.
---
### ps-serve create-key
Generate a new API key for a user.
**Syntax:**
```bash
ps-serve create-key <user_name>
```
**Arguments:**
- `<user_name>`: The username of the user (obtained from `create-user` output)
**What it does:**
- Generates a random 32-character API key
- Stores the SHA256 hash in the database
- Prints the plain key (save this somewhere safe!)
- The key cannot be recovered later—users must create a new one if lost
**Example:**
```bash
$ ps-serve create-key alice
API key created for user alice
Key: 4YXDJoXf26auwGFQPKB6aB-kY6HxbkKPJzmWFbs7cnM
Keep this key safe - you won't be able to see it again!
```
**Security Notes:**
- The key is only displayed once
- Store it securely (environment variable, secret manager, encrypted file)
- Never commit it to version control
- Users can have multiple active keys (useful for key rotation)
**Example Workflow:**
```bash
# Create two keys for the same user (one for testing, one for production)
$ ps-serve create-key alice
Key: test_key_abc123...
$ ps-serve create-key alice
Key: prod_key_xyz789...
```
---
### ps-serve serve
Start the FastAPI web server.
**Syntax:**
```bash
ps-serve serve [OPTIONS]
```
**Options:**
```
--host HOST Server host address (default: 0.0.0.0)
--port PORT Server port (default: 8000)
--reload Enable auto-reload on code changes (for development)
--log-level LEVEL Log level: debug, info, warning, error (default: info)
```
**What it does:**
- Starts the FastAPI server
- Initializes the database if it doesn't exist
- Listens for HTTP requests
- Logs all requests and errors
**Examples:**
**Start with defaults:**
```bash
$ ps-serve serve
INFO: Application startup complete
INFO: Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
```
**Development mode with auto-reload:**
```bash
ps-serve serve --reload
```
Changes to Python files will automatically restart the server.
**Custom host and port:**
```bash
ps-serve serve --host 127.0.0.1 --port 5000
```
Now the server is only accessible locally at `http://127.0.0.1:5000`
**Detailed logging:**
```bash
ps-serve serve --log-level debug
```
**All options together:**
```bash
ps-serve serve --host localhost --port 8080 --reload --log-level debug
```
**Environment Variables:**
These can also be set via environment variables:
- `SERVER_HOST`: Server host (default: `0.0.0.0`)
- `SERVER_PORT`: Server port (default: `8000`)
- `DATABASE_URL`: Database path (default: `./transcoding.db`)
- `STORAGE_PATH`: File storage directory (default: `./storage`)
- `SQL_ECHO`: Log all SQL queries (true/false)
Example:
```bash
export SERVER_HOST=localhost
export SERVER_PORT=9000
export STORAGE_PATH=/media/transcoding
ps-serve serve
```
---
## Complete Workflow
Here's a typical setup workflow from start to finish:
### 1. Initialize Database
### create_studio
```bash
mkdir ~/my-transcoding-server
cd ~/my-transcoding-server
ps-serve init
python manage.py create_studio <bucket_name> --group <group> [--name "Display Name"] [--add-user USER ...]
```
### 2. Create Users
This creates the group if it doesn't exist, adds the given users to it, and creates the studio. Bucket names must be lowercase letters, digits and hyphens.
### create_key
```bash
ps-serve create-user alice
ps-serve create-user bob
python manage.py create_key <username>
```
### 3. Create API Keys
This prints a new API key. The key is shown only once. Users can also create and revoke their own keys through `/api/keys`.
### Run the server
```bash
ps-serve create-key alice # For alice
# Save this key somewhere secure
ps-serve create-key bob # For bob
python manage.py runserver 0.0.0.0:8000
```
### 4. Start the Server
In production, set `DJANGO_SETTINGS_MODULE=privatestudio.settings.production` and serve `privatestudio.wsgi:application` or `privatestudio.asgi:application` with your WSGI/ASGI server of choice. See the configuration table in [README.md](README.md).
## Typical Workflow
```bash
ps-serve serve
python manage.py migrate
python manage.py createsuperuser --username admin
python manage.py shell -c "from django.contrib.auth.models import User; User.objects.create_user('alice')"
python manage.py create_studio demo --name "Demo Studio" --group demo-team --add-user alice
python manage.py create_key alice
python manage.py runserver
curl -H "Authorization: Bearer $KEY" http://localhost:8000/api/userinfo
curl -X PUT -H "Authorization: Bearer $KEY" --data-binary @video.mp4 http://localhost:8000/s3/demo/video.mp4
curl -H "Authorization: Bearer $KEY" http://localhost:8000/s3/demo
```
### 5. Use the API
In another terminal:
## Tests
```bash
# Upload a video
curl -X PUT \
-H "Authorization: Bearer YOUR_API_KEY" \
-F "file=@myvideo.mp4" \
http://localhost:8000/s3/1/videos/myvideo.mp4
# List uploaded files
curl -H "Authorization: Bearer YOUR_API_KEY" \
http://localhost:8000/s3/1
pytest # all tests
pytest privatestudio/studio/tests/test_s3.py -k signature
pytest --cov=privatestudio
```
---
## Troubleshooting
### Command not found: ps-serve
**Problem:** `ps-serve: command not found`
**Solution:** Make sure you've activated the virtual environment and installed the package:
```bash
source venv/bin/activate
pip install -e .
```
### Database locked error
**Problem:** `sqlite3.OperationalError: database is locked`
**Solution:** SQLite doesn't handle concurrent writes well. For production:
1. Stop any running servers
2. Use PostgreSQL instead (change `DATABASE_URL`)
3. Reduce concurrency
### Port already in use
**Problem:** `OSError: [Errno 48] Address already in use`
**Solution:** Use a different port:
```bash
ps-serve serve --port 8001
```
Or kill the existing process:
```bash
# Find the process
lsof -i :8000
# Kill it
kill -9 <PID>
```
### API key not working
**Problem:** `401 Unauthorized: Invalid API key`
**Possible causes:**
1. Wrong API key
2. API key was revoked
3. Key header is malformed (must be `Authorization: Bearer KEY`)
**Debug:**
```bash
# List all keys for a user
curl -H "Authorization: Bearer YOUR_KEY" \
http://localhost:8000/api/keys
```
---
## Running Tests
After making changes, run the test suite to ensure everything works:
```bash
# Activate virtual environment
source venv/bin/activate
# Run all tests
pytest tests/test_web.py -v
# Run a specific test
pytest tests/test_web.py::test_upload_file -v
# Run with coverage
pytest tests/test_web.py --cov=privatestudio.web --cov-report=html
```
Coverage report is generated in `htmlcov/index.html`
---
## Development Tips
### 1. Auto-reload During Development
```bash
ps-serve serve --reload
```
Every time you save a Python file, the server will restart automatically.
### 2. View SQL Queries
```bash
export SQL_ECHO=true
ps-serve serve
```
This logs all database queries to stdout for debugging.
### 3. Use a Specific Database
```bash
export DATABASE_URL="sqlite:///./test_db.db"
ps-serve init
ps-serve serve
```
Useful for keeping multiple database instances (dev, test, prod).
### 4. Store Configuration in .env
Create a `.env` file:
```bash
# .env
DATABASE_URL=sqlite:///./transcoding.db
STORAGE_PATH=./media
SERVER_HOST=localhost
SERVER_PORT=8000
SQL_ECHO=false
```
Then source it before running commands:
```bash
source .env
ps-serve serve
```
Or use a tool like `python-dotenv`:
```bash
pip install python-dotenv
```
Then in your code or shell initialization.
---
## Security Best Practices
1. **Protect API Keys**
- Never commit keys to version control
- Store in environment variables or secure vaults
- Rotate keys regularly
2. **Database Security**
- Use PostgreSQL for production (not SQLite)
- Enable database backups
- Run database on a separate server
3. **Network Security**
- Use HTTPS in production (behind a reverse proxy like nginx)
- Bind to localhost if only local access is needed
- Implement rate limiting and authentication
4. **File Storage**
- Keep storage directory outside the web root
- Use a dedicated disk or object storage (S3, MinIO) for production
- Implement backup strategy
---
## Next Steps
After getting `ps-serve` running:
1. **Upload Your First Video**
- See DEPLOYMENT.md for S3 API examples
2. **Create a Transcode Profile**
- Define encoding profiles in YAML
- Request transcode jobs
3. **Integrate with Your Application**
- Use the REST API from your application
- Handle job status polling
4. **Deploy to Production**
- Use a real database (PostgreSQL)
- Run behind nginx or similar proxy
- Set up monitoring and backups
---
## Getting Help
For more detailed information:
- **API Documentation**: Start the server and visit `http://localhost:8000/docs`
- **Deployment Guide**: See `README.md`
- **Source Code**: Check `privatestudio/web/` for implementation details
---
## Quick Reference Cheat Sheet
```bash
# Setup
python3 -m venv venv
source venv/bin/activate
pip install -e ".[dev]"
# First time
ps-serve init
ps-serve create-user myuser
ps-serve create-key 1
# Development
ps-serve serve --reload --log-level debug
# Testing
pytest tests/test_web.py -v
# Production
DATABASE_URL="postgresql://user:pass@localhost/psdb" \
SERVER_HOST=0.0.0.0 \
SERVER_PORT=8000 \
ps-serve serve
```
- **401 Unauthorized**: the API key is wrong or revoked, or the S3 credentials have expired (by default they last 1 hour, set by `S3_CREDENTIAL_TTL_HOURS`).
- **403 on a bucket**: the user isn't in the studio's group. Add them in the admin.
- **404 on a bucket**: no studio has that `bucket_name`.