Getting Started with Flask: A Comprehensive Example Application
Flask, a popular Python web framework, is renowned for its simplicity and flexibility. It's perfect for both small applications and large-scale web services. In this guide, we'll create a simple yet comprehensive Flask example application, covering routing, templates, forms, and database integration.
Setting Up the Environment
Before we dive into the Flask example app, ensure you have Python and pip installed. Then, install Flask using pip:
pip install flask
Creating the Flask Application
Create a new folder for your project and navigate into it. Then, create a new file named app.py and import the necessary modules:

from flask import Flask, render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired
Initializing Flask and Configuring the Database
Initialize Flask and configure the database. For simplicity, we'll use an SQLite database:
app = Flask(__name__)
app.config['SECRET_KEY'] = 'your_secret_key'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///example.db'
db = SQLAlchemy(app)
Creating the Database Model
Let's create a simple model for a 'Message' with 'author' and 'content' fields:
class Message(db.Model):
id = db.Column(db.Integer, primary_key=True)
author = db.Column(db.String(50), nullable=False)
content = db.Column(db.Text, nullable=False)
def __repr__(self):
return f''
Creating the Flask Form
Now, let's create a form for adding new messages using Flask-WTF:

class MessageForm(FlaskForm):
author = StringField('Author', validators=[DataRequired()])
content = StringField('Content', validators=[DataRequired()])
submit = SubmitField('Submit')
Defining Routes and Views
Define routes for displaying messages, adding new messages, and handling form submissions:
@app.route('/')
def index():
messages = Message.query.all()
return render_template('index.html', messages=messages)
@app.route('/add', methods=['GET', 'POST'])
def add_message():
form = MessageForm()
if form.validate_on_submit():
message = Message(author=form.author.data, content=form.content.data)
db.session.add(message)
db.session.commit()
return redirect(url_for('index'))
return render_template('add_message.html', form=form)
Creating Templates
Create two HTML templates, index.html and add_message.html, in a folder named templates:
index.html: Display a list of messages and a link to add a new message.add_message.html: Display the form for adding a new message.
Running the Flask Application
Finally, run the application using the following code:

if __name__ == '__main__':
db.create_all()
app.run(debug=True)
Open your browser and navigate to






















