Skip to content

feat: add django mysql guide #72

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@ This repo contains the samples for [Keploy's](https://keploy.io) integration wit

5. [Flask-Redis](https://github.com/keploy/samples-python/tree/main/flask-redis) - This Flask-based application provides a book management system utilizing Redis for caching and storage. It supports adding, retrieving, updating, and deleting book records, with optimized search functionality and cache management for improved performance. The API endpoints ensure efficient data handling and quick access to book information.

6. [Django-Mysql] (https://github.com/keploy/samples-python/tree/main/django-mysql)- This application is a simple Employee Management System built with Django and MySQL. It allows you to create, retrieve, update, and delete employee records via RESTful API endpoints. The application is containerized using Docker, making it easy to deploy and run in different environments. The backend is powered by Django, and the MySQL database is used to store employee information.


## Community Support ❤️

### 🤔 Questions?
Expand Down
54 changes: 54 additions & 0 deletions django-mysql/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# Python
*.pyc
*.pyo
*.pyd
__pycache__/

# Virtual Environment
venv/
env/
.venv/
.env/

# Django
*.log
*.pot
*.pyc
*.pyo
*.pyd
__pycache__/
db.sqlite3
media/
staticfiles/

# IDEs and Editors
.vscode/
.idea/
*.swp
*.swo

# macOS
.DS_Store

# Node.js
node_modules/

# Coverage reports
.coverage
coverage.xml
*.cover
*.py,cover
.hypothesis/

# Test output
nosetests.xml
pytest_cache/
junit.xml

# Environment variables
.env
.env.*

# Other
*.bak
*.tmp
24 changes: 24 additions & 0 deletions django-mysql/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Set base image
FROM python:3.9

# Set environment variables
ENV PYTHONUNBUFFERED=1

# Create and set the working directory
ARG HOST_PWD
WORKDIR $HOST_PWD

# Install dependencies
COPY ./requirements.txt ./requirements.txt
RUN pip install -r requirements.txt

# Copy the project files
COPY . .

# Run migrations and start the server with proper signal handling

# FOR RECORD MODE
ENTRYPOINT ["sh", "-c", "python manage.py makemigrations && python manage.py migrate && exec python manage.py runserver 0.0.0.0:8000"]

# FOR TEST MODE
# ENTRYPOINT ["sh", "-c", "exec python -m coverage run manage.py runserver 0.0.0.0:8000 --noreload"]
83 changes: 83 additions & 0 deletions django-mysql/README.MD
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
## Django MySQL CRUD Application

This application is a simple Employee Management System built with Django and MySQL. It allows you to create, retrieve, update, and delete employee records via RESTful API endpoints. The application is containerized using Docker, making it easy to deploy and run in different environments. The backend is powered by Django, and the MySQL database is used to store employee information.

## Prerequisites

* Docker

## Steps to Run the Application

### 1. Build and Run MySQL Database Container

Run the db:

```bash
docker run --name mySQL --network keploy-network -e MYSQL_ROOT_PASSWORD=keploy -e MYSQL_DATABASE=keploy_db -e MYSQL_USER=admin -e MYSQL_PASSWORD=keploy -p 3306:3306 -d mysql
```

### 2. Build and Run Django Application Container

In the project root directory, run:

```bash
docker build --build-arg HOST_PWD="$(pwd)" -t py-app .

docker run --name django-app --net keploy-network -p 8000:8000 -v "$(pwd):$(pwd)" --rm py-app
```

### 3. API Endpoints

• **Create Employee (POST):** [http://localhost:8000/api/employee/create/](http://localhost:8000/api/employee/create/)

• **Get Employee by ID (GET):** [http://localhost:8000/api/employee/{id}/](http://localhost:8000/api/employee/{id}/)

• **Get All Employees (GET):** [http://localhost:8000/api/employee/](http://localhost:8000/api/employee/)

• **Update Employee (PUT):** [http://localhost:8000/api/employee/update/{id}/](http://localhost:8000/api/employee/update/{id}/)

• **Delete Employee (DELETE):** [http://localhost:8000/api/employee/delete/{id}/](http://localhost:8000/api/employee/delete/{id}/)

### Example Request Payload for Creating an Employee:

```bash
curl -X POST http://localhost:8000/api/employee/create/ -H "Content-Type: application/json" -d '{"name": "John Doe", "years_of_experience": 5, "field": "Computer Science", "company": "TechCorp"}'
```

### Notes:

> Django application runs on port 8000.

## Testing the APIs

Use the following curl commands to test the APIs after running the application:

### POST Request to create an employee

```bash
curl -X POST http://localhost:8000/api/employee/create/ -H "Content-Type: application/json" -d '{"name": "John Doe", "years_of_experience": 5, "field": "Computer Science", "company": "TechCorp"}'
```

### GET Request to fetch all employees

```bash
curl -X GET http://localhost:8000/api/employee/
```

### GET Request to fetch an employee by ID

```bash
curl -X GET http://localhost:8000/api/employee/1/
```

### PUT Request to update an employee

```bash
curl -X PUT http://localhost:8000/api/employee/update/1/ -H "Content-Type: application/json" -d '{"name": "Jane Doe", "years_of_experience": 6, "field": "Data Science", "company": "TechCorp"}'
```

### DELETE Request to delete an employee

```bash
curl -X DELETE http://localhost:8000/api/employee/delete/1/
```
Empty file.
3 changes: 3 additions & 0 deletions django-mysql/employee/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.contrib import admin

# Register your models here.
6 changes: 6 additions & 0 deletions django-mysql/employee/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from django.apps import AppConfig


class EmployeeConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'employee'
23 changes: 23 additions & 0 deletions django-mysql/employee/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Generated by Django 4.2.7 on 2025-07-28 10:39

from django.db import migrations, models


class Migration(migrations.Migration):

initial = True

dependencies = [
]

operations = [
migrations.CreateModel(
name='Employee',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100)),
('years_of_experience', models.IntegerField()),
('company', models.CharField(max_length=100)),
],
),
]
Empty file.
6 changes: 6 additions & 0 deletions django-mysql/employee/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from django.db import models

class Employee(models.Model):
name = models.CharField(max_length=100)
years_of_experience = models.IntegerField()
company = models.CharField(max_length=100)
7 changes: 7 additions & 0 deletions django-mysql/employee/serializers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
from rest_framework import serializers
from .models import Employee

class EmployeeSerializer(serializers.ModelSerializer):
class Meta:
model = Employee
fields = ['id', 'name', 'years_of_experience', 'company']
3 changes: 3 additions & 0 deletions django-mysql/employee/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.test import TestCase

# Create your tests here.
10 changes: 10 additions & 0 deletions django-mysql/employee/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
from django.urls import path
from . import views

urlpatterns = [
path('employee/', views.get_all_employees),
path('employee/<int:pk>/', views.get_employee),
path('employee/create/', views.create_employee),
path('employee/update/<int:pk>/', views.update_employee),
path('employee/delete/<int:pk>/', views.delete_employee),
]
53 changes: 53 additions & 0 deletions django-mysql/employee/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from .models import Employee
from .serializers import EmployeeSerializer

@api_view(['POST'])
def create_employee(request):
if request.method == 'POST':
serializer = EmployeeSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

@api_view(['GET'])
def get_employee(request, pk):
try:
employee = Employee.objects.get(pk=pk)
except Employee.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)

serializer = EmployeeSerializer(employee)
return Response(serializer.data)

@api_view(['GET'])
def get_all_employees(request):
employees = Employee.objects.all()
serializer = EmployeeSerializer(employees, many=True)
return Response(serializer.data)

@api_view(['PUT'])
def update_employee(request, pk):
try:
employee = Employee.objects.get(pk=pk)
except Employee.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)

serializer = EmployeeSerializer(employee, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

@api_view(['DELETE'])
def delete_employee(request, pk):
try:
employee = Employee.objects.get(pk=pk)
except Employee.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)

employee.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
68 changes: 68 additions & 0 deletions django-mysql/keploy.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
# Generated by Keploy (2.6.22)
path: ""
appId: 0
appName: django-mysql
command: sudo docker run --name django-app --net keploy-network -p 8000:8000 -v /Users/achanandhi/Documents/fix-django-mysql/samples-python/django-mysql:/Users/achanandhi/Documents/fix-django-mysql/samples-python/django-mysql --rm py-app
templatize:
testSets: []
port: 0
e2e: false
dnsPort: 26789
proxyPort: 16789
debug: false
disableTele: false
disableANSI: false
containerName: ""
networkName: ""
buildDelay: 30
test:
selectedTests: {}
globalNoise:
global: {}
test-sets: {}
delay: 5
host: ""
port: 0
apiTimeout: 5
skipCoverage: false
coverageReportPath: ""
ignoreOrdering: true
mongoPassword: default@123
language: ""
removeUnusedMocks: false
fallBackOnMiss: false
jacocoAgentPath: ""
basePath: ""
mocking: true
ignoredTests: {}
disableLineCoverage: false
disableMockUpload: true
useLocalMock: false
updateTemplate: false
mustPass: false
maxFailAttempts: 5
maxFlakyChecks: 1
record:
filters: []
basePath: ""
recordTimer: 0s
metadata: ""
configPath: ""
bypassRules: []
generateGithubActions: false
keployContainer: keploy-v2
keployNetwork: keploy-network
cmdType: native
contract:
services: []
tests: []
path: ""
download: false
generate: false
driven: consumer
mappings:
servicesMapping: {}
self: s1
inCi: false

# Visit [https://keploy.io/docs/running-keploy/configuration-file/] to learn about using keploy through configration file.
2 changes: 2 additions & 0 deletions django-mysql/keploy/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@

/reports/
Loading