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.
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
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
dbandlogin_managerare created once, empty, before any app exists.init_appconnects 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
markdowntemplate 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), andreturn apphands the object back tomain.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:
| users | posts | comments | |
|---|---|---|---|
| Before | 5 | 10 | 45 |
After delete_admin.py | 4 | 0 | 0 |
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.
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:
| Request | With CORS(app) | Line removed |
|---|---|---|
| GET / from other.example | Allow-Origin: http://other.example | none |
| GET /static/swagger.json from other.example | Allow-Origin: http://other.example | none |
| OPTIONS /auth/login from other.example (preflight) | 200, allows DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT | 200, 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:
- Keep the docs on the same origin. Set the
serversURL inswagger.jsonto"/". On a temporary copy with that change andCORS(app)removed, the docs page opened at127.0.0.1calledhttp://127.0.0.1:5000/, and opened atlocalhostit calledhttp://localhost:5000/. Same origin both times, status 200, no allow header needed. - 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
| Finding | Where | What to ask for |
|---|---|---|
CORS(app) opens every route to every origin | app/__init__.py | remove it, or scope it to routes and origins |
| servers URL is an absolute localhost address | static/swagger.json | set it to "/" |
| hand-written docs can drift | static/swagger.json | update it with every route change |
| admin decided by email | models.py line 23 | a role or flag column |
| a script prints a password; another deletes all admin posts | root scripts | a proper admin command |
debug=True, fallback secret key, no .gitignore, misspelled requirments.txt | root | small 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.
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.
