How to divide flask app into multiple py files?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
A single-file Flask app is fine for experiments, but it becomes difficult to maintain once routes, database logic, and integrations start to grow. Splitting the project into modules improves readability, makes testing easier, and reduces merge conflicts in team environments. The most reliable structure usually combines an app factory, blueprints, and shared extension modules.
Start with a Clear Project Layout
A practical directory structure gives each concern a home and keeps import paths predictable.
This structure separates HTTP concerns from business logic and infrastructure code, which makes later refactors much less painful.
Create an App Factory
The app factory creates and configures Flask instances for development, tests, and production without global side effects.
Factory style keeps startup deterministic and avoids hidden import-time behavior.
Keep Shared Integrations in One Module
Extension objects such as SQLAlchemy should be declared once and initialized inside create_app.
This pattern avoids circular imports that happen when each route file creates its own extension instance.
Split Routes with Blueprints
Blueprints allow route modules to be organized by domain. Keep route handlers thin and delegate work to services.
Each blueprint should own one coherent area of the API.
Move Business Logic to Services
Services keep non HTTP logic out of route files.
This makes route handlers easier to test and prevents API concerns from leaking into domain logic.
Configure by Environment
Use config classes for predictable values across local, test, and production setups.
Keep secrets in environment variables, not in source files.
Entry Point and Local Run
A simple entry point connects your factory to Flask CLI.
Now the same app object pattern can be reused in deployment servers and tests.
Write Basic Tests Early
Module boundaries are only useful if protected by tests. Add quick route tests to catch registration and import issues.
Even a small test set prevents many refactor regressions.
Common Pitfalls
- Importing the Flask app object globally inside route modules, which causes circular imports.
- Putting database and business logic directly in endpoints, making handlers too large.
- Initializing extensions in multiple files instead of a shared module.
- Spreading configuration values across modules with no clear source of truth.
- Forgetting to add
__init__.pyin package folders, which breaks imports.
Summary
- Use an app factory to create modular, testable Flask apps.
- Organize endpoints with blueprints grouped by domain.
- Keep shared extensions in one place and initialize in the factory.
- Move business rules into service modules to keep routes focused.
- Back the structure with basic tests so refactors remain safe.

