Flask Web Application

This chapter takes you from scratch, using Flask to create your first web application and understand the design philosophy of microframeworks.


Positioning differences between Flask and Django

Django is an "all-in-one" full-stack framework, with built-in ORM, template engine, admin backend, user authentication, form handling, and more.

Flask is a microframework—The core is minimal, only providing routing and template rendering; other features are added on demand through extensions.

FeaturesDjangoFlask
Design philosophyOut of the box (batteries included)Micro-framework, extend as needed
ORMBuilt-in Django ORMFlask-SQLAlchemy (Extension)
Database MigrationsBuilt-in makemigrations/migrateFlask-Migrate (Extension)
User AuthenticationBuilt-in auth moduleFlask-Login (Extension)
Admin PanelBuilt-in Django AdminFlask-Admin (Extension)
Template EngineDjango TemplatesJinja2 (syntax is almost identical)
Route ConfigurationCentralized configuration in urls.pyDeclare decorators locally

Recommendation: beginners who want quick results use Django; those who like full control and on-demand assembly use Flask.


Environment Preparation

Confirm the Python version (requires 3.8 or above):

$ python3 --version
Python 3.12.0

Create a virtual environment and install Flask

$ python3 -m venv venv
$ source venv/bin/activate           # Windows:venv\Scripts\activate
(venv) $ pip install flask

Verify installation:

(venv) $ python -c "import flask; print(flask.__version__)"
3.1.0

Minimal Flask application

A Flask application only needs one Python file.

Example

# File path: app.py
from flask import Flask

# Create a Flask app instance
# __name__ tells Flask the location of the current module (used to find templates and static files)
app = Flask(__name__)

# @app.route("/") — route decorator: executes the following function when accessing the / path
@app.route("/")
def index():
    return '<h1>Welcome to EXAMPLE Blog</h1>'

# If you run python app.py directly (instead of flask run), start the development server
if __name__ == '__main__':
    app.run(debug=True)

Start the development server

(venv) $ flask run
 * Running on http://127.0.0.1:5000

Visit http://127.0.0.1:5000/ in your browser and see the page content.

Enable hot reload (automatically restart the server after code changes):

(venv) $ flask run --debug

flask runDefault Lookupapp.pyinappInstance. If the filename or instance name is different, you need to set environment variables:FLASK_APP=myapp.py(file name),FLASK_APP=myapp:create_app()(factory function).


Flask command line tool

exceptflask run, Flask also provides other useful commands.

CommandFunction
flask runStart the development server
flask run --debugStart server + hot reload + debug mode
flask routesList all registered routes
flask shellEnter the interactive shell (automatically imports the app instance)

Project directory structure planning

Although Flask supports single-file applications, real projects need clear directory organization.

blog_project/
├── app/
│   ├── __init__.py          # 应用工厂 create_app()(第十章引入)
│   ├── blueprints/          # 路由 Blueprint(第四章分离)
│   ├── templates/           # Jinja2 模板(第二章创建)
│   ├── static/              # 静态文件 CSS/JS/图片
│   ├── models.py            # SQLAlchemy 模型(第三章创建)
│   └── forms.py             # Flask-WTF 表单(第八章创建)
├── config.py                # 配置文件
├── app.py                   # 应用入口(第一章从这里开始)
└── .env                     # 环境变量

Hands-on: Blog homepage route

Create the project skeleton, configure the homepage route, and let the browser display a welcome message.

Example

# File path: app.py
from flask import Flask

app = Flask(__name__)

@app.route("/")
def index():
    """Blog home page"""
    return """
<h1>Welcome to EXAMPLE Blog</h1>
<p>This is a personal blog showcase site built with Flask.</p>
<p>More content is coming soon, stay tuned.</p>
    """


@app.route("/about")
def about():
    """About page"""
    return '<h1>About This Site</h1><p>Notes on front-end and back-end learning.</p>'

Run:

flask run

Visit the homepage and about page to confirm the routes work properly.


Chapter summary

In this chapter, you completed three things: created a virtual environment and installed Flask, understood the positioning difference between Flask as a microframework and Django as an all-in-one framework, and wrote your first route page.

Core takeaway: A minimal Flask application only requiresFlask(__name__) + @app.route()Decorator, usingflask runStart.

other extensions