This project is an e-commerce backend built with Django and Django REST Framework (DRF). It includes unit tests, performance tests, and is set up for production-grade deployment using Redis and Celery.
- Product Management: CRUD operations for products, including images and reviews.
- Collection Management: Manage product collections.
- Cart Management: Persistent shopping cart functionality.
- Customer Management: Manage customer information.
- Order Management: Handle order creation and tracking.
- Unit and Performance Testing: Comprehensive tests to ensure code quality and performance.
- Background Tasks: Asynchronous task processing using Celery.
- Python 3.8+
- Django 3.2+
- Django REST Framework
- Redis
- Celery
- Docker (for deployment)
-
Clone the repository:
git clone https://github.com/yourusername/ecommerce-backend.git cd ecommerce-backend
-
Create and activate a virtual environment:
python -m venv venv source venv/bin/activate # On Windows use `venv\Scripts\activate`
-
Install dependencies:
pip install -r requirements.txt
-
Apply migrations:
python manage.py makemigrations python manage.py migrate
-
Run the development server:
python manage.py runserver
-
Create a superuser:
python manage.py createsuperuser
from django.db import models
class Product(models.Model):
name = models.CharField(max_length=255)
description = models.TextField()
price = models.DecimalField(max_digits=10, decimal_places=2)
inventory = models.IntegerField()
last_update = models.DateTimeField(auto_now=True)
def __str__(self):
return self.name
class Collection(models.Model):
title = models.CharField(max_length=255)
featured_product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True, related_name='+')
def __str__(self):
return self.title
class Cart(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
class CartItem(models.Model):
cart = models.ForeignKey(Cart, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
quantity = models.PositiveIntegerField()
class Meta:
unique_together = [['cart', 'product']]
from django.contrib.auth.models import User
class Customer(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
phone = models.CharField(max_length=255)
birth_date = models.DateField(null=True)
def __str__(self):
return self.user.username
class Order(models.Model):
customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
placed_at = models.DateTimeField(auto_now_add=True)
payment_status = models.CharField(max_length=20, choices=[('PENDING', 'Pending'), ('COMPLETED', 'Completed'), ('FAILED', 'Failed')])
class OrderItem(models.Model):
order = models.ForeignKey(Order, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.PROTECT)
quantity = models.PositiveIntegerField()
unit_price = models.DecimalField(max_digits=10, decimal_places=2)
The API uses DRF's router system for endpoint management. Below are the main endpoints:
from rest_framework import routers
from . import views
router = routers.DefaultRouter()
router.register('products', views.ProductViewSet, basename='products')
router.register('collections', views.CollectionViewSet)
router.register('carts', views.CartViewSet)
router.register('customers', views.CustomerViewSet)
router.register('orders', views.OrderViewSet, basename='orders')
products_router = routers.NestedDefaultRouter(router, 'products', lookup='product')
products_router.register('reviews', views.ReviewViewSet, basename='product-reviews')
products_router.register('images', views.ProductImageViewSet, basename='product-images')
carts_router = routers.NestedDefaultRouter(router, 'carts', lookup='cart')
carts_router.register('items', views.CartItemViewSet, basename='cart-items')
Unit tests are essential for ensuring the correctness of your code. Run unit tests with:
python manage.py test
Use a tool like Locust or JMeter for performance testing. Example with Locust:
locust -f locustfile.py
Celery is used for handling asynchronous tasks such as sending emails, processing orders, etc.
-
Install Celery:
pip install celery
-
Configure Celery in your Django project:
# settings.py CELERY_BROKER_URL = 'redis://localhost:6379/0' CELERY_RESULT_BACKEND = 'redis://localhost:6379/0'
-
Create a
celery.py
file in your project directory:from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'your_project.settings') app = Celery('your_project') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks()
-
Define tasks in your Django apps:
# tasks.py from celery import shared_task @shared_task def example_task(): print("Task executed")
-
Run Celery worker:
celery -A your_project worker --loglevel=info
The project uses separate settings files for different environments: common.py
, dev.py
, and prod.py
.
Ensure Redis is installed and running. Update your settings to use Redis for caching and session management.
Deploy the project to Vercel using the following URL: storefront3-wsl2.vercel.app
Ensure the DJANGO_SETTINGS_MODULE
environment variable is set during deployment. For example:
export DJANGO_SETTINGS_MODULE=your_project.settings.prod