Tutorial: Building a Flask CRUD App with TinyDB

Tutorial: Building a Flask CRUD App with TinyDB

Flask is a micro web framework for Python, known for its simplicity and flexibility.

TinyDB is a lightweight, document-oriented database that is ideal for use in small to medium-sized applications. Its simplicity and ease of use make it suitable for a variety of use cases.

Use-cases of TinyDB

Here are some common scenarios where TinyDB can be effectively used:

1. Prototyping and Development

  • Rapid Prototyping: TinyDB is excellent for quickly developing prototypes due to its minimal setup and ease of integration.
  • Testing: It can be used as a lightweight database for testing purposes during the development phase.

2. Small Applications

  • Personal Projects: Perfect for individual developers working on small-scale applications or personal projects where a full-fledged database might be overkill.
  • Desktop Applications: Suitable for desktop apps that require a local database for storing user data or configurations.

3. Education and Learning

  • Learning Database Concepts: Ideal for beginners learning about databases and CRUD operations without the complexity of setting up a traditional database system.
  • Teaching: Used in educational settings to teach students about document-oriented databases and database management.

4. Configuration Storage

  • Application Settings: Can be used to store configuration settings for applications, providing a simple way to manage user preferences and application states.
  • User Preferences: Storing user-specific settings or preferences in a lightweight and easy-to-access format.

5. IoT and Embedded Systems

  • IoT Devices: Useful for storing sensor data and configurations in Internet of Things (IoT) projects, where resources are often limited.
  • Embedded Systems: Can be integrated into embedded systems that require a simple data storage solution.

6. Data Logging

  • Logging: Effective for logging application events, error messages, or other types of logs that need to be stored and analyzed.
  • Audit Trails: Maintaining a history of changes or transactions in applications that do not require complex audit logging mechanisms.

7. Web Applications

  • Simple Web Apps: Suitable for small web applications that require a lightweight database for storing user data, session information, or other application data.
  • Static Site Generators: Can be used in static site generators for managing content and metadata.

8. Local Caching

  • Caching Data: Used for caching data locally in applications to improve performance and reduce the need for frequent data retrieval from remote servers.
  • Offline Mode: Enabling offline functionality in web and mobile applications by storing data locally and syncing with the server when online.

TinyDB is a simple database that is ideal for small applications and can be easily integrated with Flask.

This tutorial will guide you through building a simple CRUD (Create, Read, Update, Delete) application using Flask and TinyDB.

Step 1: Setting Up the Environment

Create the Project Structure:

flask_tinydb_crud/
├── app.py
├── templates/
│   ├── index.html
│   ├── add.html
│   ├── edit.html
└── static/
    └── style.css

Install Flask and TinyDB:

pip install flask tinydb

Step 2: Basic Flask App

Create Basic Template (templates/index.html):

<!DOCTYPE html>
<html>
<head>
    <title>Users</title>
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
    <h1>User List</h1>
    <a href="{{ url_for('add_user') }}">Add User</a>
    <ul>
        {% for user in users %}
            <li>{{ user.name }} - {{ user.email }} - <a href="{{ url_for('edit_user', user_id=user.doc_id) }}">Edit</a> - <a href="{{ url_for('delete_user', user_id=user.doc_id) }}">Delete</a></li>
        {% endfor %}
    </ul>
</body>
</html>

Initialize Flask App (app.py):

from flask import Flask, render_template, request, redirect, url_for
from tinydb import TinyDB, Query

app = Flask(__name__)
db = TinyDB('database.json')
User = Query()

@app.route('/')
def index():
    users = db.all()
    return render_template('index.html', users=users)

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

Step 3: Adding Users

Add User Template (templates/add.html):

<!DOCTYPE html>
<html>
<head>
    <title>Add User</title>
</head>
<body>
    <h1>Add User</h1>
    <form method="POST">
        <label for="name">Name:</label>
        <input type="text" name="name" required>
        <br>
        <label for="email">Email:</label>
        <input type="email" name="email" required>
        <br>
        <button type="submit">Add</button>
    </form>
    <a href="{{ url_for('index') }}">Back</a>
</body>
</html>

Add User Route (app.py):

@app.route('/add', methods=['GET', 'POST'])
def add_user():
    if request.method == 'POST':
        name = request.form['name']
        email = request.form['email']
        db.insert({'name': name, 'email': email})
        return redirect(url_for('index'))
    return render_template('add.html')

Step 4: Editing Users

Edit User Template (templates/edit.html):

<!DOCTYPE html>
<html>
<head>
    <title>Edit User</title>
</head>
<body>
    <h1>Edit User</h1>
    <form method="POST">
        <label for="name">Name:</label>
        <input type="text" name="name" value="{{ user.name }}" required>
        <br>
        <label for="email">Email:</label>
        <input type="email" name="email" value="{{ user.email }}" required>
        <br>
        <button type="submit">Save</button>
    </form>
    <a href="{{ url_for('index') }}">Back</a>
</body>
</html>

Edit User Route (app.py):

@app.route('/edit/<int:user_id>', methods=['GET', 'POST'])
def edit_user(user_id):
    user = db.get(doc_id=user_id)
    if request.method == 'POST':
        name = request.form['name']
        email = request.form['email']
        db.update({'name': name, 'email': email}, doc_ids=[user_id])
        return redirect(url_for('index'))
    return render_template('edit.html', user=user)

Step 5: Deleting Users

Delete User Route (app.py):

@app.route('/delete/<int:user_id>')
def delete_user(user_id):
    db.remove(doc_ids=[user_id])
    return redirect(url_for('index'))

Complete app.py Code:

from flask import Flask, render_template, request, redirect, url_for
from tinydb import TinyDB, Query

app = Flask(__name__)
db = TinyDB('database.json')
User = Query()

@app.route('/')
def index():
    users = db.all()
    return render_template('index.html', users=users)

@app.route('/add', methods=['GET', 'POST'])
def add_user():
    if request.method == 'POST':
        name = request.form['name']
        email = request.form['email']
        db.insert({'name': name, 'email': email})
        return redirect(url_for('index'))
    return render_template('add.html')

@app.route('/edit/<int:user_id>', methods=['GET', 'POST'])
def edit_user(user_id):
    user = db.get(doc_id=user_id)
    if request.method == 'POST':
        name = request.form['name']
        email = request.form['email']
        db.update({'name': name, 'email': email}, doc_ids=[user_id])
        return redirect(url_for('index'))
    return render_template('edit.html', user=user)

@app.route('/delete/<int:user_id>')
def delete_user(user_id):
    db.remove(doc_ids=[user_id])
    return redirect(url_for('index'))

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

This tutorial covers the basic setup for a Flask CRUD application using TinyDB. You can extend this application by adding more features such as user authentication, validation, and styling. For more information, refer to the Flask documentation and TinyDB documentation.








Open-source Apps

9,500+

Medical Apps

500+

Lists

450+

Dev. Resources

900+