Consider a Flask app with this structure:
myapp/
app.py
templates/
home.html
static/
style.cssThe app.py contains:
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_template('home.html')What will the app do when you visit the root URL?
from flask import Flask, render_template app = Flask(__name__) @app.route('/') def home(): return render_template('home.html')
Flask looks for templates in the templates folder by default.
Flask automatically finds templates in the templates folder inside the project directory. The route '/' renders home.html correctly.
In a standard Flask project, where should you place CSS, JavaScript, and image files so Flask can serve them automatically?
Flask uses a default folder name for static files.
Flask serves static files from the static folder by default.
Given this project structure:
myapp/
app/
__init__.py
routes.py
templates/
index.htmlAnd app/__init__.py contains:
from flask import Flask app = Flask(__name__) from app import routes
But running the app raises TemplateNotFound when rendering index.html. What is the likely cause?
from flask import Flask app = Flask(__name__) from app import routes
Flask looks for templates relative to the app package location.
When the Flask app is created inside a package (app), Flask expects the templates folder inside that package folder. Having templates outside causes TemplateNotFound.
In a Flask project structured as a package, why do we include an __init__.py file inside the app folder?
Think about Python packages and app initialization.
The __init__.py file makes the folder a Python package and usually contains the Flask app creation code.
Given this Flask project structure:
myapp/
app/
__init__.py
routes.py
run.pyWith app/__init__.py:
from flask import Flask app = Flask(__name__) from app import routes
And app/routes.py:
from app import app
@app.route('/')
def home():
return 'Home'
@app.route('/about')
def about():
return 'About'And run.py:
from app import app
if __name__ == '__main__':
app.run()How many routes will the app have when running?
from flask import Flask app = Flask(__name__) from app import routes # routes.py from app import app @app.route('/') def home(): return 'Home' @app.route('/about') def about(): return 'About' # run.py from app import app if __name__ == '__main__': app.run()
Check where routes are defined and imported.
Both routes '/' and '/about' are defined in routes.py, which is imported in __init__.py, so both are registered.