"Mastering Flask: A Comprehensive Example Project Tutorial"

Building a Simple Blog with Flask: A Comprehensive Example Project

Flask, a popular Python micro web framework, is an excellent choice for building small web applications and APIs. In this guide, we'll create a simple blog project to demonstrate Flask's core features and best practices. This example project will help you understand Flask's routing, templates, forms, and database integration.

Setting Up the Project and Environment

First, ensure you have Python (3.6 or later) and pip installed. Then, install Flask and Flask-SQLAlchemy (for database operations) using pip:

pip install flask flask_sqlalchemy

Create a new folder for your project and navigate into it. Set up a virtual environment to isolate your project's dependencies:

an image of the inside of a glass bottle with labels on it and labeled in english
an image of the inside of a glass bottle with labels on it and labeled in english

python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate
pip install -r requirements.txt

Creating the Flask Application

Create a new file app.py and import the required modules:

```python from flask import Flask, render_template, request, redirect, url_for, flash from flask_sqlalchemy import SQLAlchemy from forms import BlogForm ```

Configuring the Application

Set up the Flask application and configure the database:

```python app = Flask(__name__) app.config['SECRET_KEY'] = 'your_secret_key' app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///blog.db' db = SQLAlchemy(app) ```

Defining the Database Model

Create a new file models.py to define the BlogPost model:

the anatomy of a glass bottle with labeled parts stock illustration image 518976
the anatomy of a glass bottle with labeled parts stock illustration image 518976

```python from app import db class BlogPost(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(100), nullable=False) content = db.Column(db.Text, nullable=False) date_posted = db.Column(db.DateTime, nullable=False, default=datetime.utcnow) ```

Creating Forms for User Input

Create a new file forms.py to define the BlogForm using Flask-WTF:

```python from flask_wtf import FlaskForm from wtforms import StringField, TextAreaField, SubmitField from wtforms.validators import DataRequired class BlogForm(FlaskForm): title = StringField('Title', validators=[DataRequired()]) content = TextAreaField('Content', validators=[DataRequired()]) submit = SubmitField('Post') ```

Implementing Routes and Views

Back in app.py, implement the routes for listing, creating, and updating blog posts:

```python @app.route('/') def index(): posts = BlogPost.query.order_by(BlogPost.date_posted.desc()).all() return render_template('index.html', posts=posts) @app.route('/post/new', methods=['GET', 'POST']) def new_post(): form = BlogForm() if form.validate_on_submit(): post = BlogPost(title=form.title.data, content=form.content.data) db.session.add(post) db.session.commit() flash('Your post has been created!', 'success') return redirect(url_for('index')) return render_template('create_post.html', title='New Post', form=form, legend='New Post') @app.route('/post/', methods=['GET', 'POST']) def update_post(post_id): post = BlogPost.query.get_or_404(post_id) form = BlogForm() if form.validate_on_submit(): post.title = form.title.data post.content = form.content.data db.session.commit() flash('Your post has been updated!', 'success') return redirect(url_for('index')) elif request.method == 'GET': form.title.data = post.title form.content.data = post.content return render_template('create_post.html', title='Update Post', form=form, legend='Update Post') ```

Creating Templates

Create a new folder templates and add the following files:

frasco com líquido para científico experimentar. Ciência, estudando química às escola. vetor rabisco esboço
frasco com líquido para científico experimentar. Ciência, estudando química às escola. vetor rabisco esboço

  • base.html - Base template with Bootstrap CDN and navigation bar.
  • index.html - Displays a list of blog posts.
  • create_post.html - Form for creating and updating blog posts.

Use Jinja2 syntax to extend the base template and display data in your views.

Running the Application

Add the following code to the end of app.py to run the application:

```python if __name__ == '__main__': db.create_all() app.run(debug=True) ```

Activate your virtual environment, run the application, and open your browser to http://127.0.0.1:5000/ to see your simple blog in action.

This Flask example project demonstrates core features such as routing, templates, forms, and database integration. You can further extend this project by adding user authentication, pagination, and more. Happy coding!

an illustration of a flask with the word test written in black ink on it
an illustration of a flask with the word test written in black ink on it
Flask Project Structure: Build a Scalable Web App – Real Python
Flask Project Structure: Build a Scalable Web App – Real Python
a blue liquid in a flask with bubbles on the side, transparent png and psd
a blue liquid in a flask with bubbles on the side, transparent png and psd
Python Flask Tutorial 3 - Flask Templates
Python Flask Tutorial 3 - Flask Templates
Markgraf clayworks strap flask
Markgraf clayworks strap flask
a water bottle painted in blue and white
a water bottle painted in blue and white
Tutorial — Flask Documentation (3.1.x)
Tutorial — Flask Documentation (3.1.x)
a black and white drawing of a flask
a black and white drawing of a flask
#inktober2025 #aiinktober #aiart #ink #digitalillustration #b&w #31daysdraw #kartopl9a #day15
#inktober2025 #aiinktober #aiart #ink #digitalillustration #b&w #31daysdraw #kartopl9a #day15
a red and white flask with the words first aid on it sitting on a carpet
a red and white flask with the words first aid on it sitting on a carpet
Custom Wave Hydroflask!
Custom Wave Hydroflask!
an old drawing of a bottle and its contents
an old drawing of a bottle and its contents
a bottle with a skull and crossbones on the label is shown in black and white
a bottle with a skull and crossbones on the label is shown in black and white
someone is holding up a flask with the words let's get star spangled hammered on it
someone is holding up a flask with the words let's get star spangled hammered on it
Cool Science Drawings, Easy Science Drawings, Chemistry Theme, Chemical Poster Drawing, Thermodynamics Drawing, Science Aesthetic Drawing, Chemistry Easy Drawings, Science Illustration Art, Chemistry Project Cover Page Aesthetic
Cool Science Drawings, Easy Science Drawings, Chemistry Theme, Chemical Poster Drawing, Thermodynamics Drawing, Science Aesthetic Drawing, Chemistry Easy Drawings, Science Illustration Art, Chemistry Project Cover Page Aesthetic
a flask with glitter writing on it sitting on a carpeted floor next to a bottle opener
a flask with glitter writing on it sitting on a carpeted floor next to a bottle opener
an old fashioned black oil bottle hanging from a hook
an old fashioned black oil bottle hanging from a hook
someone holding up a sticker that says bottoms up on the side of a table
someone holding up a sticker that says bottoms up on the side of a table
a blue and green glass bottle sitting on top of a table
a blue and green glass bottle sitting on top of a table
a black flask shaped like a bat with gold chain around the neck and clasp
a black flask shaped like a bat with gold chain around the neck and clasp
clipart of lab flasks
clipart of lab flasks
two hand painted flasks with words written on them, dressed up and 100 % of the shots you don't take
two hand painted flasks with words written on them, dressed up and 100 % of the shots you don't take
the painting is being made to look like he has been dressed as a super hero
the painting is being made to look like he has been dressed as a super hero