mirror of
https://github.com/pacnpal/thrillwiki_django_no_react.git
synced 2025-12-20 13:11:08 -05:00
6.3 KiB
6.3 KiB
Code Documentation
Project Structure
thrillwiki/
├── accounts/ # User management
├── analytics/ # Usage tracking
├── companies/ # Company profiles
├── core/ # Core functionality
├── designers/ # Designer profiles
├── email_service/ # Email handling
├── history/ # Historical views
├── history_tracking/ # Change tracking
├── location/ # Geographic features
├── media/ # Media management
├── moderation/ # Content moderation
├── parks/ # Park management
├── reviews/ # Review system
└── rides/ # Ride management
Code Patterns
1. Model Patterns
History Tracking
@pghistory.track()
class TrackedModel(models.Model):
"""Base class for models with history tracking"""
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
Slug Management
class SluggedModel:
"""Pattern for models with slug-based URLs"""
@classmethod
def get_by_slug(cls, slug: str) -> Tuple[Model, bool]:
# Check current slugs
try:
return cls.objects.get(slug=slug), False
except cls.DoesNotExist:
# Check historical slugs
historical = HistoricalSlug.objects.filter(
content_type=ContentType.objects.get_for_model(cls),
slug=slug
).first()
if historical:
return cls.objects.get(pk=historical.object_id), True
Generic Relations
# Example from parks/models.py
class Park(TrackedModel):
location = GenericRelation(Location)
photos = GenericRelation(Photo)
2. View Patterns
Class-Based Views
class ModeratedCreateView(LoginRequiredMixin, CreateView):
"""Base view for content requiring moderation"""
def form_valid(self, form):
obj = form.save(commit=False)
obj.status = 'PENDING'
obj.created_by = self.request.user
return super().form_valid(form)
Permission Mixins
class ModeratorRequiredMixin:
"""Ensures user has moderation permissions"""
def dispatch(self, request, *args, **kwargs):
if not request.user.has_perm('moderation.can_moderate'):
raise PermissionDenied
return super().dispatch(request, *args, **kwargs)
3. Service Patterns
Email Service
class EmailService:
"""Handles email templating and sending"""
def send_moderation_notification(self, content):
template = 'moderation/email/notification.html'
context = {'content': content}
self.send_templated_email(template, context)
Media Processing
class MediaProcessor:
"""Handles image optimization and processing"""
def process_image(self, image):
# Optimize size
# Extract EXIF
# Generate thumbnails
return processed_image
Dependencies
Core Dependencies
# From pyproject.toml
[tool.poetry.dependencies]
django = "5.1.6"
djangorestframework = "3.15.2"
django-allauth = "65.4.1"
psycopg2-binary = "2.9.10"
django-pghistory = "3.5.2"
Frontend Dependencies
{
"tailwindcss": "^3.0.0",
"htmx": "^1.22.0",
"webpack": "^5.0.0"
}
Build Configuration
Django Settings
INSTALLED_APPS = [
# Django apps
'django.contrib.admin',
'django.contrib.auth',
# Third-party apps
'allauth',
'rest_framework',
'corsheaders',
# Local apps
'parks.apps.ParksConfig',
'rides.apps.RidesConfig',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
]
Database Configuration
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': env('DB_NAME'),
'USER': env('DB_USER'),
'PASSWORD': env('DB_PASSWORD'),
'HOST': env('DB_HOST'),
'PORT': env('DB_PORT'),
}
}
Testing Framework
Test Structure
tests/
├── unit/ # Unit tests
├── integration/ # Integration tests
└── e2e/ # End-to-end tests
Test Patterns
class ParkTestCase(TestCase):
def setUp(self):
self.park = Park.objects.create(
name="Test Park",
status="OPERATING"
)
def test_park_creation(self):
self.assertEqual(self.park.slug, "test-park")
Package Management
Python Dependencies
# Development dependencies
pip install -r requirements-dev.txt
# Production dependencies
pip install -r requirements.txt
Frontend Build
# Install frontend dependencies
npm install
# Build static assets
npm run build
Code Quality Tools
Python Tools
- black (code formatting)
- flake8 (linting)
- mypy (type checking)
- pytest (testing)
Configuration Files
# pyproject.toml
[tool.black]
line-length = 88
target-version = ['py311']
[tool.mypy]
plugins = ["mypy_django_plugin.main"]
Development Workflow
Local Development
- Set up virtual environment
- Install dependencies
- Run migrations
- Start development server
python -m venv venv
source venv/bin/activate
pip install -r requirements.txt
python manage.py migrate
python manage.py runserver
Code Review Process
- Run linting tools
- Run test suite
- Check type hints
- Review documentation
Deployment Process
Pre-deployment Checks
- Run test suite
- Check migrations
- Validate static files
- Verify environment variables
Deployment Steps
- Update dependencies
- Apply migrations
- Collect static files
- Restart application server
Error Handling
Exception Pattern
class CustomException(Exception):
"""Base exception for application"""
def __init__(self, message, code=None):
self.message = message
self.code = code
Middleware Pattern
class ErrorHandlingMiddleware:
"""Centralized error handling"""
def process_exception(self, request, exception):
# Log exception
# Handle gracefully
# Return appropriate response