Add Django backend: users, admin, OTIO + scene persistence

A Project (owner, OTIO file, fps, scene JSON) persists the timeline. Session
API: list projects, GET/PUT scene, serve OTIO. Admin manages users/projects;
seed_demo creates a project from the bundled one_two_three.otio.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Your Name 2026-06-28 23:45:49 -04:00
parent 7a960afb5c
commit 57ef570539
21 changed files with 406 additions and 0 deletions

7
.gitignore vendored
View file

@ -31,3 +31,10 @@ node_modules/
.idea/
.vscode/
.DS_Store
# Python / Django backend
.venv/
__pycache__/
*.pyc
db.sqlite3
/media/

37
README.md Normal file
View file

@ -0,0 +1,37 @@
# scene_analysis
- `tl/` — the lumet frontend (ClojureScript / reagent / re-frame). See `tl/`.
- Django backend (this folder) — users, admin, and persistence of OTIO + the
timeline scene.
## Backend
The backend stores one `Project` per editing session: the uploaded **OTIO**
source file, the playback **fps**, and the live **scene** (the `{:tracks
:groups}` mark-group map the frontend keeps in app-db) as a JSON dump.
### Run
```bash
python -m venv .venv && .venv/bin/pip install -r requirements.txt
.venv/bin/python manage.py migrate
DJANGO_SUPERUSER_PASSWORD=admin .venv/bin/python manage.py createsuperuser --noinput --username admin --email admin@example.com
.venv/bin/python manage.py seed_demo # demo project from tl/.../one_two_three.otio
.venv/bin/python manage.py runserver
```
Admin: <http://127.0.0.1:8000/admin/> (admin / admin). Upload OTIO and inspect
the scene JSON there.
### API (session auth; 401 if not logged in)
| Method | Path | Purpose |
| --- | --- | --- |
| GET | `/api/projects/` | the current user's projects |
| GET | `/api/projects/<id>/scene/` | `{fps, scene}` |
| PUT | `/api/projects/<id>/scene/` | replace `scene` and/or `fps` (JSON body) |
| GET | `/api/projects/<id>/otio/` | serve the uploaded OTIO file |
The frontend currently loads `/one_two_three.otio` and persists annotations to
localStorage; pointing it at `/api/projects/<id>/otio/` and the scene endpoints
is the next wiring step (CORS/credentials needed across the dev ports).

22
manage.py Executable file
View file

@ -0,0 +1,22 @@
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'server.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()

3
requirements.txt Normal file
View file

@ -0,0 +1,3 @@
asgiref==3.11.1
Django==6.0.6
sqlparse==0.5.5

0
scenes/__init__.py Normal file
View file

11
scenes/admin.py Normal file
View file

@ -0,0 +1,11 @@
from django.contrib import admin
from .models import Project
@admin.register(Project)
class ProjectAdmin(admin.ModelAdmin):
list_display = ("name", "owner", "fps", "updated")
list_filter = ("owner",)
search_fields = ("name",)
readonly_fields = ("created", "updated")

5
scenes/apps.py Normal file
View file

@ -0,0 +1,5 @@
from django.apps import AppConfig
class ScenesConfig(AppConfig):
name = 'scenes'

View file

View file

View file

@ -0,0 +1,31 @@
"""Create a demo Project owned by `admin`, with the bundled OTIO attached."""
from pathlib import Path
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.files import File
from django.core.management.base import BaseCommand
from scenes.models import Project
OTIO = settings.BASE_DIR / "tl" / "resources" / "public" / "one_two_three.otio"
class Command(BaseCommand):
help = "Seed a demo project from the bundled OTIO file."
def handle(self, *args, **opts):
User = get_user_model()
owner = User.objects.filter(username="admin").first()
if owner is None:
self.stderr.write("no 'admin' user — run createsuperuser first")
return
project, created = Project.objects.get_or_create(
owner=owner, name="one two three", defaults={"scene": {}})
if OTIO.exists() and not project.otio:
with OTIO.open("rb") as fh:
project.otio.save(Path(OTIO).name, File(fh), save=True)
verb = "created" if created else "exists"
self.stdout.write(f"project #{project.pk} {verb}: {project.name} (otio={bool(project.otio)})")

View file

@ -0,0 +1,33 @@
# Generated by Django 6.0.6 on 2026-06-29 03:38
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Project',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=200)),
('otio', models.FileField(blank=True, null=True, upload_to='otio/')),
('fps', models.FloatField(default=23.976023976023978)),
('scene', models.JSONField(blank=True, default=dict)),
('created', models.DateTimeField(auto_now_add=True)),
('updated', models.DateTimeField(auto_now=True)),
('owner', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='projects', to=settings.AUTH_USER_MODEL)),
],
options={
'ordering': ['-updated'],
},
),
]

View file

25
scenes/models.py Normal file
View file

@ -0,0 +1,25 @@
from django.conf import settings
from django.db import models
NTSC_24 = 24000 / 1001
class Project(models.Model):
"""One editing project: an uploaded OTIO source + the live mark-group scene
(tl.scene) the frontend reads and writes. The scene is just a JSON dump for
now — the whole {:tracks :groups} map the client keeps in app-db."""
owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,
related_name="projects")
name = models.CharField(max_length=200)
otio = models.FileField(upload_to="otio/", blank=True, null=True)
fps = models.FloatField(default=NTSC_24)
scene = models.JSONField(default=dict, blank=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Meta:
ordering = ["-updated"]
def __str__(self):
return f"{self.name} (#{self.pk})"

3
scenes/tests.py Normal file
View file

@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

9
scenes/urls.py Normal file
View file

@ -0,0 +1,9 @@
from django.urls import path
from . import views
urlpatterns = [
path("projects/", views.projects),
path("projects/<int:pk>/scene/", views.scene),
path("projects/<int:pk>/otio/", views.otio),
]

56
scenes/views.py Normal file
View file

@ -0,0 +1,56 @@
import json
from django.http import FileResponse, HttpResponseNotAllowed, JsonResponse
from django.shortcuts import get_object_or_404
from django.views.decorators.csrf import csrf_exempt
from .models import Project
def _auth(request):
"""None if logged in, else a 401 JSON response (so fetch() doesn't get a
login redirect)."""
if not request.user.is_authenticated:
return JsonResponse({"detail": "authentication required"}, status=401)
return None
def _owned(request, pk):
return get_object_or_404(Project, pk=pk, owner=request.user)
def projects(request):
"""GET /api/projects/ — the current user's projects."""
if (resp := _auth(request)):
return resp
rows = Project.objects.filter(owner=request.user).values("id", "name", "fps", "updated")
return JsonResponse(list(rows), safe=False)
@csrf_exempt # dev convenience: session-auth API without a CSRF token round-trip
def scene(request, pk):
"""GET/PUT /api/projects/<pk>/scene/ — read or replace the timeline scene."""
if (resp := _auth(request)):
return resp
project = _owned(request, pk)
if request.method == "GET":
return JsonResponse({"fps": project.fps, "scene": project.scene})
if request.method == "PUT":
data = json.loads(request.body or "{}")
if "scene" in data:
project.scene = data["scene"]
if "fps" in data:
project.fps = data["fps"]
project.save(update_fields=["scene", "fps", "updated"])
return JsonResponse({"ok": True, "updated": project.updated})
return HttpResponseNotAllowed(["GET", "PUT"])
def otio(request, pk):
"""GET /api/projects/<pk>/otio/ — serve the uploaded OTIO file."""
if (resp := _auth(request)):
return resp
project = _owned(request, pk)
if not project.otio:
return JsonResponse({"detail": "no otio uploaded"}, status=404)
return FileResponse(project.otio.open("rb"), content_type="application/json")

0
server/__init__.py Normal file
View file

16
server/asgi.py Normal file
View file

@ -0,0 +1,16 @@
"""
ASGI config for server project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/6.0/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'server.settings')
application = get_asgi_application()

124
server/settings.py Normal file
View file

@ -0,0 +1,124 @@
"""
Django settings for server project.
Generated by 'django-admin startproject' using Django 6.0.6.
For more information on this file, see
https://docs.djangoproject.com/en/6.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/6.0/ref/settings/
"""
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/6.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-it#u2wp)_qjx@cq61o*thw#*4_1*hk!%%lz#d+fww6^*l3j+zj'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['localhost', '127.0.0.1', 'testserver']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'scenes',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'server.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'server.wsgi.application'
# Database
# https://docs.djangoproject.com/en/6.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/6.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/6.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/6.0/howto/static-files/
STATIC_URL = 'static/'
# Uploaded OTIO files
MEDIA_URL = 'media/'
MEDIA_ROOT = BASE_DIR / 'media'
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

8
server/urls.py Normal file
View file

@ -0,0 +1,8 @@
"""URL configuration for the scene_analysis backend."""
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path("admin/", admin.site.urls),
path("api/", include("scenes.urls")),
]

16
server/wsgi.py Normal file
View file

@ -0,0 +1,16 @@
"""
WSGI config for server project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/6.0/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'server.settings')
application = get_wsgi_application()