0
0
Flaskframework~15 mins

Flask project structure conventions - Deep Dive

Choose your learning style9 modes available
Overview - Flask project structure conventions
What is it?
Flask project structure conventions are the common ways developers organize files and folders in a Flask web application. They help keep the code clean, easy to understand, and maintain as the project grows. These conventions include where to put the main app code, templates, static files, and configuration. Following these patterns makes teamwork and scaling easier.
Why it matters
Without a clear structure, Flask projects become messy and hard to manage, especially as they grow or when multiple people work on them. It would be like trying to find a book in a library with no shelves or labels. Good structure saves time, reduces bugs, and helps developers quickly understand and improve the app.
Where it fits
Before learning Flask project structure, you should know basic Python and how Flask apps work at a simple level. After mastering structure conventions, you can learn about advanced Flask features like blueprints, extensions, and deployment best practices.
Mental Model
Core Idea
A well-organized Flask project separates code, templates, static files, and configuration into clear folders to keep the app clean and maintainable.
Think of it like...
Think of a Flask project like a kitchen: code files are the cooking tools, templates are the recipes, static files are the ingredients, and configuration is the kitchen setup. Keeping each in its place makes cooking smooth and fast.
Flask Project Structure

├── app/
│   ├── __init__.py      # Initialize app and extensions
│   ├── routes.py        # URL routes and view functions
│   ├── models.py        # Database models
│   ├── templates/       # HTML templates
│   │   └── *.html
│   └── static/          # CSS, JS, images
│       ├── css/
│       ├── js/
│       └── img/
├── config.py            # Configuration settings
├── run.py               # Entry point to start the app
└── requirements.txt     # Dependencies list
Build-Up - 7 Steps
1
FoundationBasic Flask app file layout
🤔
Concept: Learn the simplest way to organize a Flask app with a single file and folders for templates and static files.
A minimal Flask app usually has one main Python file (like app.py) where the app is created and routes are defined. Two folders sit alongside it: 'templates' for HTML files and 'static' for CSS, JavaScript, and images. This keeps code and assets separate.
Result
You get a working Flask app where HTML pages load correctly with styles and scripts, and the code is easy to find.
Understanding this basic layout is the foundation for all Flask projects and prevents mixing code with design files.
2
FoundationUsing an app package for organization
🤔
Concept: Instead of one file, organize the app code inside a folder treated as a package with an __init__.py file.
Create a folder named 'app' with an __init__.py file that creates the Flask app instance. Put routes, models, and other code in separate files inside this folder. Keep templates and static folders inside 'app' to group all app-related files together.
Result
The app is modular and easier to maintain as code grows, with a clear place for each part.
Packaging the app code helps separate concerns and prepares the project for scaling and teamwork.
3
IntermediateSeparating configuration settings
🤔Before reading on: do you think configuration should be mixed with app code or kept separate? Commit to your answer.
Concept: Move configuration like secret keys and database URLs into a separate config.py file.
Create a config.py file with classes or variables holding settings. Import and apply these settings in the app's __init__.py. This keeps sensitive or environment-specific info out of main code and makes changing settings easier.
Result
You can switch between development, testing, and production settings without changing app code.
Separating configuration improves security and flexibility, which is crucial for real-world apps.
4
IntermediateOrganizing templates and static files
🤔Before reading on: do you think all static files should be in one folder or split into subfolders? Commit to your answer.
Concept: Group static files into subfolders like css, js, and images inside the static folder for clarity.
Inside 'app/static', create folders named 'css', 'js', and 'img'. Place stylesheets in css, scripts in js, and pictures in img. Templates stay in 'app/templates'. This structure helps browsers and developers find assets quickly.
Result
Static files load correctly and are easy to manage, especially when many assets exist.
Clear asset organization prevents confusion and speeds up development and debugging.
5
IntermediateEntry point script for running app
🤔
Concept: Use a separate run.py file to start the Flask app, keeping app creation and running separate.
Create run.py at the project root that imports the app instance from app package and calls app.run(). This separates app logic from how the app is started, which helps with testing and deployment.
Result
You can run the app with 'python run.py' and keep app code clean.
Separating the entry point clarifies responsibilities and supports different ways to run the app.
6
AdvancedUsing Blueprints for modular apps
🤔Before reading on: do you think all routes should live in one file or split by feature? Commit to your answer.
Concept: Blueprints let you split the app into smaller parts, each with its own routes and templates.
Create folders for features (like 'auth', 'blog') inside 'app'. Each has its own routes.py and templates folder. Register these Blueprints in app/__init__.py. This keeps code modular and easier to maintain.
Result
Large apps stay organized, and teams can work on different features without conflicts.
Blueprints enable scalable app design and parallel development.
7
ExpertManaging instance folder and environment configs
🤔Before reading on: do you think sensitive configs belong in the main code or a separate instance folder? Commit to your answer.
Concept: Use Flask's instance folder to store environment-specific and sensitive files outside version control.
Create an 'instance' folder outside the app package. Put config files like config.py or database files here. Tell Flask to load configs from instance folder. This keeps secrets safe and configs flexible per environment.
Result
You can deploy the same code to different servers with different settings securely.
Using the instance folder is a best practice for security and environment management in production.
Under the Hood
Flask looks for templates and static files in specific folders relative to the app package. The __init__.py file creates the Flask app object, which holds configuration and registers routes and Blueprints. When the app runs, Flask uses this structure to find code, templates, and assets efficiently. Blueprints register their routes and templates with the main app, allowing modular loading. The instance folder is a special location Flask can load configs from without including them in the main codebase.
Why designed this way?
Flask was designed to be simple and flexible, so it does not enforce a strict structure but recommends conventions to keep projects manageable. Separating code, templates, and static files follows web development best practices. Blueprints were added later to support larger apps. The instance folder concept was introduced to handle environment-specific settings securely, avoiding hardcoding secrets in code.
Project Structure Flow

[run.py] --> imports --> [app/__init__.py] --> creates --> [Flask app instance]

[app/__init__.py] registers --> [routes.py], [Blueprints]

[Flask app instance] serves --> [templates/*.html]
                      serves --> [static/css, js, img]

[instance/config.py] loaded separately for sensitive settings
Myth Busters - 4 Common Misconceptions
Quick: Do you think putting all code and templates in one folder is fine for any Flask app? Commit yes or no.
Common Belief:It's okay to keep all files in one folder for simplicity, even for big apps.
Tap to reveal reality
Reality:Mixing code, templates, and static files in one folder quickly becomes confusing and unmanageable as the app grows.
Why it matters:This leads to bugs, slows development, and makes teamwork difficult because files are hard to find and organize.
Quick: Do you think the 'static' folder can be anywhere in the project? Commit yes or no.
Common Belief:You can place the static folder anywhere and just configure Flask to find it.
Tap to reveal reality
Reality:Flask expects the static folder inside the app package or at the project root by default; placing it elsewhere requires extra config and can cause broken links.
Why it matters:Incorrect static folder placement breaks loading of CSS, JS, and images, ruining the user experience.
Quick: Do you think Blueprints are only for very large apps? Commit yes or no.
Common Belief:Blueprints are unnecessary for small or medium apps and add complexity.
Tap to reveal reality
Reality:Using Blueprints early helps keep code organized and prepares the app to scale smoothly, even if small at first.
Why it matters:Avoiding Blueprints can cause messy code later and make refactoring harder.
Quick: Do you think storing secret keys in config.py inside the app folder is safe? Commit yes or no.
Common Belief:It's fine to keep all configs, including secrets, inside the main config.py file.
Tap to reveal reality
Reality:Secrets should be kept outside version control, typically in the instance folder or environment variables, to avoid accidental exposure.
Why it matters:Exposing secrets risks security breaches and data leaks.
Expert Zone
1
Blueprints can have their own static and template folders, which Flask merges intelligently at runtime.
2
The instance folder is not created by default; developers must create and configure it properly for environment-specific settings.
3
Flask's app factory pattern, often used with this structure, allows creating multiple app instances with different configs, improving testing and deployment.
When NOT to use
For very simple or one-off scripts, strict project structure may be overkill; a single file app suffices. For large enterprise apps, consider full-stack frameworks like Django that enforce stricter structures and provide more built-in features.
Production Patterns
In production, apps use environment variables and instance folders for secrets, Blueprints for modular features, and separate requirements.txt or Pipfile for dependencies. Deployment scripts often rely on the run.py or app factory pattern to start the app with correct configs.
Connections
Modular programming
Flask project structure uses modular programming principles by separating concerns into files and folders.
Understanding modular programming helps grasp why Flask apps split code into Blueprints and packages for maintainability.
Operating system file hierarchy
Flask project structure mirrors OS file organization by grouping related files into directories.
Knowing how OS organizes files helps understand why Flask groups templates and static assets separately.
Urban city planning
Like city planning zones separate residential, commercial, and industrial areas, Flask separates code, templates, and static files.
This cross-domain view shows how clear separation prevents chaos and improves navigation in complex systems.
Common Pitfalls
#1Putting templates folder outside the app package
Wrong approach:project_root/templates/index.html app/__init__.py creates app without template_folder argument
Correct approach:project_root/app/templates/index.html app/__init__.py creates app normally (Flask finds templates inside app folder)
Root cause:Flask by default looks for templates inside the app package; placing templates elsewhere without configuring template_folder breaks template loading.
#2Defining routes in run.py instead of app package
Wrong approach:In run.py: from flask import Flask app = Flask(__name__) @app.route('/') def home(): return 'Hello' if __name__ == '__main__': app.run()
Correct approach:In app/routes.py: from flask import current_app as app @app.route('/') def home(): return 'Hello' In run.py: from app import app if __name__ == '__main__': app.run()
Root cause:Mixing app creation and route definitions in run.py breaks modularity and makes testing and scaling harder.
#3Committing secret keys in config.py to version control
Wrong approach:config.py: SECRET_KEY = 'supersecretkey' # This file is tracked by git
Correct approach:# Move secret keys to instance/config.py or environment variables # Add instance/ to .gitignore config.py: import os SECRET_KEY = os.environ.get('SECRET_KEY')
Root cause:Beginners often put secrets in code for convenience, risking exposure when sharing or deploying code.
Key Takeaways
Organizing a Flask project into clear folders for code, templates, and static files keeps the app clean and maintainable.
Using an app package with __init__.py and separating configuration improves scalability and security.
Blueprints allow modular design, making large apps easier to develop and maintain.
The instance folder is essential for managing sensitive and environment-specific settings safely.
Following these conventions prevents common bugs and prepares your Flask app for real-world use and teamwork.