DEV Community

Cover image for Implementing a Basic CRUD Application in Python (Flask/Django)
Info general Hazedawn
Info general Hazedawn

Posted on

4 2 1 2 2

Implementing a Basic CRUD Application in Python (Flask/Django)

Creating a basic CRUD (Create, Read, Update, Delete) application is an excellent way to learn about web development using Python. In this guide, we will explore how to build a simple CRUD application using both Flask and Django. We will cover the essential code needed to handle database operations and routing for each framework.

What is CRUD? đź“‹

CRUD stands for:

  • Create: Adding new data to the database.
  • Read: Retrieving data from the database.
  • Update: Modifying existing data.
  • Delete: Removing data from the database. Both Flask and Django provide tools to implement these operations effectively.

Option 1: Building a CRUD Application with Flask 🛠️

Step 1: Setting Up Flask
First, ensure you have Flask installed. You can do this via pip:

bash
pip install Flask Flask-SQLAlchemy

Step 2: Create Your Flask Application
Create a new directory for your project and add a file named app.py. Here’s a simple structure:

text
flask-crud-app/
│
├── app.py
└── models.py

Step 3: Define Your Models
In models.py, define your database model:

python
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

class Task(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100), nullable=False)
completed = db.Column(db.Boolean, default=False)

def __repr__(self):
    return f"<Task {self.title}>"
Enter fullscreen mode Exit fullscreen mode

Step 4: Create the Flask App and Routes
In app.py, set up your Flask application and routes:

python
from flask import Flask, request, jsonify
from models import db, Task

app = Flask(name)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///tasks.db'
db.init_app(app)

@app.route('/tasks', methods=['POST'])
def create_task():
data = request.get_json()
new_task = Task(title=data['title'])
db.session.add(new_task)
db.session.commit()
return jsonify({'message': 'Task created!'}), 201

@app.route('/tasks', methods=['GET'])
def get_tasks():
tasks = Task.query.all()
return jsonify([{'id': task.id, 'title': task.title, 'completed': task.completed} for task in tasks])

@app.route('/tasks/int:id', methods=['PUT'])
def update_task(id):
task = Task.query.get(id)
if not task:
return jsonify({'message': 'Task not found!'}), 404

data = request.get_json()
task.title = data['title']
task.completed = data['completed']
db.session.commit()

return jsonify({'message': 'Task updated!'})
Enter fullscreen mode Exit fullscreen mode

@app.route('/tasks/int:id', methods=['DELETE'])
def delete_task(id):
task = Task.query.get(id)
if not task:
return jsonify({'message': 'Task not found!'}), 404

db.session.delete(task)
db.session.commit()

return jsonify({'message': 'Task deleted!'})
Enter fullscreen mode Exit fullscreen mode

if name == 'main':
with app.app_context():
db.create_all() # Create database tables
app.run(debug=True)

Explanation:

  • Database Configuration: SQLite is used for simplicity.
  • Routes: Each route corresponds to a CRUD operation.

Option 2: Building a CRUD Application with Django 🌟

Step 1: Setting Up Django
First, ensure you have Django installed:

bash
pip install django

Step 2: Create Your Django Project
Create a new Django project and app:

bash
django-admin startproject myproject
cd myproject
django-admin startapp tasks

Step 3: Define Your Models
In tasks/models.py, define your model:

python
from django.db import models

class Task(models.Model):
title = models.CharField(max_length=100)
completed = models.BooleanField(default=False)

def __str__(self):
    return self.title
Enter fullscreen mode Exit fullscreen mode

Step 4: Set Up Views and URLs
In tasks/views.py, create views for your CRUD operations:

python
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
import json
from .models import Task

@csrf_exempt
def create_task(request):
if request.method == 'POST':
data = json.loads(request.body)
task = Task.objects.create(title=data['title'])
return JsonResponse({'message': 'Task created!', 'id': task.id}, status=201)

def get_tasks(request):
tasks = list(Task.objects.values())
return JsonResponse(tasks, safe=False)

@csrf_exempt
def update_task(request, id):
try:
task = Task.objects.get(id=id)
if request.method == 'PUT':
data = json.loads(request.body)
task.title = data['title']
task.completed = data['completed']
task.save()
return JsonResponse({'message': 'Task updated!'})
except Task.DoesNotExist:
return JsonResponse({'message': 'Task not found!'}, status=404)

@csrf_exempt
def delete_task(request, id):
try:
task = Task.objects.get(id=id)
if request.method == 'DELETE':
task.delete()
return JsonResponse({'message': 'Task deleted!'})
except Task.DoesNotExist:
return JsonResponse({'message': 'Task not found!'}, status=404)

Step 5: Configure URLs
In myproject/urls.py, include the routes for your app:

python
from django.contrib import admin
from django.urls import path
from tasks.views import create_task, get_tasks, update_task, delete_task

urlpatterns = [
path('admin/', admin.site.urls),
path('tasks/', create_task),
path('tasks/', get_tasks),
path('tasks/int:id/', update_task),
path('tasks/int:id/', delete_task),
]

Final Steps for Django:
Run migrations to set up your database:

bash
python manage.py makemigrations tasks
python manage.py migrate

Start the server:

bash
python manage.py runserver

Conclusion: Building Your CRUD Application 🏗️

Whether you choose Flask or Django, creating a basic CRUD application is an excellent way to understand web development with Python. Both frameworks offer powerful tools for handling database operations and routing effectively.

Next Steps:

  • Explore adding user authentication to your application.
  • Consider deploying your application using platforms like Heroku or AWS.

Start building your CRUD applications today and enhance your web development skills! 💡✨

Python #Flask #Django #WebDevelopment #CRUD #Programming #LearnToCode #TechForBeginners #SoftwareEngineering

Heroku

Deliver your unique apps, your own way.

Heroku tackles the toil — patching and upgrading, 24/7 ops and security, build systems, failovers, and more. Stay focused on building great data-driven applications.

Learn More

Top comments (0)

Jetbrains image

Build Secure, Ship Fast

Discover best practices to secure CI/CD without slowing down your pipeline.

Read more

đź‘‹ Kindness is contagious

Dive into this informative piece, backed by our vibrant DEV Community

Whether you’re a novice or a pro, your perspective enriches our collective insight.

A simple “thank you” can lift someone’s spirits—share your gratitude in the comments!

On DEV, the power of shared knowledge paves a smoother path and tightens our community ties. Found value here? A quick thanks to the author makes a big impact.

Okay