xonecas.io
3517
Mt

meal_tracker / commit d5a5017

Initial setup of the backend api

Use Django Rest Framework to expose a CRUD around Meals

xonecas2020-03-04 d5a5017fc9dbfb3619d40f7e4bb7f1c56e64cc7f

17 files changed

.gitignore+2−0
@@ -0,0 +1,2 @@
1+__pycache__
2+*.pyc
bmi_api/__init__.py+0−0
bmi_api/admin.py+3−0
@@ -0,0 +1,3 @@
1+from django.contrib import admin
2+
3+# Register your models here.
bmi_api/apps.py+5−0
@@ -0,0 +1,5 @@
1+from django.apps import AppConfig
2+
3+
4+class BmiApiConfig(AppConfig):
5+ name = 'bmi_api'
bmi_api/migrations/0001_initial.py+24−0
@@ -0,0 +1,24 @@
1+# Generated by Django 3.0.4 on 2020-03-04 13:12
2+
3+from django.db import migrations, models
4+
5+
6+class Migration(migrations.Migration):
7+
8+ initial = True
9+
10+ dependencies = [
11+ ]
12+
13+ operations = [
14+ migrations.CreateModel(
15+ name='Meal',
16+ fields=[
17+ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
18+ ('date', models.DateField(auto_now_add=True, verbose_name='Meal date')),
19+ ('time', models.TimeField(auto_now_add=True, verbose_name='Meal time')),
20+ ('text', models.TextField(verbose_name='Meal description or title')),
21+ ('calories', models.IntegerField()),
22+ ],
23+ ),
24+ ]
bmi_api/migrations/__init__.py+0−0
bmi_api/models.py+12−0
@@ -0,0 +1,12 @@
1+from django.db import models
2+
3+# Create your models here.
4+
5+class Meal(models.Model):
6+ date = models.DateField("Meal date", auto_now_add=True)
7+ time = models.TimeField("Meal time", auto_now_add=True)
8+ text = models.TextField("Meal description or title")
9+ calories = models.IntegerField()
10+
11+ def __str__(self):
12+ return self.text
bmi_api/serializers.py+8−0
@@ -0,0 +1,8 @@
1+from rest_framework import serializers
2+
3+from .models import Meal
4+
5+class MealSerializer(serializers.ModelSerializer):
6+ class Meta:
7+ model = Meal
8+ fields = '__all__'
bmi_api/tests.py+43−0
@@ -0,0 +1,43 @@
1+import json
2+from datetime import datetime, timedelta
3+
4+from django.test import TestCase, Client
5+from django.urls import reverse
6+
7+from rest_framework import status
8+
9+from .models import Meal
10+from .serializers import MealSerializer
11+
12+client = Client()
13+
14+class GetMealListTest(TestCase):
15+
16+ def setUp(self):
17+ eight_hours_later = datetime.now() + timedelta(hours=8)
18+ Meal.objects.create(
19+ text='Lunch time', calories='200')
20+ Meal.objects.create(
21+ text='Dinner time', calories='180', date=eight_hours_later, time=eight_hours_later.time())
22+
23+ def test_get_all_meals(self):
24+ response = client.get(reverse('meal_list'))
25+ serializer = MealSerializer(Meal.objects.all(), many=True)
26+
27+ self.assertEqual(response.data, serializer.data)
28+ self.assertEqual(response.status_code, status.HTTP_200_OK)
29+
30+ def test_create_new_meal(self):
31+ yesterday_lunch = datetime.now() - timedelta(hours=24)
32+ response = client.post(
33+ reverse('meal_list'),
34+ data=json.dumps({
35+ 'text': 'Quick small lunch',
36+ 'calories': 190,
37+ 'date': yesterday_lunch.__str__(),
38+ 'time': yesterday_lunch.time().__str__()
39+ }),
40+ content_type='application/json'
41+ )
42+
43+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)
bmi_api/views.py+49−0
@@ -0,0 +1,49 @@
1+from rest_framework.response import Response
2+from rest_framework.decorators import api_view
3+from rest_framework import status
4+
5+from .models import Meal
6+from .serializers import MealSerializer
7+
8+@api_view(['GET', 'POST'])
9+def meal_list(request):
10+ if request.method == 'GET':
11+ data = Meal.objects.all()
12+ serializer = MealSerializer(data, context={'request': request}, many=True)
13+
14+ return Response(serializer.data)
15+
16+ elif request.method == 'POST':
17+ serializer = MealSerializer(data=request.data)
18+
19+ if serializer.is_valid():
20+ serializer.save()
21+ return Response(status=status.HTTP_201_CREATED)
22+
23+ return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
24+
25+@api_view(['GET', 'PUT', 'DELETE'])
26+def meal_detail(request, pk):
27+ try:
28+ meal = Meal.objects.get(pk=pk)
29+ except Meal.DoesNotExist:
30+ return Response(status=status.HTTP_404_NOT_FOUND)
31+
32+ if request.method == 'GET':
33+ serializer = MealSerializer(meal, context={'request': request}, many=True)
34+
35+ return Response(serializer.data)
36+
37+ elif request.method == 'PUT':
38+ serializer = MealSerializer(data, context={'request': request})
39+
40+ if serializer.is_valid():
41+ serializer.save()
42+ return Response(status=status.HTTP_204_NO_CONTENT)
43+
44+ return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
45+
46+ elif request.method == 'DELETE':
47+ student.delete()
48+
49+ return Response(status=status.HTTP_204_NO_CONTENT)
bmi_track/__init__.py+0−0
bmi_track/asgi.py+16−0
@@ -0,0 +1,16 @@
1+"""
2+ASGI config for bmi_track project.
3+
4+It exposes the ASGI callable as a module-level variable named ``application``.
5+
6+For more information on this file, see
7+https://docs.djangoproject.com/en/3.0/howto/deployment/asgi/
8+"""
9+
10+import os
11+
12+from django.core.asgi import get_asgi_application
13+
14+os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bmi_track.settings')
15+
16+application = get_asgi_application()
bmi_track/settings.py+126−0
@@ -0,0 +1,126 @@
1+"""
2+Django settings for bmi_track project.
3+
4+Generated by 'django-admin startproject' using Django 3.0.4.
5+
6+For more information on this file, see
7+https://docs.djangoproject.com/en/3.0/topics/settings/
8+
9+For the full list of settings and their values, see
10+https://docs.djangoproject.com/en/3.0/ref/settings/
11+"""
12+
13+import os
14+
15+# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
16+BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
17+
18+
19+# Quick-start development settings - unsuitable for production
20+# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
21+
22+# SECURITY WARNING: keep the secret key used in production secret!
23+SECRET_KEY = 'vq52v33m71dr4$)42ufuyoskdxd)^y@dw4fsrz)-3bzg*&t)@k'
24+
25+# SECURITY WARNING: don't run with debug turned on in production!
26+DEBUG = True
27+
28+ALLOWED_HOSTS = []
29+
30+
31+# Application definition
32+
33+INSTALLED_APPS = [
34+ 'django.contrib.admin',
35+ 'django.contrib.auth',
36+ 'django.contrib.contenttypes',
37+ 'django.contrib.sessions',
38+ 'django.contrib.messages',
39+ 'django.contrib.staticfiles',
40+ 'rest_framework',
41+ 'corsheaders',
42+ 'bmi_api',
43+]
44+
45+MIDDLEWARE = [
46+ 'django.middleware.security.SecurityMiddleware',
47+ 'django.contrib.sessions.middleware.SessionMiddleware',
48+ 'django.middleware.common.CommonMiddleware',
49+ 'django.middleware.csrf.CsrfViewMiddleware',
50+ 'django.contrib.auth.middleware.AuthenticationMiddleware',
51+ 'django.contrib.messages.middleware.MessageMiddleware',
52+ 'django.middleware.clickjacking.XFrameOptionsMiddleware',
53+ 'corsheaders.middleware.CorsMiddleware',
54+]
55+
56+CORS_ORIGIN_ALLOW_ALL = True
57+
58+ROOT_URLCONF = 'bmi_track.urls'
59+
60+TEMPLATES = [
61+ {
62+ 'BACKEND': 'django.template.backends.django.DjangoTemplates',
63+ 'DIRS': [],
64+ 'APP_DIRS': True,
65+ 'OPTIONS': {
66+ 'context_processors': [
67+ 'django.template.context_processors.debug',
68+ 'django.template.context_processors.request',
69+ 'django.contrib.auth.context_processors.auth',
70+ 'django.contrib.messages.context_processors.messages',
71+ ],
72+ },
73+ },
74+]
75+
76+WSGI_APPLICATION = 'bmi_track.wsgi.application'
77+
78+
79+# Database
80+# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
81+
82+DATABASES = {
83+ 'default': {
84+ 'ENGINE': 'django.db.backends.sqlite3',
85+ 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
86+ }
87+}
88+
89+
90+# Password validation
91+# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators
92+
93+AUTH_PASSWORD_VALIDATORS = [
94+ {
95+ 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
96+ },
97+ {
98+ 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
99+ },
100+ {
101+ 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
102+ },
103+ {
104+ 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
105+ },
106+]
107+
108+
109+# Internationalization
110+# https://docs.djangoproject.com/en/3.0/topics/i18n/
111+
112+LANGUAGE_CODE = 'en-us'
113+
114+TIME_ZONE = 'UTC'
115+
116+USE_I18N = True
117+
118+USE_L10N = True
119+
120+USE_TZ = True
121+
122+
123+# Static files (CSS, JavaScript, Images)
124+# https://docs.djangoproject.com/en/3.0/howto/static-files/
125+
126+STATIC_URL = '/static/'
bmi_track/urls.py+25−0
@@ -0,0 +1,25 @@
1+"""bmi_track URL Configuration
2+
3+The `urlpatterns` list routes URLs to views. For more information please see:
4+ https://docs.djangoproject.com/en/3.0/topics/http/urls/
5+Examples:
6+Function views
7+ 1. Add an import: from my_app import views
8+ 2. Add a URL to urlpatterns: path('', views.home, name='home')
9+Class-based views
10+ 1. Add an import: from other_app.views import Home
11+ 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
12+Including another URLconf
13+ 1. Import the include() function: from django.urls import include, path
14+ 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
15+"""
16+from django.contrib import admin
17+from django.urls import path, re_path
18+
19+from bmi_api import views
20+
21+urlpatterns = [
22+ path('admin/', admin.site.urls),
23+ re_path(r'api/meals/$', views.meal_list, name='meal_list'),
24+ re_path(r'api/meals/(?P<pk>[0-9]+)$', views.meal_detail, name='meal_detail'),
25+]
bmi_track/wsgi.py+16−0
@@ -0,0 +1,16 @@
1+"""
2+WSGI config for bmi_track project.
3+
4+It exposes the WSGI callable as a module-level variable named ``application``.
5+
6+For more information on this file, see
7+https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/
8+"""
9+
10+import os
11+
12+from django.core.wsgi import get_wsgi_application
13+
14+os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bmi_track.settings')
15+
16+application = get_wsgi_application()
db.sqlite3+0−0
Binary file, not shown.
manage.py+21−0
@@ -0,0 +1,21 @@
1+#!/usr/bin/env python
2+"""Django's command-line utility for administrative tasks."""
3+import os
4+import sys
5+
6+
7+def main():
8+ os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bmi_track.settings')
9+ try:
10+ from django.core.management import execute_from_command_line
11+ except ImportError as exc:
12+ raise ImportError(
13+ "Couldn't import Django. Are you sure it's installed and "
14+ "available on your PYTHONPATH environment variable? Did you "
15+ "forget to activate a virtual environment?"
16+ ) from exc
17+ execute_from_command_line(sys.argv)
18+
19+
20+if __name__ == '__main__':
21+ main()