Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Python
  • Python for AI: The Five Tools You Actually Need
  • Thinking Like a Python Architect in an AI-First World
  • Your First Python Program: print, Comments, sep and end
  • Set Up PyCharm for Python: Install, First Project and First Run
  • Run a Python File and Read the Error: Tracebacks in Three Steps
  • Python Data Types, Variables and Strings: Indexing, Slicing and f-strings
  • Python Operators: Arithmetic, Comparison, Logical, Membership, Identity and Precedence
  • Python Conditionals and Loops: if/elif/else, for, while, break and continue
  • Looping Over Real Data in Python: Dicts, Lists of Dicts, enumerate and zip
  • Checking AI-Written Python Code: A Six-Step Habit That Finds Three Hidden Faults
  • Python Basics Practice: Report Card, Shopping Cart and Password Checker from a Prompt
  • Python Functions: Parameters, Return, Scope (LEGB), *args and **kwargs
  • Type Hints on Python Functions: Parameters, Returns, None and Collections
  • Python lambda, map, filter, Modules and Packages (with pip and venv)
  • Python Functions Practice: Bonus Calculator, Product Pipeline and a Math Package
  • Python Lists, Tuples, Sets and Dicts, Plus Type Hints on Variables
  • Python Comprehensions: List, Dict, Set and Generator Expressions, Read as Loops
  • Python Class Methods, Static Methods and Properties: What Each One Receives
  • Python Classes and Objects: __init__, self and PEP 8 Names
  • Python Inheritance and Polymorphism: super(), Overriding and Duck Typing
  • Python Multiple Inheritance, the MRO and Mixins
  • Python Encapsulation and Special Methods: Underscores, __str__, __add__ and __len__
  • Python Composition, Abstract Classes and Dataclasses
  • Python OOP Practice: Design a Bank, an Employee System and a Library
  • Set Up a Python AI Project with uv, VS Code and an API Key in .env
  • uv and pyproject.toml: Start, Add, Run and Rebuild a Python Project
  • Python try and except Basics: Catch an Error and Keep Going
  • Read and Write a File in Python: open, with, Modes and Encoding
  • Python Custom Exceptions and Advanced Error Handling: raise, raise from and the Call Stack
  • Python Logging and Debugging: Levels, Handlers, logger.exception and breakpoint()
  • Python File Modes, pathlib and Context Managers: x, r+, rb, Path and __enter__/__exit__
  • Python CSV, JSON and Large Files: csv, json, yield Pipelines, tomllib and pickle
  • Python Practice: Build a Log File Analyzer and a File Organizer
  • Python Project Structure for AI-Assisted Development: Packages, config.py and AGENTS.md
  • Regular Expressions in Python: search, findall, Groups and Greedy vs Lazy
  • Testing Python Code with pytest: assert, parametrize, fixtures and pytest.raises
  • Async Python: async def, await, asyncio.gather and the Blocking Trap
  • Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
  • One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask
  • Getting Started with Flask: Routes, Jinja2 Templates and WSGI in One Small App
  • Your First Flask App with uv: From an Empty Folder to a Page in Debug Mode
  • Flask Routes, Templates and url_for: Converters, Forms, Redirects and the Signed Session
  • Flask-SQLAlchemy Models and Flask-Migrate: From a Python Class to a Real Table
  • Building a Blog with an AI Coding Agent: Plan Mode, a Master Prompt and the First Review
  • Handing a Figma Design to an AI Agent: Compare the Files, Then Review the Change
  • Inside a Flask Blog: The App Factory, Blueprints, the Instance Folder and CORS Done Right
  • How a Request and a Login Flow Through a Flask Blog: Flask-Login, CSRF and the Signed Session
  • Testing a Flask Blog with pytest: A Test App from the Factory, Fixtures and the Test Client
  1. Blog
  2. /
  3. Python
  4. /
  5. Advanced Python

Inside a Flask Blog: The App Factory, Blueprints, the Instance Folder and CORS Done Right

A folder-by-folder tour of an AI-built Flask blog: main.py and the app object, config from .env, create_app, four blueprints, the models, the instance folder, two risky admin scripts, a hand-written swagger.json that drifts, and why CORS(app) opened every route to every site.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Advanced Python

What you will learn

  • Tell apart the app package and the app object that create_app returns
  • Read an application factory and say what each line plugs in
  • Find each piece of a Flask project: config, blueprints, models, templates, static, instance
  • Explain what CORS is, why CORS(app) is the wrong fix and how to open CORS narrowly

Before you start

  • Flask routes, templates and url_for
  • Flask-SQLAlchemy models

An AI agent built this blog, and then gave it a design. Now you're the architect, and you need to know where each piece sits. When a page breaks, or you want to change one, you should know which file to open. So let's open every folder of the designed Flask blog (Flask 3.1.3, SQLite) and see what each file does, plus the review points we found on the way.

The tree at a glance

The project splits into four groups: the root with main.py, config.py, .env and requirments.txt; the app package with __init__.py, models.py, routes, templates and static; the instance folder with blog.db; and three scripts: seed_data.py, reset_admin_password.py and delete_admin.py. Root main.py (starts the app) config.py (settings) .env, .env.example requirments.txt (typo) app/ (a Python package) __init__.py: create_app models.py: User, Post, Comment routes/ auth.py, blog.py, admin.py templates/ base.html, index.html, post_detail.html, auth/, admin/ static/ css/style.css swagger.json (hand-written) instance/ blog.db (SQLite) Scripts at the root seed_data.py reset_admin_password.py delete_admin.py
Four groups. The real code lives in the app package; the database file lives in instance.

Remember the LEGO picture from Getting started with Flask: a small core, and the pieces you add. Here the agent added pieces for the database, logins, forms, the docs and CORS. (The Django version of this blog gets the same tour in the Django project folder structure.)

main.py: one word, two meanings

from app import create_app

app = create_app()

if __name__ == '__main__':
    app.run(debug=True)

Six lines, with one idea that's easy to get wrong. On the import line, app is the folder: it has an __init__.py, so Python treats it as a package, and we import create_app from it. On the left of the equals sign, app is an object, the one create_app built and returned.

python -c "import main; print(type(main.app)); print(main.app.name)"
<class 'flask.app.Flask'>
app

A Flask object, not a folder. The last two lines run the development server only when you start the file directly with python main.py. With flask --app main run, Flask finds the variable app instead. debug=True is fine on your machine, but it's written into the code, so it's a review point.

config.py and the .env file

import os
from dotenv import load_dotenv

basedir = os.path.abspath(os.path.dirname(__file__))
load_dotenv(os.path.join(basedir, '.env'))


class Config:
    SECRET_KEY = os.environ.get('SECRET_KEY') or 'change-me'
    SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \
        'sqlite:///' + os.path.join(basedir, 'blog.db')
    SQLALCHEMY_TRACK_MODIFICATIONS = False
    ADMIN_EMAIL = os.environ.get('ADMIN_EMAIL') or '<admin-email>'

load_dotenv reads .env into the environment. SECRET_KEY signs the session cookie. DATABASE_URL in .env is sqlite:///blog.db, so the whole database is one file. ADMIN_EMAIL matters in the models.

Each line has a fallback after or. Without a secret key in the environment, Flask uses a fixed text that anyone can read in this file. On a public server, always set your own. .env.example lists the same three names with placeholder values; it's the template you copy, and it's safe to share.

create_app, the application factory

A function that builds and returns the app is called an application factory. It's the heart of the project, in app/__init__.py:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from flask_swagger_ui import get_swaggerui_blueprint
from flask_cors import CORS
from config import Config
import markdown as md
from markupsafe import Markup

db = SQLAlchemy()
login_manager = LoginManager()

# Swagger UI configuration
SWAGGER_URL = '/api/docs'
API_URL = '/static/swagger.json'


def create_app(config_class=Config):
    app = Flask(__name__)
    app.config.from_object(config_class)

    # Enable CORS for all routes
    CORS(app)

    db.init_app(app)
    login_manager.init_app(app)
    login_manager.login_view = 'auth.login'
    login_manager.login_message = 'Please log in to access this page.'

    # Register markdown filter for templates
    @app.template_filter('markdown')
    def markdown_filter(text):
        return Markup(md.markdown(text, extensions=['fenced_code', 'tables', 'nl2br']))

    # Register Swagger UI blueprint
    swaggerui_blueprint = get_swaggerui_blueprint(
        SWAGGER_URL,
        API_URL,
        config={
            'app_name': "Flask Blog API"
        }
    )
    app.register_blueprint(swaggerui_blueprint, url_prefix=SWAGGER_URL)

    from app.routes import auth, blog, admin
    app.register_blueprint(auth.bp)
    app.register_blueprint(blog.bp)
    app.register_blueprint(admin.bp)

    with app.app_context():
        db.create_all()

    return app
  • db and login_manager are created once, empty, before any app exists. init_app connects them later.
  • app.config.from_object(config_class) loads the settings.
  • CORS(app): keep this line in mind. We come back to it at the end.
  • A markdown template filter turns a post's text into HTML.
  • Four blueprints: the Swagger docs, then auth, blog and admin.
  • db.create_all() makes missing tables (it can't change existing ones; see models and migrations), and return app hands the object back to main.py.

Every call builds a fresh object. That's handy for tests, because a test can build its own app with its own settings, as in Testing the Flask blog with pytest.

Blueprints and routes

app/routes has three files, and each starts with a Blueprint. The top of blog.py:

bp = Blueprint('blog', __name__)


class CommentForm(FlaskForm):
    content = TextAreaField('Comment', validators=[DataRequired()])
    submit = SubmitField('Post Comment')


@bp.route('/')
def index():
    page = request.args.get('page', 1, type=int)
    posts = Post.query.order_by(Post.created_at.desc()).paginate(
        page=page, per_page=10, error_out=False)
    return render_template('index.html', posts=posts)

auth has the prefix /auth and admin has /admin. flask --app main routes lists thirteen rules, including these:

Endpoint              Methods    Rule
--------------------  ---------  ------------------------------
admin.create_post     GET, POST  /admin/post/create
admin.dashboard       GET        /admin/
admin.delete_comment  POST       /admin/comment/delete/<int:id>
admin.delete_post     POST       /admin/post/delete/<int:id>
admin.edit_post       GET, POST  /admin/post/edit/<int:id>
auth.login            GET, POST  /auth/login
auth.logout           GET        /auth/logout
auth.register         GET, POST  /auth/register
blog.index            GET        /
blog.post_detail      GET, POST  /post/<slug>
static                GET        /static/<path:filename>

The other two rules belong to the swagger_ui blueprint at /api/docs. Each endpoint is the blueprint name, a dot and the function name. How a login travels through these routes has its own article: How a request and a login flow through the Flask blog.

models.py

Each class becomes a table: User (name, email, password hash; the password itself is never stored), Post (title, slug, content, author) and Comment (links a user to a post). After the seed script ran, the database held 5 users, 10 posts and 45 comments.

Now look at line 23, inside User:

    def is_admin(self, admin_email):
        return self.email == admin_email

Whoever registers with the admin email becomes the admin. There's no role column. It works, but it's a review point.

Templates, static and instance

base.html is the frame with the header, menu and footer; index.html and post_detail.html fill it. templates/auth holds login and register, and templates/admin holds the dashboard and the two post forms, so the folders match the blueprints. static has one big CSS file from the design, plus swagger.json, the source of the docs page.

The instance folder holds files for this copy of the app, not the code. Flask-SQLAlchemy put blog.db there. seed_data.py clears the data and creates one admin, four regular users and ten posts with comments. All seeded users are made-up test accounts.

The two admin scripts

reset_admin_password.py finds the admin by the configured email, asks for a new password (pressing Enter sets a default) and then prints the new password on the screen. Fine for a test user; a real password should never be printed.

delete_admin.py removes the admin so you can register again with that email. Look at what it really did:

userspostscomments
Before51045
After delete_admin.py400

All ten posts belonged to the admin, so the cascade took them, and every comment on them too. Ask why these scripts are needed at all, and whether a role column would remove the need.

A few more files at the root: the package list is named requirments.txt, missing an "e", so tools that look for requirements.txt won't find it. Every package in it is pinned (Flask 3.1.3, Flask-SQLAlchemy, Flask-Login, Flask-WTF, flask-swagger-ui, flask-cors and more). And there's no .gitignore, so .env with the secret key, and the database, could end up in git.

The Swagger docs drift

The swagger UI blueprint serves the docs page at /api/docs, and the page reads /static/swagger.json. That file is written by hand: 548 lines, and nothing builds it from the routes. Comparing it with the real routes, it documents 10 paths and the app has 10. They match today.

Then, on a temporary copy, one route was added, /about. The app had 11, the docs still had 10, and /about was missing. That's drift. Whenever a route changes, ask the agent to update swagger.json too.

What CORS is

When this project was first built, a "Try it out" call on the docs page failed with a CORS error, and the fix was CORS(app). Here's what really happened.

An origin is three things together: the scheme, the host and the port. http://127.0.0.1:5000 is one origin. http://localhost:5000 is a different origin, even though it's the same server on your machine.

CORS, Cross-Origin Resource Sharing, is a rule in the browser. When a page from one origin calls another origin, the browser only lets the page read the answer if the server says yes, with an Access-Control-Allow-Origin header. When a page calls its own origin, the browser doesn't ask.

The servers line in swagger.json says http://localhost:5000. So a docs page opened at 127.0.0.1 sends its calls to localhost: a different origin. That's where the error came from.

A docs page loaded from 127.0.0.1:5000 calls localhost:5000 because swagger.json names that server. The browser treats it as cross-origin and blocks the answer unless the server sends Access-Control-Allow-Origin. With servers set to slash, the call stays on the same origin and no CORS is needed. As shipped: servers = "http://localhost:5000" Docs page from 127.0.0.1:5000 API call to localhost:5000 different origin browser needs Allow-Origin Fixed: servers = "/" Docs page from any address API call to the same origin same origin no CORS needed
The real cause was the server address in swagger.json, not a missing CORS setting.

Why CORS(app) is the wrong fix

With no options, CORS(app) adds the allow header to every route, for every origin. The lecture tested it with a made-up site, http://other.example:

RequestWith CORS(app)Line removed
GET / from other.exampleAllow-Origin: http://other.examplenone
GET /static/swagger.json from other.exampleAllow-Origin: http://other.examplenone
OPTIONS /auth/login from other.example (preflight)200, allows DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT200, no allow headers

One line told every website that it may call every route of the blog. The error went away, but the real cause, the wrong server address, was still there. The blog's own pages don't need CORS at all, because they only call their own origin.

CORS done right

Two steps:

  1. Keep the docs on the same origin. Set the servers URL in swagger.json to "/". On a temporary copy with that change and CORS(app) removed, the docs page opened at 127.0.0.1 called http://127.0.0.1:5000/, and opened at localhost it called http://localhost:5000/. Same origin both times, status 200, no allow header needed.
  2. If a separate front end really needs this app, open CORS narrowly. Name the routes and name the origins:
CORS(app, resources={r"/static/swagger.json": {"origins": "http://localhost:5000"}})

With that line, only GET /static/swagger.json from http://localhost:5000 got the allow header. The made-up site got nothing, and the home page got nothing either. Allow the smallest set of routes, for the origins you trust.

The review list

FindingWhereWhat to ask for
CORS(app) opens every route to every originapp/__init__.pyremove it, or scope it to routes and origins
servers URL is an absolute localhost addressstatic/swagger.jsonset it to "/"
hand-written docs can driftstatic/swagger.jsonupdate it with every route change
admin decided by emailmodels.py line 23a role or flag column
a script prints a password; another deletes all admin postsroot scriptsa proper admin command
debug=True, fallback secret key, no .gitignore, misspelled requirments.txtrootsmall fixes, one at a time

A sample prompt for an agent, in Role, Context, Task and Format: Role: a Flask reviewer. Context: this blog and its review list. Task: fix the CORS setup and the Swagger server address, one change at a time. Format: a short diff per change. Then read every line of the diff before you accept it.

Try it yourself

Add a route to blog.py, run flask --app main routes, and check whether swagger.json lists it. It won't, until you or the agent add it.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in Python · 46 of 48

Previous
Handing a Figma Design to an AI Agent: Compare the Files, Then Review the Change
Next post
How a Request and a Login Flow Through a Flask Blog: Flask-Login, CSRF and the Signed Session

Related course on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Related posts

Regular Expressions in Python: search, findall, Groups and Greedy vs Lazy

A regex is a stencil for a shape of text. Watch it slide and back up, build patterns with \d, \w, quantifiers and anchors, use search, findall, sub and split, pull parts out with named groups, and test AI-written patterns on edge cases.

Testing Python Code with pytest: assert, parametrize, fixtures and pytest.raises

A test is a line on a checklist your code must pass every time. Catch a discount bug with assert, read the E lines in the pytest report, cover cases with parametrize, share a cart with a fixture, test errors with pytest.raises, and see why a passing test from an AI tool can prove nothing.

Async Python: async def, await, asyncio.gather and the Blocking Trap

One cook, several pots: async lets one program wait on many things at once. See what async def and await really do, why three awaits in a row are no faster, how gather and TaskGroup bring 0.6 seconds down to 0.2, and the two mistakes that catch almost everyone.

Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose

One small project lists two blog posts three times: as a Django view, a Flask route and a FastAPI endpoint. See each shape with its real output, what each framework includes, and a three-question way to choose.

On this page

  • The tree at a glance
  • main.py: one word, two meanings
  • config.py and the .env file
  • create_app, the application factory
  • Blueprints and routes
  • models.py
  • Templates, static and instance
  • The two admin scripts
  • The Swagger docs drift
  • What CORS is
  • Why CORS(app) is the wrong fix
  • CORS done right
  • The review list
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.