Building Your First Full Flask Website from Scratch
Flask is often called a "micro-framework" — but don't let that fool you. It's powerful enough to run Instagram at scale and simple enough to learn in a weekend. In this guide we'll go from zero to a real multi-page site.
Prerequisites
- Python 3.10+
- Basic knowledge of HTML & Python
1. Project Setup
mkdir mysite && cd mysite
python -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install flask
Create this structure:
mysite/
app.py
templates/
base.html
index.html
about.html
static/
css/
style.css
2. The Application Factory
# app.py
from flask import Flask, render_template
def create_app():
app = Flask(__name__)
app.secret_key = "change-me-in-production"
@app.route("/")
def index():
posts = [
{"title": "Hello World", "body": "My first post."},
{"title": "Flask is great", "body": "Here is why..."},
]
return render_template("index.html", posts=posts)
@app.route("/about")
def about():
return render_template("about.html")
return app
app = create_app()
if __name__ == "__main__":
app.run(debug=True)
3. The Base Template
<!-- templates/base.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{% block title %}MySite{% endblock %}</title>
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
</head>
<body>
<nav>
<a href="{{ url_for('index') }}">Home</a>
<a href="{{ url_for('about') }}">About</a>
</nav>
<main>
{% block content %}{% endblock %}
</main>
</body>
</html>
4. Adding a SQLite Database
import sqlite3
from flask import g
def get_db():
if 'db' not in g:
g.db = sqlite3.connect('site.db')
g.db.row_factory = sqlite3.Row
return g.db
@app.teardown_appcontext
def close_db(e=None):
db = g.pop('db', None)
if db: db.close()
5. Running & Deploying
flask run --debug # development
gunicorn app:app # production
Congratulations — you just built a real Flask website. Next steps: add user authentication (see our next post!), a contact form, and deploy to Railway or Render.
0 Comments
Join the conversation
No comments yet. Be the first!