Getting Started with Flask: A Guide for Beginners

Joël-Steve N.
3 min readJun 11, 2024

--

Flask is a lightweight micro-framework in Python that allows you to quickly and easily create web applications. It is particularly appreciated for its simplicity and flexibility. In this article, we will see how to get started with Flask, step by step, with code examples to illustrate each concept.

1. Installing Flask

To get started, you need to install Flask. It is recommended to create a virtual environment for your project to isolate dependencies.

# Create a virtual environment
python -m venv venv

# Activate the virtual environment

# On Windows
venv\Scripts\activate

# On MacOS/Linux
source venv/bin/activate

# Install Flask
pip install Flask

2. Your First Flask Application

Let’s create a file named app.py and write our first Flask application.

from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
return "Hello, Flask!"

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

To run the application, use the following command:

python app.py

You should see a message indicating that the server is running at http://127.0.0.1:5000/. Open this link in your browser, and you will see "Hello, Flask!".

3. Project Structure

For larger projects, it is better to organize your code more systematically. Here is an example project structure:

my_flask_app/

├── app/
│ ├── __init__.py
│ ├── routes.py
│ ├── models.py
│ └── templates/
│ └── home.html

├── venv/

├── config.py
├── app.py
└── requirements.txt
  • app/: Contains your application code.
  • templates/: Contains HTML files.
  • config.py: Configuration file.
  • app.py: Entry point of the application.

4. Adding Routes and Templates

Let’s add a new route and an HTML template.

app/routes.py:

from flask import render_template
from app import app

@app.route('/')
def home():
return render_template('home.html')

app/__init__.py:

from flask import Flask

app = Flask(__name__)

from app import routes

app/templates/home.html:

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Home Page</title>
</head>
<body>
<h1>Welcome to Flask!</h1>
</body>
</html>

app.py:

from app import app

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

5. Handling Forms

Flask also makes it easy to handle forms. For this, we will use the Flask-WTF extension.

pip install Flask-WTF

app/forms.py:

from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired

class MyForm(FlaskForm):
name = StringField('Name', validators=[DataRequired()])
submit = SubmitField('Submit')

app/routes.py:

from flask import render_template, flash, redirect, url_for
from app import app
from app.forms import MyForm

@app.route('/', methods=['GET', 'POST'])
def home():
form = MyForm()
if form.validate_on_submit():
flash(f'Form submitted with name: {form.name.data}')
return redirect(url_for('home'))
return render_template('home.html', form=form)

app/templates/home.html:

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Home Page</title>
</head>
<body>
<h1>Welcome to Flask!</h1>
<form method="POST" action="">
{{ form.hidden_tag() }}
<p>
{{ form.name.label }}<br>
{{ form.name(size=32) }}<br>
{{ form.submit() }}
</p>
</form>
{% with messages = get_flashed_messages() %}
{% if messages %}
<ul>
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
</body>
</html>

6. Connecting to a Database

Flask works well with SQLAlchemy for database management.

pip install Flask-SQLAlchemy
pip install Flask-Migrate

config.py:

import os

basedir = os.path.abspath(os.path.dirname(__file__))

class Config:
SECRET_KEY = os.environ.get('SECRET_KEY') or 'you-will-never-guess'
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \
'sqlite:///' + os.path.join(basedir, 'app.db')
SQLALCHEMY_TRACK_MODIFICATIONS = False

app/__init__.py:

from flask import Flask
from config import Config
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate

app = Flask(__name__)
app.config.from_object(Config)

db = SQLAlchemy(app)
migrate = Migrate(app, db)

from app import routes, models

app/models.py:

from app import db

class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(64), index=True, unique=True)
email = db.Column(db.String(120), index=True, unique=True)

def __repr__(self):
return f'<User {self.username}>'

To create the database, run:

flask db init
flask db migrate -m "users table"
flask db upgrade

To run again the application after, you can use the following command:

python app.py

requirements.txt:

alembic==1.13.1
blinker==1.8.2
click==8.1.7
colorama==0.4.6
Flask==3.0.3
Flask-Migrate==4.0.7
Flask-SQLAlchemy==3.1.1
Flask-WTF==1.2.1
greenlet==3.0.3
itsdangerous==2.2.0
Jinja2==3.1.4
Mako==1.3.5
MarkupSafe==2.1.5
SQLAlchemy==2.0.30
typing_extensions==4.12.2
Werkzeug==3.0.3
WTForms==3.1.2

Conclusion

Flask is a powerful and flexible tool for creating web applications in Python. With this guide, you have learned how to install Flask, create a basic application, organize your project, handle forms, and connect your application to a database. With these basics, you are ready to explore further and develop robust and high-performing web applications. Happy coding!

--

--

Joël-Steve N.

Chief Technology Officer | Community Manager | Backend Developper (Python, Javascript, Java) | Motivational Coach