Sorting System Backend: Flask to Django Port
A four-phase port moving Flask Blueprints to Django + DRF and splitting the database
Background
The sorting system backend was simple Flask Blueprint routing, and it hit its limits as the team grew. Code conflicts between developers, difficulty separating responsibilities, and the burden of hand-building admin pages piled up. So did the structural cost of editing the MySQL schema every time an AI model changed. Around the same time, code review turned up a hardcoded GitHub token, a JWT lifetime of 100 years, and SQL injection, so security had to be addressed in the same effort.
System architecture
- Phase 1 → 2: internal MVC refactor within Flask, plus a MySQL/MongoDB split by data characteristics.
- Phase 3: zero-downtime move to Django + PostgreSQL, with Django Admin removing the need for a separately built admin page.
- Phase 4: Selector / Service / API three-layer separation, a database strategy framework unifying connection pooling, Redis caching, indexes, and partitions, and the security fixes.
How it was built
Phase 1 — Flask MVC refactor. Routes, logic, and queries scattered across Blueprints were reorganized into MVC. An internal MVC session and a guide document aligned conventions.
Phase 2 — MySQL/MongoDB split. Structured data stayed in MySQL, while unstructured data such as AI inference results and image metadata moved to MongoDB. A model change no longer forces a matching MySQL schema change.
Phase 3 — Django migration. The move from Flask to Django also converted MySQL to PostgreSQL. Django Admin removed the need to build admin pages, and migrating endpoint by endpoint finished the work without service downtime.
Phase 4 — Security and architecture cleanup. Hardcoded secrets moved to environment variables, and the JWT lifetime dropped from 100 years to 7 days. SQL injection was resolved through Django ORM parameter binding. The app structure was standardized into Selector / Service / API layers. Connection pooling, Redis caching, composite indexes, and partition management were consolidated into a single database strategy framework.
Results
- Zero-downtime Flask → Django migration, MySQL → PostgreSQL + MongoDB split.
- JWT lifetime 100 years → 7 days, SQL injection removed, hardcoded secrets moved to environment variables.
- RANGE partitioning and composite indexes cut dashboard load time by 85% and improved graph API response by 90%.
- Selector / Service / API three-layer standard, automated API documentation, and Django Admin-based internal management reduced the team's operational load.