Home » Flask » How to Build a Flask CRUD Web App: A Comprehensive Guide with Code Examples and Best Practices | NileshBlog

How to Build a Flask CRUD Web App: A Comprehensive Guide with Code Examples and Best Practices | NileshBlog

Flask is a web framework based on Python that allows you to build web applications easily and quickly. CRUD stands for Create, Read, Update, and Delete, which are the four basic functions of persistent storage. In this article, we will learn how to build a Flask CRUD web app.

Web App How to Build a Flask CRUD Web App

How to Build a Flask CRUD Web App

Step To Build A fledge CRUD app

  • Setting up the project
  • Creating the database
  • Building the user interface
  • Implementing CRUD operations
  • Testing the app

Build Your Own Instagram Clone Web App with HTML , CSS and JavaScript

Setting up the project

The first step is to set up the project. To do this, you need to install Flask and other necessary packages. You can install Flask using pip. Open a terminal and type the following command:

pip install flask

In addition to Flask, we also need to install Flask SQLAlchemy, which is a package that provides a way to work with databases using Flask. Type the following command to install it:

pip install flask_sqlalchemy

Now that you have installed the required packages, create a new directory for your project and navigate to it in the terminal. Then, create a new file called app.py. This is where we will write our Flask application.

Creating the database

Before we start building the user interface, we need to create a database to store the data. We will be using SQLite for our database. SQLite is a lightweight database that is easy to use and does not require any configuration.

To create the database, we need to define a model for our data. In this example, we will create a model for a book. Open app.py and add the following code:

from flask import Flask

from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///books.db'

db = SQLAlchemy(app)

class Book(db.Model):

    id = db.Column(db.Integer, primary_key=True)

    title = db.Column(db.String(80), nullable=False)

    author = db.Column(db.String(80), nullable=False)

    genre = db.Column(db.String(80), nullable=False)

Restsharp Picnob Response as forbidden

In this code, we import Flask and SQLAlchemy. We then create a Flask app and configure the database to use SQLite. We also create a model called Book with three columns: id, title, author, and genre.

To create the database, we need to run the following commands in the terminal:

from app import db

db.create_all()

exit()

This will create a new file called books.db in the same directory as app.py.

Building the user interface

Now that we have set up the database, we can start building the user interface. We will create a simple HTML form that allows users to add, update, and delete books. To do this, we will use Flask’s built-in templates and render_template function.

Create a new directory called templates and add a new file called index.html. This file will contain the HTML code for our form. Add the following code:

<!DOCTYPE html>

<html>

<head>

<title>Flask CRUD Example</title>

</head>

<body>

<h1>Books</h1>

<table>

<tr>

<th>Title</th>

<th>Author</th>

<th>Genre</th>

<th>Action</th>

</tr>

{% for book in books %}

<tr>

<td>{{ book.title }}</td>

<td>{{ book.author }}</td>

<td>{{ book.genre }}</td>

<td>

<a href="/edit/{{ book.id }}">Edit</a>

<a href="/delete/{{ book.id }}">Delete</a>

</td></tr>

</table>

<form method="POST" action="/add">

<h2>Add a Book</h2>

<label for="title">Title:</label>

<input type="text" name="title" required><br>

php

Copy code

<label for="author">Author:</label>

<input type="text" name="author" required><br>

<label for="genre">Genre:</label>

<input type="text" name="genre" required><br>

<input type="submit" value="Add">

</form>

</body>

</html>

“`

In this code, we define an HTML form that displays a table of all the books in the database. We use Flask’s template engine to iterate over the books and display them in the table.

We also add a form to add a new book to the database. This form sends a POST request to the server when the user clicks the “Add” button.

Implementation

Now that we have the user interface, we can start implementing the CRUD operations. We will use Flask’s routing system to define routes for each operation.

To create a new book, we need to define a route that handles the POST request from the form. Add the following code to app.py:

@app.route('/add', methods=['POST'])

def add():

    title = request.form['title']

    author = request.form['author']

    genre = request.form['genre']

    book = Book(title=title, author=author, genre=genre)

    db.session.add(book)

    db.session.commit()

    return redirect('/')

In this code, we define a new route called “/add” that handles the POST request from the form. We extract the data from the form and create a new Book object with the data. We then add the book to the database and commit the changes. Finally, we redirect the user back to the index page.

To edit a book, we need to define a route that handles the GET request for the edit page and a route that handles the POST request to update the book. Add the following code to app.py:

@app.route('/edit/<int:id>', methods=['GET'])

def edit(id):

    book = Book.query.get(id)

    return render_template('edit.html', book=book)

@app.route('/update/<int:id>', methods=['POST'])

def update(id):

    book = Book.query.get(id)

    book.title = request.form['title']

    book.author = request.form['author']

    book.genre = request.form['genre']

    db.session.commit()

    return redirect('/')

In this code, we define a route called “/edit/int:id” that handles the GET request for the edit page. so query the database for the book with the given ID and pass it to the template. We then render the template “edit.html” with the book data.

i can also define a route called “/update/int:id” that handles the POST request to update the book. We extract the data from the form and update the book object and then commit the changes to the database and redirect the user back to the index page.

To delete a book, we need to define a route that handles the GET request to confirm the deletion and a route that handles the POST request to delete the book. Add the following code to app.py:

@app.route('/delete/<int:id>', methods=['GET'])

def delete(id):

    book = Book.query.get(id)

    return render_template('delete.html', book=book)

@app.route('/remove/<int:id>', methods=['POST'])

def remove(id):

    book = Book.query.get(id)

    db.session.delete(book)

    db.session.commit()

    return redirect('/')

In this code, we define a route called “/delete/int:id” that handles the GET request to confirm the deletion. so query the database for the book with the given ID and pass it to the template , then render the template “delete.html” with the book data.

We also define a route called “/remove/int:id” that handles the POST request to delete the book. the query the database for the book with the given ID and delete it. We then commit the changes to the database and redirect the user back to the index page.

Styling the web app

Now that we have the functionality of the web app working, let’s add some style to it. We will use Bootstrap to add some basic styling to the pages.

To use Bootstrap, we need to include its CSS and JavaScript files in our HTML templates. Download the Bootstrap files from its official website and add them to the static folder in our Flask app.

We also need to update our HTML templates to include the Bootstrap classes. Here’s the updated index.html template:

<!DOCTYPE html>

<html>

<head>

<title>Book Inventory</title>

<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='css/bootstrap.min.css') }}">

<script type="text/javascript" src="{{ url_for('static', filename='js/bootstrap.min.js') }}"></script>

</head>

<body>

<div class="container">

<h1>Book Inventory</h1>

<table class="table table-striped">

<thead>

<tr>

<th>Title</th>

<th>Author</th>

<th>Genre</th>

<th>Actions</th>

</tr>

</thead>

<tbody>

{% for book in books %}

<tr>

<td>{{ book.title }}</td>

<td>{{ book.author }}</td>

<td>{{ book.genre }}</td>

<td>

<a href="/edit/{{ book.id }}" class="btn btn-primary">Edit</a>

<a href="/delete/{{ book.id }}" class="btn btn-danger">Delete</a>

</td>

</tr>

{% endfor %}

</tbody>

</table>

<form method="POST" action="/add">

<h2>Add a Book</h2>

<label for="title">Title:</label>

<input type="text" name="title" required class="form-control"><br>

<label for="author">Author:</label>

<input type="text" name="author" required class="form-control"><br>

<label for="genre">Genre:</label>

<input type="text" name="genre" required class="form-control"><br>

<input type="submit" value="Add" class="btn btn-success">

</form>

</div>

</body>

</html>

In this code, we add the Bootstrap CSS and JavaScript files to the HTML head. he also update the table classes to use Bootstrap’s “table” and “table-striped” classes.

We update the form inputs to use Bootstrap’s “form-control” class, and we update the submit button to use the “btn” and “btn-success” classes.

We also update the edit.html and delete.html templates to use Bootstrap’s classes for styling.

Conclusion

In this article, we learned how to build a CRUD web app using Flask. I started by creating a database using SQLAlchemy and defining a Book model. We then created the user interface using HTML and Flask’s template engine.

We implemented the CRUD operations by defining routes

for creating, reading, updating, and deleting books. We used SQLAlchemy to query the database and update the book data.

We also added some basic styling to the web app using Bootstrap.

Now that you have learned how to build a basic Flask web app with CRUD functionality, you can build more complex applications using these concepts. You can add user authentication, search functionality, and other features to your web app.

FAQ

Q: What is Flask?

A: Flask is a lightweight web framework for Python. It is used to build web applications quickly and easily.

Q: What is CRUD?

A: CRUD stands for Create, Read, Update, and Delete. It is a set of basic operations that can be performed on data in a database.

Q: What is SQLAlchemy?

A: SQLAlchemy is an Object-Relational Mapping (ORM) library for Python. It provides a set of high-level API for accessing relational databases.

Q: What is Bootstrap?

A: Bootstrap is a popular HTML, CSS, and JavaScript framework for building responsive and mobile-first websites.

Q: Can I use a different database with Flask?

A: Yes, Flask supports many different databases through various extensions. You can use MySQL, PostgreSQL, SQLite, and many others.

Q: How do I deploy my Flask app to a production server?

A: There are many ways to deploy a Flask app to a production server, such as using a web server like Apache or Nginx, or using a Platform-as-a-Service (PaaS) provider like Heroku or Google Cloud.

About the Author

This article was written by Technilesh, a software engineer and blogger at NileshBlog. nilesh has experience in building web applications using Python, Flask, and other technologies.

References

Flask documentation: https://flask.palletsprojects.com/

SQLAlchemy documentation: https://docs.sqlalchemy.org/

Bootstrap documentation: https://getbootstrap.com/

Python documentation: https://www.python.org/doc/

Backlinks:

Technilesh: https://technilesh.com/

NileshBlog: https://nileshblog.com/

These are the official websites of the author and their blog, respectively.

Leave a Reply