Skip to content
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
5 changes: 5 additions & 0 deletions .envs/.postgres
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
POSTGRES_HOST=postgres

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Renombraría el archivo para que sea algo así como un template para inspirarse, de esa forma no quedan las credenciales en el código.

POSTGRES_PORT=5432
POSTGRES_DB=todo
POSTGRES_USER=root
POSTGRES_PASSWORD=1234
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
*.pyc
__pychache__
*.log

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agregaría una regla para no commitear los archivos en .envs

12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,3 +33,15 @@ El usuario de la aplicación tiene que ser capaz de:
- El Readme debe contener todas las instrucciones para poder levantar la aplicación, en caso de ser necesario, y explicar cómo se usa.
- Disponibilidad para realizar una pequeña demo del proyecto al finalizar el challenge.
- Tiempo para la entrega: Aproximadamente 7 días.


## Solución

- Construir el proyecto
- ### docker-compose build
- Correr Proyecto
- ### docker-compose up
- Crear superusuario
- ### docker-compose run --rm challenge python manage.py createsuperuser
- Para correr los tests:
- ### docker-compose run --rm python manage.py test
Empty file added api/__init__.py
Empty file.
Empty file added api/todos/__init__.py
Empty file.
4 changes: 4 additions & 0 deletions api/todos/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
from django.contrib import admin
from api.todos.models import Todo

admin.site.register(Todo)
5 changes: 5 additions & 0 deletions api/todos/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from django.apps import AppConfig


class TodosConfig(AppConfig):
name = 'api.todos'
28 changes: 28 additions & 0 deletions api/todos/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# Generated by Django 2.2.16 on 2021-09-06 12:23

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.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=150)),
('description', models.TextField(default='', max_length=250)),
('completed', models.BooleanField(default=False)),
('created', models.DateTimeField(auto_now_add=True)),
('usuario', models.ForeignKey(default='', on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
Empty file.
12 changes: 12 additions & 0 deletions api/todos/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
from django.db import models
from django.contrib.auth.models import User

class Todo(models.Model):
name = models.CharField(max_length=150, null=False)
description = models.TextField(max_length=250, null=False, default='')
completed = models.BooleanField(default=False)
created = models.DateTimeField(auto_now_add=True)
usuario = models.ForeignKey(User, on_delete=models.CASCADE, default='')

def __str__(self):
return self.name
8 changes: 8 additions & 0 deletions api/todos/serializers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
from rest_framework import serializers
from api.todos.models import Todo

class TodoSerializer(serializers.ModelSerializer):

class Meta:
model = Todo
fields = "__all__"
Empty file added api/todos/tests/__init__.py
Empty file.
57 changes: 57 additions & 0 deletions api/todos/tests/test_todos.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
from django.test import TestCase
from django.urls import reverse
from django.contrib.auth.models import User
from rest_framework.test import APIClient
from rest_framework import status

class TodoTestCase(TestCase):

def setUp(self):
"""Define el cliente para el test y otros variables"""
self.user = User.objects.create_user(
username='test@test.com', password='realpassword')
self.client = APIClient()
self.todo_data = {
"name": "Go to Ibiza",
"description": "A mediados de Junio",
"completed": False,
"usuario": self.user.pk
}
self.response = self.client.post(
reverse('todos'),
data=self.todo_data,
format="json"
)

def test_api_can_create_a_todo(self):
"""Confirmamos si se creo correctamente el TODO"""
self.assertEqual(self.response.status_code, status.HTTP_201_CREATED)

def test_api_can_get_a_todo(self):
"""Consultamos el TODO creado"""
id = self.response.data.get('id')
url = reverse('todo_list', kwargs={'pk':id})
response = self.client.get(url)

self.assertEqual(response.status_code, status.HTTP_200_OK)

def test_api_can_update_todo(self):
"""Modificamos el TODO creado"""
id = self.response.data.get('id')
change_todo = {'completed': True}
url = reverse('todo_list', kwargs={'pk':id})
res = self.client.patch(
url,
change_todo,
'json'
)

self.assertEqual(res.status_code, status.HTTP_200_OK)

def test_api_can_delete_todo(self):
"""Eliminamos el TODO creado."""
id = self.response.data.get('id')
url = reverse('todo_list', kwargs={'pk': id})
response = self.client.delete(url)

self.assertEquals(response.status_code, status.HTTP_204_NO_CONTENT)
15 changes: 15 additions & 0 deletions api/todos/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
from django.urls import path
from api.todos.views import TodoView

urlpatterns = [
path('todos/', TodoView.as_view({
'get': 'list',
'post': 'create'
}), name='todos'),
path('todos/<int:pk>', TodoView.as_view({
'get': 'retrieve',
'put': 'update',
'patch': 'partial_update',
'delete': 'destroy'
}), name='todo_list'),
]
15 changes: 15 additions & 0 deletions api/todos/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
from rest_framework.viewsets import ModelViewSet
from rest_framework.filters import SearchFilter
from rest_framework.pagination import PageNumberPagination
from api.todos.models import Todo
from api.todos.serializers import TodoSerializer


class TodoView(ModelViewSet):
filter_backends = (SearchFilter,)
queryset = Todo.objects.all()
serializer_class = TodoSerializer
search_fields = ('name', 'description', 'created')
ordering_fields = ['created']
pagination_class = PageNumberPagination
pagination_class.page_size = 8
22 changes: 22 additions & 0 deletions compose/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
FROM python:3.6-alpine

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

no podemos usar una versión más nueva de python?


RUN apk update \
# psycopg2 dependencies
&& apk add --virtual build-deps gcc python3-dev musl-dev \
&& apk add postgresql-dev \
&& apk add postgresql-client

COPY ./requirements.txt /requirements.txt
RUN pip install -r requirements.txt

COPY ./compose/entrypoint /entrypoint
RUN sed -i 's/\r//' /entrypoint
RUN chmod +x /entrypoint

COPY ./compose/start /start
RUN sed -i 's/\r//' /start
RUN chmod +x /start

WORKDIR /app

ENTRYPOINT ["/entrypoint"]
42 changes: 42 additions & 0 deletions compose/entrypoint
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
#!/bin/sh

set -o errexit
set -o pipefail
set -o nounset


# N.B. If only .env files supported variable expansion...

if [ -z "${POSTGRES_USER}" ]; then
base_postgres_image_default_user='postgres'
export POSTGRES_USER="${base_postgres_image_default_user}"
fi
export DATABASE_URL="postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@${POSTGRES_HOST}:${POSTGRES_PORT}/${POSTGRES_DB}"

postgres_ready() {
python << END
import sys

import psycopg2

try:
psycopg2.connect(
dbname="${POSTGRES_DB}",
user="${POSTGRES_USER}",
password="${POSTGRES_PASSWORD}",
host="${POSTGRES_HOST}",
port="${POSTGRES_PORT}",
)
except psycopg2.OperationalError:
sys.exit(-1)
sys.exit(0)

END
}
until postgres_ready; do
>&2 echo 'Waiting for PostgreSQL to become available...'
sleep 1
done
>&2 echo 'PostgreSQL is available'

exec "$@"
9 changes: 9 additions & 0 deletions compose/start
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
#!/bin/sh

set -o errexit
set -o pipefail
set -o nounset


python manage.py migrate
python manage.py runserver 0.0.0.0:8000
116 changes: 116 additions & 0 deletions config/settings/base.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
import environ

ROOT_DIR = environ.Path(__file__) - 3
APPS_DIR = ROOT_DIR.path('api')

env = environ.Env()

# Base
DEBUG = env.bool('DJANGO_DEBUG', False)

# Language and timezone
TIME_ZONE = 'America/Argentina/Buenos_Aires'
LANGUAGE_CODE = 'es-AR'
SITE_ID = 1
USE_I18N = True
USE_L10N = True
USE_TZ = True

# DATABASES
DATABASES = {
'default': env.db('DATABASE_URL'),
}

DATABASES['default']['ATOMIC_REQUESTS'] = True

# URLs
ROOT_URLCONF = 'config.urls'

# WSGI
WSGI_APPLICATION = 'config.wsgi.application'

# Apps
DJANGO_APPS = [
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
]

THIRD_PARTY_APPS = [
'rest_framework'
]
LOCAL_APPS = [
'api.todos.apps.TodosConfig',
]
INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS

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',
},
]

# Middlewares
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

# Static files
STATIC_ROOT = str(ROOT_DIR('staticfiles'))
STATIC_URL = '/static/'
STATICFILES_DIRS = [
str(APPS_DIR.path('static')),
]
STATICFILES_FINDERS = [
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
]

# Media
MEDIA_ROOT = str(APPS_DIR('media'))
MEDIA_URL = '/media/'

# Templates
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
str(APPS_DIR.path('templates')),
],
'OPTIONS': {
'debug': DEBUG,
'loaders': [
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
],
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.template.context_processors.i18n',
'django.template.context_processors.media',
'django.template.context_processors.static',
'django.template.context_processors.tz',
'django.contrib.messages.context_processors.messages',
],
},
},
]
Loading