second
This commit is contained in:
commit
e591d0f409
34 changed files with 424 additions and 0 deletions
6
.env
Normal file
6
.env
Normal file
|
@ -0,0 +1,6 @@
|
||||||
|
DB_NAME=todo_db
|
||||||
|
DB_USER=postgres
|
||||||
|
DB_PASSWORD=postgres
|
||||||
|
DB_HOST=db
|
||||||
|
DB_PORT=5432
|
||||||
|
DEBUG=1
|
30
Dockerfile
Normal file
30
Dockerfile
Normal file
|
@ -0,0 +1,30 @@
|
||||||
|
# backend/Dockerfile
|
||||||
|
FROM python:3.9-slim
|
||||||
|
|
||||||
|
# Set environment variables
|
||||||
|
ENV PYTHONDONTWRITEBYTECODE 1
|
||||||
|
ENV PYTHONUNBUFFERED 1
|
||||||
|
|
||||||
|
# Set work directory
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
# Install system dependencies
|
||||||
|
RUN apt-get update && apt-get install -y \
|
||||||
|
gcc \
|
||||||
|
postgresql-client \
|
||||||
|
netcat-openbsd \
|
||||||
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
|
# Install Python dependencies
|
||||||
|
COPY requirements.txt .
|
||||||
|
RUN pip install --no-cache-dir -r requirements.txt
|
||||||
|
|
||||||
|
# Copy project
|
||||||
|
COPY . .
|
||||||
|
|
||||||
|
# Copy entrypoint script and set permissions
|
||||||
|
COPY entrypoint.sh /entrypoint.sh
|
||||||
|
RUN chmod +x /entrypoint.sh \
|
||||||
|
&& sed -i 's/\r$//g' /entrypoint.sh
|
||||||
|
|
||||||
|
ENTRYPOINT ["/entrypoint.sh"]
|
BIN
db.sqlite3
Normal file
BIN
db.sqlite3
Normal file
Binary file not shown.
17
entrypoint.sh
Normal file
17
entrypoint.sh
Normal file
|
@ -0,0 +1,17 @@
|
||||||
|
#!/bin/sh
|
||||||
|
|
||||||
|
# Wait for postgres to be ready
|
||||||
|
while ! nc -z db 5432; do
|
||||||
|
echo "Waiting for postgres..."
|
||||||
|
sleep 1
|
||||||
|
done
|
||||||
|
|
||||||
|
echo "PostgreSQL started"
|
||||||
|
|
||||||
|
# Apply database migrations
|
||||||
|
echo "Applying database migrations..."
|
||||||
|
python manage.py migrate
|
||||||
|
|
||||||
|
# Start server
|
||||||
|
echo "Starting server..."
|
||||||
|
python manage.py runserver 0.0.0.0:8000
|
22
manage.py
Executable file
22
manage.py
Executable file
|
@ -0,0 +1,22 @@
|
||||||
|
#!/usr/bin/env python
|
||||||
|
"""Django's command-line utility for administrative tasks."""
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
"""Run administrative tasks."""
|
||||||
|
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'todo_project.settings')
|
||||||
|
try:
|
||||||
|
from django.core.management import execute_from_command_line
|
||||||
|
except ImportError as exc:
|
||||||
|
raise ImportError(
|
||||||
|
"Couldn't import Django. Are you sure it's installed and "
|
||||||
|
"available on your PYTHONPATH environment variable? Did you "
|
||||||
|
"forget to activate a virtual environment?"
|
||||||
|
) from exc
|
||||||
|
execute_from_command_line(sys.argv)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
7
requirements.txt
Normal file
7
requirements.txt
Normal file
|
@ -0,0 +1,7 @@
|
||||||
|
Django==4.2.0
|
||||||
|
djangorestframework==3.14.0
|
||||||
|
django-cors-headers==4.1.0
|
||||||
|
djangorestframework-simplejwt==5.2.2
|
||||||
|
python-dotenv==1.0.0
|
||||||
|
psycopg2-binary==2.9.9
|
||||||
|
|
0
todo_project/__init__.py
Normal file
0
todo_project/__init__.py
Normal file
BIN
todo_project/__pycache__/__init__.cpython-312.pyc
Normal file
BIN
todo_project/__pycache__/__init__.cpython-312.pyc
Normal file
Binary file not shown.
BIN
todo_project/__pycache__/settings.cpython-312.pyc
Normal file
BIN
todo_project/__pycache__/settings.cpython-312.pyc
Normal file
Binary file not shown.
BIN
todo_project/__pycache__/urls.cpython-312.pyc
Normal file
BIN
todo_project/__pycache__/urls.cpython-312.pyc
Normal file
Binary file not shown.
BIN
todo_project/__pycache__/wsgi.cpython-312.pyc
Normal file
BIN
todo_project/__pycache__/wsgi.cpython-312.pyc
Normal file
Binary file not shown.
16
todo_project/asgi.py
Normal file
16
todo_project/asgi.py
Normal file
|
@ -0,0 +1,16 @@
|
||||||
|
"""
|
||||||
|
ASGI config for todo_project project.
|
||||||
|
|
||||||
|
It exposes the ASGI callable as a module-level variable named ``application``.
|
||||||
|
|
||||||
|
For more information on this file, see
|
||||||
|
https://docs.djangoproject.com/en/4.2/howto/deployment/asgi/
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
|
||||||
|
from django.core.asgi import get_asgi_application
|
||||||
|
|
||||||
|
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'todo_project.settings')
|
||||||
|
|
||||||
|
application = get_asgi_application()
|
151
todo_project/settings.py
Normal file
151
todo_project/settings.py
Normal file
|
@ -0,0 +1,151 @@
|
||||||
|
"""
|
||||||
|
Django settings for todo_project project.
|
||||||
|
|
||||||
|
Generated by 'django-admin startproject' using Django 4.2.
|
||||||
|
|
||||||
|
For more information on this file, see
|
||||||
|
https://docs.djangoproject.com/en/4.2/topics/settings/
|
||||||
|
|
||||||
|
For the full list of settings and their values, see
|
||||||
|
https://docs.djangoproject.com/en/4.2/ref/settings/
|
||||||
|
"""
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
import os
|
||||||
|
from dotenv import load_dotenv
|
||||||
|
|
||||||
|
# Load environment variables
|
||||||
|
load_dotenv()
|
||||||
|
|
||||||
|
# Build paths inside the project like this: BASE_DIR / 'subdir'.
|
||||||
|
BASE_DIR = Path(__file__).resolve().parent.parent
|
||||||
|
|
||||||
|
|
||||||
|
# Quick-start development settings - unsuitable for production
|
||||||
|
# See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/
|
||||||
|
|
||||||
|
# SECURITY WARNING: keep the secret key used in production secret!
|
||||||
|
SECRET_KEY = 'django-insecure-lfui+*aw(!!kq8qbalr@mp$--uc7gb2#8o#ps3p5s2)pzw@s3i'
|
||||||
|
|
||||||
|
# SECURITY WARNING: don't run with debug turned on in production!
|
||||||
|
DEBUG = True
|
||||||
|
|
||||||
|
ALLOWED_HOSTS = []
|
||||||
|
|
||||||
|
|
||||||
|
# Application definition
|
||||||
|
|
||||||
|
INSTALLED_APPS = [
|
||||||
|
'django.contrib.admin',
|
||||||
|
'django.contrib.auth',
|
||||||
|
'django.contrib.contenttypes',
|
||||||
|
'django.contrib.sessions',
|
||||||
|
'django.contrib.messages',
|
||||||
|
'django.contrib.staticfiles',
|
||||||
|
'rest_framework',
|
||||||
|
'corsheaders',
|
||||||
|
'todos',
|
||||||
|
]
|
||||||
|
|
||||||
|
MIDDLEWARE = [
|
||||||
|
'django.middleware.security.SecurityMiddleware',
|
||||||
|
'django.contrib.sessions.middleware.SessionMiddleware',
|
||||||
|
'corsheaders.middleware.CorsMiddleware',
|
||||||
|
'django.middleware.common.CommonMiddleware',
|
||||||
|
'django.middleware.csrf.CsrfViewMiddleware',
|
||||||
|
'django.contrib.auth.middleware.AuthenticationMiddleware',
|
||||||
|
'django.contrib.messages.middleware.MessageMiddleware',
|
||||||
|
'django.middleware.clickjacking.XFrameOptionsMiddleware',
|
||||||
|
]
|
||||||
|
|
||||||
|
CORS_ALLOWED_ORIGINS = [
|
||||||
|
"http://localhost:5173", # Vue.js development server
|
||||||
|
]
|
||||||
|
|
||||||
|
REST_FRAMEWORK = {
|
||||||
|
'DEFAULT_AUTHENTICATION_CLASSES': [
|
||||||
|
'rest_framework_simplejwt.authentication.JWTAuthentication',
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
ROOT_URLCONF = 'todo_project.urls'
|
||||||
|
|
||||||
|
TEMPLATES = [
|
||||||
|
{
|
||||||
|
'BACKEND': 'django.template.backends.django.DjangoTemplates',
|
||||||
|
'DIRS': [],
|
||||||
|
'APP_DIRS': True,
|
||||||
|
'OPTIONS': {
|
||||||
|
'context_processors': [
|
||||||
|
'django.template.context_processors.debug',
|
||||||
|
'django.template.context_processors.request',
|
||||||
|
'django.contrib.auth.context_processors.auth',
|
||||||
|
'django.contrib.messages.context_processors.messages',
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
WSGI_APPLICATION = 'todo_project.wsgi.application'
|
||||||
|
|
||||||
|
|
||||||
|
# Database
|
||||||
|
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases
|
||||||
|
|
||||||
|
#DATABASES = {
|
||||||
|
# 'default': {
|
||||||
|
# 'ENGINE': 'django.db.backends.sqlite3',
|
||||||
|
# 'NAME': BASE_DIR / 'db.sqlite3',
|
||||||
|
# }
|
||||||
|
#}
|
||||||
|
DATABASES = {
|
||||||
|
'default': {
|
||||||
|
'ENGINE': 'django.db.backends.postgresql',
|
||||||
|
'NAME': os.getenv('DB_NAME', 'todo_db'),
|
||||||
|
'USER': os.getenv('DB_USER', 'postgres'),
|
||||||
|
'PASSWORD': os.getenv('DB_PASSWORD', 'postgres'),
|
||||||
|
'HOST': os.getenv('DB_HOST', 'localhost'),
|
||||||
|
'PORT': os.getenv('DB_PORT', '5432'),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# Password validation
|
||||||
|
# https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators
|
||||||
|
|
||||||
|
AUTH_PASSWORD_VALIDATORS = [
|
||||||
|
{
|
||||||
|
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
# Internationalization
|
||||||
|
# https://docs.djangoproject.com/en/4.2/topics/i18n/
|
||||||
|
|
||||||
|
LANGUAGE_CODE = 'en-us'
|
||||||
|
|
||||||
|
TIME_ZONE = 'UTC'
|
||||||
|
|
||||||
|
USE_I18N = True
|
||||||
|
|
||||||
|
USE_TZ = True
|
||||||
|
|
||||||
|
|
||||||
|
# Static files (CSS, JavaScript, Images)
|
||||||
|
# https://docs.djangoproject.com/en/4.2/howto/static-files/
|
||||||
|
|
||||||
|
STATIC_URL = 'static/'
|
||||||
|
|
||||||
|
# Default primary key field type
|
||||||
|
# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field
|
||||||
|
|
||||||
|
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
|
24
todo_project/urls.py
Normal file
24
todo_project/urls.py
Normal file
|
@ -0,0 +1,24 @@
|
||||||
|
"""
|
||||||
|
URL configuration for todo_project project.
|
||||||
|
|
||||||
|
The `urlpatterns` list routes URLs to views. For more information please see:
|
||||||
|
https://docs.djangoproject.com/en/4.2/topics/http/urls/
|
||||||
|
Examples:
|
||||||
|
Function views
|
||||||
|
1. Add an import: from my_app import views
|
||||||
|
2. Add a URL to urlpatterns: path('', views.home, name='home')
|
||||||
|
Class-based views
|
||||||
|
1. Add an import: from other_app.views import Home
|
||||||
|
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
|
||||||
|
Including another URLconf
|
||||||
|
1. Import the include() function: from django.urls import include, path
|
||||||
|
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
|
||||||
|
"""
|
||||||
|
|
||||||
|
from django.contrib import admin
|
||||||
|
from django.urls import path, include
|
||||||
|
|
||||||
|
urlpatterns = [
|
||||||
|
path('admin/', admin.site.urls),
|
||||||
|
path('api/', include('todos.urls')),
|
||||||
|
]
|
16
todo_project/wsgi.py
Normal file
16
todo_project/wsgi.py
Normal file
|
@ -0,0 +1,16 @@
|
||||||
|
"""
|
||||||
|
WSGI config for todo_project project.
|
||||||
|
|
||||||
|
It exposes the WSGI callable as a module-level variable named ``application``.
|
||||||
|
|
||||||
|
For more information on this file, see
|
||||||
|
https://docs.djangoproject.com/en/4.2/howto/deployment/wsgi/
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
|
||||||
|
from django.core.wsgi import get_wsgi_application
|
||||||
|
|
||||||
|
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'todo_project.settings')
|
||||||
|
|
||||||
|
application = get_wsgi_application()
|
0
todos/__init__.py
Normal file
0
todos/__init__.py
Normal file
BIN
todos/__pycache__/__init__.cpython-312.pyc
Normal file
BIN
todos/__pycache__/__init__.cpython-312.pyc
Normal file
Binary file not shown.
BIN
todos/__pycache__/admin.cpython-312.pyc
Normal file
BIN
todos/__pycache__/admin.cpython-312.pyc
Normal file
Binary file not shown.
BIN
todos/__pycache__/apps.cpython-312.pyc
Normal file
BIN
todos/__pycache__/apps.cpython-312.pyc
Normal file
Binary file not shown.
BIN
todos/__pycache__/models.cpython-312.pyc
Normal file
BIN
todos/__pycache__/models.cpython-312.pyc
Normal file
Binary file not shown.
BIN
todos/__pycache__/serializers.cpython-312.pyc
Normal file
BIN
todos/__pycache__/serializers.cpython-312.pyc
Normal file
Binary file not shown.
BIN
todos/__pycache__/urls.cpython-312.pyc
Normal file
BIN
todos/__pycache__/urls.cpython-312.pyc
Normal file
Binary file not shown.
BIN
todos/__pycache__/views.cpython-312.pyc
Normal file
BIN
todos/__pycache__/views.cpython-312.pyc
Normal file
Binary file not shown.
3
todos/admin.py
Normal file
3
todos/admin.py
Normal file
|
@ -0,0 +1,3 @@
|
||||||
|
from django.contrib import admin
|
||||||
|
|
||||||
|
# Register your models here.
|
6
todos/apps.py
Normal file
6
todos/apps.py
Normal file
|
@ -0,0 +1,6 @@
|
||||||
|
from django.apps import AppConfig
|
||||||
|
|
||||||
|
|
||||||
|
class TodosConfig(AppConfig):
|
||||||
|
default_auto_field = 'django.db.models.BigAutoField'
|
||||||
|
name = 'todos'
|
27
todos/migrations/0001_initial.py
Normal file
27
todos/migrations/0001_initial.py
Normal file
|
@ -0,0 +1,27 @@
|
||||||
|
# Generated by Django 4.2 on 2025-01-15 13:36
|
||||||
|
|
||||||
|
from django.conf import settings
|
||||||
|
from django.db import migrations, models
|
||||||
|
import django.db.models.deletion
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
initial = True
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.CreateModel(
|
||||||
|
name='Todo',
|
||||||
|
fields=[
|
||||||
|
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||||
|
('title', models.CharField(max_length=200)),
|
||||||
|
('completed', models.BooleanField(default=False)),
|
||||||
|
('created_at', models.DateTimeField(auto_now_add=True)),
|
||||||
|
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
]
|
0
todos/migrations/__init__.py
Normal file
0
todos/migrations/__init__.py
Normal file
BIN
todos/migrations/__pycache__/0001_initial.cpython-312.pyc
Normal file
BIN
todos/migrations/__pycache__/0001_initial.cpython-312.pyc
Normal file
Binary file not shown.
BIN
todos/migrations/__pycache__/__init__.cpython-312.pyc
Normal file
BIN
todos/migrations/__pycache__/__init__.cpython-312.pyc
Normal file
Binary file not shown.
12
todos/models.py
Normal file
12
todos/models.py
Normal file
|
@ -0,0 +1,12 @@
|
||||||
|
from django.db import models
|
||||||
|
from django.contrib.auth.models import User
|
||||||
|
|
||||||
|
class Todo(models.Model):
|
||||||
|
user = models.ForeignKey(User, on_delete=models.CASCADE)
|
||||||
|
title = models.CharField(max_length=200)
|
||||||
|
completed = models.BooleanField(default=False)
|
||||||
|
created_at = models.DateTimeField(auto_now_add=True)
|
||||||
|
|
||||||
|
def __str__(self):
|
||||||
|
return self.title
|
||||||
|
|
21
todos/serializers.py
Normal file
21
todos/serializers.py
Normal file
|
@ -0,0 +1,21 @@
|
||||||
|
from rest_framework import serializers
|
||||||
|
from django.contrib.auth.models import User
|
||||||
|
from .models import Todo
|
||||||
|
|
||||||
|
class UserSerializer(serializers.ModelSerializer):
|
||||||
|
class Meta:
|
||||||
|
model = User
|
||||||
|
fields = ('id', 'username')
|
||||||
|
extra_kwargs = {'password': {'write_only': True}}
|
||||||
|
|
||||||
|
def create(self, validated_data):
|
||||||
|
user = User.objects.create_user(
|
||||||
|
username=validated_data['username'],
|
||||||
|
password=validated_data['password']
|
||||||
|
)
|
||||||
|
return user
|
||||||
|
|
||||||
|
class TodoSerializer(serializers.ModelSerializer):
|
||||||
|
class Meta:
|
||||||
|
model = Todo
|
||||||
|
fields = ('id', 'title', 'completed', 'created_at')
|
3
todos/tests.py
Normal file
3
todos/tests.py
Normal file
|
@ -0,0 +1,3 @@
|
||||||
|
from django.test import TestCase
|
||||||
|
|
||||||
|
# Create your tests here.
|
12
todos/urls.py
Normal file
12
todos/urls.py
Normal file
|
@ -0,0 +1,12 @@
|
||||||
|
from django.urls import path, include
|
||||||
|
from rest_framework.routers import DefaultRouter
|
||||||
|
from .views import TodoViewSet, register_user, login_user
|
||||||
|
|
||||||
|
router = DefaultRouter()
|
||||||
|
router.register(r'todos', TodoViewSet, basename='todo')
|
||||||
|
|
||||||
|
urlpatterns = [
|
||||||
|
path('', include(router.urls)),
|
||||||
|
path('register/', register_user, name='register'),
|
||||||
|
path('login/', login_user, name='login'),
|
||||||
|
]
|
51
todos/views.py
Normal file
51
todos/views.py
Normal file
|
@ -0,0 +1,51 @@
|
||||||
|
from rest_framework import viewsets, permissions, status
|
||||||
|
from rest_framework.response import Response
|
||||||
|
from rest_framework.decorators import api_view, permission_classes
|
||||||
|
from django.contrib.auth import authenticate
|
||||||
|
from rest_framework_simplejwt.tokens import RefreshToken
|
||||||
|
from .models import Todo
|
||||||
|
from .serializers import TodoSerializer, UserSerializer
|
||||||
|
import logging
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
@api_view(['POST'])
|
||||||
|
@permission_classes([permissions.AllowAny])
|
||||||
|
def register_user(request):
|
||||||
|
serializer = UserSerializer(data=request.data)
|
||||||
|
if serializer.is_valid():
|
||||||
|
user = serializer.save()
|
||||||
|
refresh = RefreshToken.for_user(user)
|
||||||
|
return Response({
|
||||||
|
'token': str(refresh.access_token),
|
||||||
|
})
|
||||||
|
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
|
||||||
|
|
||||||
|
@api_view(['POST'])
|
||||||
|
@permission_classes([permissions.AllowAny])
|
||||||
|
def login_user(request):
|
||||||
|
username = request.data.get('username')
|
||||||
|
password = request.data.get('password')
|
||||||
|
user = authenticate(username=username, password=password)
|
||||||
|
if user:
|
||||||
|
refresh = RefreshToken.for_user(user)
|
||||||
|
return Response({
|
||||||
|
'token': str(refresh.access_token),
|
||||||
|
})
|
||||||
|
return Response({'error': 'Invalid credentials'}, status=status.HTTP_400_BAD_REQUEST)
|
||||||
|
|
||||||
|
class TodoViewSet(viewsets.ModelViewSet):
|
||||||
|
serializer_class = TodoSerializer
|
||||||
|
permission_classes = [permissions.IsAuthenticated]
|
||||||
|
|
||||||
|
def get_queryset(self):
|
||||||
|
print(f"user query: {self.request.user.username}")
|
||||||
|
logger.info(f"query by user: {self.request.user.username}")
|
||||||
|
return Todo.objects.filter(user=self.request.user)
|
||||||
|
|
||||||
|
def perform_create(self, serializer):
|
||||||
|
todo = serializer.save(user=self.request.user)
|
||||||
|
serializer.save(user=self.request.user)
|
||||||
|
print(f"New todo added - Title: '{todo.title}' by user: {self.request.user.username}")
|
||||||
|
logger.info(f"New todo added - Title: '{todo.title}' by user: {self.request.user.username}")
|
||||||
|
|
Loading…
Reference in a new issue