Performance: Flask project structure conventions
This affects the initial load time and runtime efficiency by organizing code and assets to minimize unnecessary imports and reduce template rendering delays.
project/
app/
__init__.py
routes.py
models.py
templates/
index.html
static/
css/
js/
config.py
run.py
# Example snippet in run.py
from app import create_app
app = create_app()
if __name__ == '__main__':
app.run()app.py # All routes, models, and configurations in one file # Templates and static files mixed in root folder # Example snippet from flask import Flask, render_template app = Flask(__name__) @app.route('/') def home(): return render_template('index.html') if __name__ == '__main__': app.run()
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Single file app with mixed assets | N/A (server-side) | N/A | Higher due to delayed content delivery | [X] Bad |
| Modular app with separate templates/static | N/A (server-side) | N/A | Lower due to faster content delivery | [OK] Good |
templates to hold HTML files for rendering views.templates folder, not static or others.__init__.py to initialize modules and setup code.app folder is a package, so __init__.py initializes the Flask app instance.myproject/ ├── app/ │ ├── __init__.py │ ├── routes.py │ ├── templates/ │ │ └── home.html │ └── static/ │ └── style.css ├── config.py └── run.py
run.py is commonly used as the entry point to start the app server.config.py holds settings, __init__.py initializes app, and routes.py defines routes, but none start the server directly.run.py file:from app import app
if __name__ == '__main__':
app.run(debug=true)python run.py gives an ImportError: cannot import name 'app'. What is the likely cause?app is not found inside the app package's __init__.py.app = Flask(__name__) is defined in __init__.py. If missing, import fails.__init__.py and routes.myproject/ ├── app/ │ ├── __init__.py │ ├── auth/ │ │ ├── __init__.py │ │ └── routes.py │ ├── blog/ │ │ ├── __init__.py │ │ └── routes.py │ ├── templates/ │ └── static/ ├── config.py └── run.pyplaces blueprints inside
app/ folder as sub-packages, keeping templates and static centralized, which is recommended.Pass the test and this pattern moves unknown