Skip to main content
AIDevOps
  • Learn
  • Learning Paths
  • Practice
  • Open Source
  • Books
  • Engineering

    AI DevOpsThe full map of building and operating AI servicesLLMOpsLLM deployment · evaluation · observabilityHands-on ProjectsBuild AI Agent projects

    Knowledge

    DocsTechnical documentationBlogEngineering articlesPloggerDevelopment log feed

    Validate

    Certification3-level skills certification · coming soon
AI Models
LlamaTutorial|MistralTutorial|GemmaTutorial|DeepSeekTutorial|QwenTutorial
⚙️ Backend
Backend Intro & RoadmapPython BasicsFastAPIDjangoFlask|CGoGinNode.js
🤖 AI Applied Development
Applied AI Intro & RoadmapHugging FaceLangChainLlamaIndexLLMOps|LangGraphMCPMulti-AgentAgent Evaluation
🧠 AI Core
AI Intro & RoadmapML FundamentalsLLM Fundamentals|Python AIC++|PyTorchTensorFlowJAX
🧠 AI Agent Development
Finance AI AgentLLM API ServerStock Investing AgentAIOps AI AgentEducation AI AgentCoding AI Agent
🌱 Spring Cloud
Spring Intro & RoadmapSpring Cloud GatewaySpring BootJava|Spring AISpring SecuritySpring BatchSpring JPA
🐳 DevOps
DevOps Intro & RoadmapLinuxDockerCI/CD|Kubernetes BasicsK8s AdvancedPrometheusGrafana
🧱 Infrastructure
Infrastructure Intro & RoadmapNginxRedis
☁️ Cloud
Cloud Intro & RoadmapAWSGCPAzureNCPCloudflare
🎨 Frontend
Frontend Intro & RoadmapJavaScriptTypeScript|ReactNext.js|VueNuxt|Electron
📱 Mobile
Mobile Intro & RoadmapKotlinAndroidFlutter
💾 Database
DB Intro & RoadmapCore SQLOracleMySQLPostgreSQL|MongoDBVector DB
🧪 Testing
k6JMeternGrinder
AIDevOps

Engineering AI. From Code to Production.
An engineering learning platform for building and operating AI and AI Agents

Learn

  • All Guides
  • Learning Paths
  • AI Tutorial
  • Practice
  • Books

Resources

  • AI DevOps
  • LLMOps
  • Hands-on Projects
  • Docs
  • Blog
  • Plogger
  • Open Source
  • Certification (coming soon)

Start Here

  • AI Core Roadmap
  • AI Applied Development Roadmap
  • Spring Cloud Roadmap
  • DevOps Roadmap
  • Infrastructure Roadmap

 

  • Cloud Roadmap
  • Frontend Roadmap
  • Mobile Roadmap
  • Backend Roadmap
  • Database Roadmap
© 2026 AIDevOps. All rights reserved.
Terms of ServicePrivacy PolicySitemaptestforge.kr
  1. Home
  2. Learn
  3. Backend
  4. Flask
Guide to the Python micro web framework

FL Flask Complete Guide

Visitors

Build small, explicit Python web services with Flask. Routing, structuring with Blueprints, separating configuration, SQLAlchemy integration, testing, and WSGI deployment, laid out as a real-world workflow.

  • Intermediate
  • Updated Oct 1, 2026
  • ~4 min read
  • 11 sections
  • 9 code examples
  • Web IDE lab included
FL

Flask Web IDE

Run code in the browser with nothing to install and learn through step-by-step examples.

Open the Web IDE →
MicroservicesREST APIPrototypesPython web backend

Related frameworks & environments

🐍Python Basics→⚡FastAPI→🟢Django→

Contents

0 / 14
  1. How to use this guide
  2. Architecture diagrams
  3. What is Flask?
  4. Project setup
  5. Routing
  6. Blueprint structure
  7. Separating configuration
  8. SQLAlchemy integration
  9. Testing
  10. WSGI deployment
  11. Flask design
  12. Operating standards
  13. Verification strategy
  14. Frequently asked questions
Contents 14 sections
  1. How to use this guide
  2. Architecture diagrams
  3. What is Flask?
  4. Project setup
  5. Routing
  6. Blueprint structure
  7. Separating configuration
  8. SQLAlchemy integration
  9. Testing
  10. WSGI deployment
  11. Flask design
  12. Operating standards
  13. Verification strategy
  14. Frequently asked questions

How to use this guide

How to read it

Understanding Flask as a real-world workflow

Build small, explicit Python web services with Flask. Routing, structuring with Blueprints, separating configuration, SQLAlchemy integration, testing, and WSGI deployment, laid out as a real-world workflow. Rather than listing concepts, this guide is organized so you can follow the content in the order you have to make decisions on a real project.

Key perspective

Backend / systems development

Before syntax, pin down the boundaries a request crosses: validation, processing, storage, and response.

MicroservicesREST APIPrototypesPython web backend

Architecture diagrams

To make what you read stick, it helps to capture the flow as a picture first. The two diagrams below are reference maps you can keep coming back to while learning Flask.

Learning flow

Rendering diagram…

Architecture view

Rendering diagram…

What is Flask?

When you first open Flask, the big picture matters more than individual commands. This section starts with the problems the concepts ahead were created to solve.

Flask is a Python micro web framework where you pick and assemble the features you need yourself. Because it does not include an admin, ORM, or authentication by default the way Django does, it suits small API servers, internal tools, and fast prototypes. In exchange, the larger the project grows, the more clearly you have to set the criteria for directory structure, configuration, and choice of extension libraries.
AspectFlaskDjango
PhilosophyA small, explicit corebatteries included
StructureAssembled yourself from Blueprints and extensionsProject/app structure provided out of the box
DataYour choice, such as SQLAlchemyORM included
Good fitSmall APIs, microservices, fast experimentsProduct-style services that need admin/auth/ORM

Project setup

Here you look at Project setup alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.

Flask runs right away with minimal code, but in practice it is better to start with the app factory structure. It makes testing and configuration separation easier and lets you create the same app safely in several environments.
BASH
uv venv
source .venv/bin/activate
uv pip install flask gunicorn pytest

mkdir -p app tests
touch app/__init__.py app/routes.py tests/test_app.py

flask --app app run --debug

Routing

Here you look at Routing alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.

A Flask route connects a function directly to a URL. A single file is fine for a small example, but as the API grows you should split out a service layer so the route functions do not hold all the business logic.
app/__init__.pyPYTHON
from flask import Flask, jsonify, request

def create_app() -> Flask:
    app = Flask(__name__)

    @app.get("/health")
    def health():
        return {"status": "ok"}

    @app.post("/items")
    def create_item():
        payload = request.get_json(silent=True) or {}
        name = payload.get("name")
        if not name:
            return jsonify({"error": "name is required"}), 400
        return jsonify({"id": 1, "name": name}), 201

    return app

Blueprint structure

Here you look at Blueprint structure alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.

The Blueprint is the basic tool for splitting a Flask app by feature. Dividing along boundaries such as users, auth, admin, and api makes URL registration, testing, and maintenance easier.
app/users.pyPYTHON
from flask import Blueprint, jsonify

bp = Blueprint("users", __name__, url_prefix="/users")

@bp.get("/")
def list_users():
    return jsonify([
        {"id": 1, "name": "Ada"},
        {"id": 2, "name": "Linus"},
    ])
app/__init__.pyPYTHON
from flask import Flask
from .users import bp as users_bp

def create_app() -> Flask:
    app = Flask(__name__)
    app.register_blueprint(users_bp)
    return app

Separating configuration

Here you look at Separating configuration alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.

Production code must not hard-code the secret, database url, or debug values. Build a config object by reading environment variables, and inject a separate configuration in tests.
app/config.pyPYTHON
import os

class Config:
    SECRET_KEY = os.getenv("SECRET_KEY", "dev-only")
    DATABASE_URL = os.getenv("DATABASE_URL", "sqlite:///app.db")
    JSON_SORT_KEYS = False

class TestConfig(Config):
    TESTING = True
    DATABASE_URL = "sqlite:///:memory:"

SQLAlchemy integration

Here you look at SQLAlchemy integration alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.

Flask itself does not include an ORM. Flask-SQLAlchemy connects the app context and the SQLAlchemy session conveniently. Keep models and routes separate, and be clear about when to roll back on a failed transaction.
BASH
uv pip install flask-sqlalchemy
app/models.pyPYTHON
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(120), unique=True, nullable=False)
    name = db.Column(db.String(80), nullable=False)

    def to_dict(self) -> dict:
        return {"id": self.id, "email": self.email, "name": self.name}

Testing

Here you look at Testing alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.

Flask provides a test_client out of the box. You can verify requests/responses, status codes, and JSON bodies without bringing up a network.
tests/test_app.pyPYTHON
from app import create_app

def test_health():
    app = create_app()
    client = app.test_client()

    res = client.get("/health")
    assert res.status_code == 200
    assert res.get_json() == {"status": "ok"}

def test_create_item_requires_name():
    app = create_app()
    client = app.test_client()

    res = client.post("/items", json={})
    assert res.status_code == 400
    assert "error" in res.get_json()

WSGI deployment

Here you look at WSGI deployment alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.

The development server is not for production. In production, put Nginx, Cloud Run, or a container platform in front of a WSGI server such as Gunicorn, and manage timeouts, the number of workers, the log format, and health checks.
BASH
gunicorn "app:create_app()" \
  --bind 0.0.0.0:8000 \
  --workers 2 \
  --timeout 30 \
  --access-logfile -

Tip

  • Do not run long CPU bound work directly in the Flask request thread.
  • Always set a timeout on external API calls.
  • Make request ids and structured logging the operational default.

Flask practical design

Flask practical design is a point where the options diverge. Using the table to compare what each approach is for and how it differs in operation makes later decisions much easier.

Flask gives a lot of freedom, so the boundaries of the app factory, Blueprints, config, and extension initialization have to be clear. Even when starting with one small file, it matters to decide in advance the criteria for separating route, service, model, and config.
Decision pointQuestion to askPractical guideline
BoundariesWhich parts of the Flask code are most likely to change?Separate input/output, configuration, external integrations, and the core rules.
StateWhere is state created and where does it go away?Make the owner and lifecycle of state visible in the code.
FailureWhat does the caller receive on failure?Decide the timeout, fallback, and error contract first.

Flask operating standards

This section covers Flask operating standards from a practical perspective. Instead of memorizing the concept, focus on the situations in which you would reach for it.

In operation, manage the number of Gunicorn workers, the request timeout, reverse proxy headers, structured logging, health checks, and how secrets are injected.

Tip

  • app factory
  • Blueprint boundary
  • Gunicorn timeout
  • test_client coverage

Flask verification strategy

Flask verification strategy is a point where the options diverge. Using the table to compare what each approach is for and how it differs in operation makes later decisions much easier.

Flask tests should verify test_client, a fixture-based app factory, config overrides, and the error response contract together.
Quality axisHow to verifyDefinition of done
CorrectnessAutomate the normal/failure cases.The core scenarios pass reproducibly.
Regression preventionWhen fixing a bug, leave the same case behind as a test.The same failure is not deployed again.
OperabilityCheck the logs, metrics, and alerts.There is a path for tracing the cause when a problem occurs.

Flask: frequently asked questions

When should I choose Flask?

Choose it when you want something light with only the features you pick, such as a small API or an internal tool. It provides the core, and the ORM, authentication, and validation are added as extensions, so you decide the structure. As the project grows, so does the burden of defining structure and conventions yourself.

Can I run a production server with flask run?

No. The built-in server is for development; its concurrency and stability are not suited to production. In production, run the application with a WSGI server such as Gunicorn, usually behind a reverse proxy such as Nginx.

What is a Blueprint and why use one?

A Blueprint groups routes and related code by feature. Keeping every route in one file becomes hard to manage, so you create a Blueprint per area, such as users, orders, and admin, and register them on the application. URL prefixes can also be set per Blueprint.

← Previous guideDjangoNext guide →C