CRUD Operations using Additional Features in Flask

CRUD Operations using Additional Features in Flask

Introduction

When building web applications, we often need to perform four essential operations: Create, Read, Update, and Delete (CRUD). These operations allow us to manage data efficiently.

Flask, a lightweight Python web framework, provides simple yet powerful tools to implement CRUD operations. In this blog, we will explore how to enhance these operations using additional Flask features like request handling, redirects, and dynamic URLs.


Setting Up Flask

Before we dive into CRUD operations, let’s set up a basic Flask application.

from flask import Flask, render_template, request, redirect, url_for

app = Flask(__name__)

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

Now, let’s explore CRUD operations one by one.


1. Create Operation (Adding Data)

To create a new entry, we usually need an HTML form where users can input data.

HTML Form

<form method="POST" action="/create">
    <input type="text" name="name" placeholder="Enter Name">
    <input type="submit" value="Create">
</form>
        

Flask Route

@app.route('/create', methods=['GET', 'POST'])
def create():
    if request.method == 'POST':
        name = request.form['name']
        # Add logic to store 'name' in the database
        return redirect(url_for('read_all'))
    return render_template('create.html')
        

2. Read Operation (Retrieving Data)

We can display all records or fetch a specific record based on an ID.

Retrieve All Records

@app.route('/read', methods=['GET'])
def read_all():
    records = get_all_records()  # Function to get all records
    return render_template('read.html', records=records)
        

Retrieve a Specific Record

@app.route('/read/<int:id>', methods=['GET'])
def read_one(id):
    record = get_record_by_id(id)  # Function to get a specific record
    return render_template('read_one.html', record=record)
        

3. Update Operation (Modifying Data)

Updating data requires an HTML form where the user can edit existing information.

HTML Form

<form method="POST" action="/update/{{ record.id }}">
    <input type="text" name="name" value="{{ record.name }}">
    <input type="submit" value="Update">
</form>
        

Flask Route

@app.route('/update/<int:id>', methods=['GET', 'POST'])
def update(id):
    if request.method == 'POST':
        new_name = request.form['name']
        update_record(id, new_name)  # Function to update record
        return redirect(url_for('read_one', id=id))
    record = get_record_by_id(id)  # Fetch current record
    return render_template('update.html', record=record)
        

4. Delete Operation (Removing Data)

Deleting a record requires a confirmation button.

HTML Form

<form method="POST" action="/delete/{{ record.id }}">
    <input type="submit" value="Delete">
</form>
        

Flask Route

@app.route('/delete/<int:id>', methods=['POST'])
def delete(id):
    delete_record(id)  # Function to delete the record
    return redirect(url_for('read_all'))
        

Additional Flask Features

1. Accessing Form Data with request.form

Flask allows us to access form data easily using request.form. Example:

@app.route('/login', methods=['POST'])
def login():
    username = request.form['username']
    password = request.form['password']
    return f"Username: {username}, Password: {password}"
        

2. Redirecting Users with redirect()

To send users to another page after an action:

@app.route('/admin')
def admin():
    return redirect(url_for('login'))
        

3. Generating Dynamic URLs with url_for()

Instead of hardcoding URLs, use url_for() for flexibility:

@app.route('/dashboard')
def dashboard():
    return redirect(url_for('home'))
        

Conclusion

CRUD operations are essential in web development, and Flask makes them simple to implement. By using Flask’s built-in features like request.form, redirect(), and url_for(), we can create efficient and scalable applications.

If you’re new to Flask, try implementing these CRUD operations step by step and experiment with different features to build your own web application!

要查看或添加评论,请登录

Rohit Ramteke的更多文章

社区洞察