diff --git a/toh/hero/__init__.py b/toh/hero/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/toh/hero/admin.py b/toh/hero/admin.py new file mode 100644 index 0000000..8c38f3f --- /dev/null +++ b/toh/hero/admin.py @@ -0,0 +1,3 @@ +from django.contrib import admin + +# Register your models here. diff --git a/toh/hero/apps.py b/toh/hero/apps.py new file mode 100644 index 0000000..d673eaa --- /dev/null +++ b/toh/hero/apps.py @@ -0,0 +1,6 @@ +from django.apps import AppConfig + + +class HeroConfig(AppConfig): + default_auto_field = 'django.db.models.BigAutoField' + name = 'hero' diff --git a/toh/hero/migrations/0001_initial.py b/toh/hero/migrations/0001_initial.py new file mode 100644 index 0000000..301d731 --- /dev/null +++ b/toh/hero/migrations/0001_initial.py @@ -0,0 +1,21 @@ +# Generated by Django 4.1.2 on 2022-10-12 10:49 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ] + + operations = [ + migrations.CreateModel( + name='Hero', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('name', models.CharField(max_length=120)), + ], + ), + ] diff --git a/toh/hero/migrations/0002_hero_age.py b/toh/hero/migrations/0002_hero_age.py new file mode 100644 index 0000000..a34b8c8 --- /dev/null +++ b/toh/hero/migrations/0002_hero_age.py @@ -0,0 +1,18 @@ +# Generated by Django 4.1.2 on 2022-10-12 11:36 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('hero', '0001_initial'), + ] + + operations = [ + migrations.AddField( + model_name='hero', + name='age', + field=models.IntegerField(blank=True, null=True), + ), + ] diff --git a/toh/hero/migrations/0003_team.py b/toh/hero/migrations/0003_team.py new file mode 100644 index 0000000..fdc75bc --- /dev/null +++ b/toh/hero/migrations/0003_team.py @@ -0,0 +1,23 @@ +# Generated by Django 4.1.2 on 2022-10-13 03:11 + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + dependencies = [ + ('hero', '0002_hero_age'), + ] + + operations = [ + migrations.CreateModel( + name='Team', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('name', models.CharField(max_length=120)), + ('leader', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='leader_set', to='hero.hero')), + ('members', models.ManyToManyField(related_name='teams', to='hero.hero')), + ], + ), + ] diff --git a/toh/hero/migrations/0004_hero_score.py b/toh/hero/migrations/0004_hero_score.py new file mode 100644 index 0000000..4f7b672 --- /dev/null +++ b/toh/hero/migrations/0004_hero_score.py @@ -0,0 +1,18 @@ +# Generated by Django 4.1.2 on 2022-10-13 03:28 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('hero', '0003_team'), + ] + + operations = [ + migrations.AddField( + model_name='hero', + name='score', + field=models.IntegerField(blank=True, default=0, null=True), + ), + ] diff --git a/toh/hero/migrations/__init__.py b/toh/hero/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/toh/hero/models.py b/toh/hero/models.py new file mode 100644 index 0000000..296c865 --- /dev/null +++ b/toh/hero/models.py @@ -0,0 +1,30 @@ +from django.db import models + +class Hero(models.Model): + name = models.CharField(max_length=120) + + age = models.IntegerField(blank=True, null=True) + + score = models.IntegerField(default =0, blank=True, null=True) + + def __str__(self): + return self.name + + def introduce(self): + return "Hello, my name is {} and my score is {}!".format(self.name, self.score) + +class Team(models.Model): + name = models.CharField(max_length=120) + leader = models.ForeignKey( + Hero, + on_delete=models.CASCADE, + related_name = 'leader_set', + ) + members = models.ManyToManyField( + Hero, + related_name = 'teams', + ) + + def __str__(self): + return self.name + \ No newline at end of file diff --git a/toh/hero/tests.py b/toh/hero/tests.py new file mode 100644 index 0000000..7ce503c --- /dev/null +++ b/toh/hero/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/toh/hero/urls.py b/toh/hero/urls.py new file mode 100644 index 0000000..4e70a23 --- /dev/null +++ b/toh/hero/urls.py @@ -0,0 +1,9 @@ +from django.urls import path +from . import views + +urlpatterns = [ + path('', views.hero_list), + path('/', views.hero_id), + path('/', views.hero_name), + path('info//', views.hero_info), +] \ No newline at end of file diff --git a/toh/hero/views.py b/toh/hero/views.py new file mode 100644 index 0000000..ed25d76 --- /dev/null +++ b/toh/hero/views.py @@ -0,0 +1,59 @@ +from django.shortcuts import render +from django.http import HttpResponse,HttpResponseBadRequest, HttpResponseNotAllowed, JsonResponse +from django.views.decorators.csrf import csrf_exempt +import json +from json.decoder import JSONDecodeError +from .models import Hero + +def index(request): + return HttpResponse("Hello, world!") + +def hero_id(request, id = 0): + return HttpResponse("Your id is {}!".format(id)) + +def hero_name(request, name=""): + return HttpResponse("Your name is {}!".format(name)) + +@csrf_exempt +def hero_list(request): + if request.method == 'GET': + hero_all_list = [hero for hero in Hero.objects.all().values()] + return JsonResponse(hero_all_list, safe=False) + elif request.method == 'POST': + try: + body = request.body.decode() + hero_name = json.loads(body)['name'] + hero_age = json.loads(body)['age'] + except (KeyError, JSONDecodeError) as e: + return HttpResponseBadRequest() + hero = Hero(name=hero_name, age = hero_age) + hero.save() + response_dict = {'id': hero.id, 'name': hero.name, 'age':str(hero.age)} + return JsonResponse(response_dict, status=201) + else: + return HttpResponseNotAllowed(['GET''POST']) + +@csrf_exempt +def hero_info(request, id): + if request.method == 'GET': + hero = Hero.objects.get(id = id) + response_dict= {'id': hero.id, 'name': hero.name, 'age':str(hero.age)} + return JsonResponse(response_dict) + elif request.method == 'PUT': + try: + body = request.body.decode() + hero_name = json.loads(body)['name'] + hero_age = json.loads(body)['age'] + except (KeyError, JSONDecodeError) as e: + return HttpResponseBadRequest() + hero = Hero.objects.get(id = id) + hero.name = hero_name + hero.age = hero_age + hero.save() + response_dict= {'id': hero.id, 'name': hero.name, 'age':hero.age} + return JsonResponse(response_dict) + else: + return HttpResponseNotAllowed(['GET''PUT']) + +# Create your views here. +# curl -X PUT -H "Content-Type: application/json" -d "{\"name\":\"Batman\", \"age\": \"50\"}" http://127.0.0.1:8000/hero/info/1/ diff --git a/toh/manage.py b/toh/manage.py new file mode 100644 index 0000000..04f198e --- /dev/null +++ b/toh/manage.py @@ -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', 'toh.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() diff --git a/toh/toh/__init__.py b/toh/toh/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/toh/toh/asgi.py b/toh/toh/asgi.py new file mode 100644 index 0000000..940b9f8 --- /dev/null +++ b/toh/toh/asgi.py @@ -0,0 +1,16 @@ +""" +ASGI config for toh 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.1/howto/deployment/asgi/ +""" + +import os + +from django.core.asgi import get_asgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'toh.settings') + +application = get_asgi_application() diff --git a/toh/toh/settings.py b/toh/toh/settings.py new file mode 100644 index 0000000..ba8b7d0 --- /dev/null +++ b/toh/toh/settings.py @@ -0,0 +1,124 @@ +""" +Django settings for toh project. + +Generated by 'django-admin startproject' using Django 4.1.2. + +For more information on this file, see +https://docs.djangoproject.com/en/4.1/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/4.1/ref/settings/ +""" + +from pathlib import Path + +# 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.1/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = 'django-insecure-j#=*36)1f_47yuy)#j0eq82t#zcxv&1j*zm)kzbnofd#3s#wue' + +# SECURITY WARNING: don't run with debug turned on in production! +DEBUG = True + +ALLOWED_HOSTS = [] + + +# Application definition + +INSTALLED_APPS = [ + 'hero.apps.HeroConfig', + 'django.contrib.admin', + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.messages', + 'django.contrib.staticfiles', +] + +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', +] + +ROOT_URLCONF = 'toh.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 = 'toh.wsgi.application' + + +# Database +# https://docs.djangoproject.com/en/4.1/ref/settings/#databases + +DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.sqlite3', + 'NAME': BASE_DIR / 'db.sqlite3', + } +} + + +# Password validation +# https://docs.djangoproject.com/en/4.1/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.1/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.1/howto/static-files/ + +STATIC_URL = 'static/' + +# Default primary key field type +# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field + +DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' diff --git a/toh/toh/urls.py b/toh/toh/urls.py new file mode 100644 index 0000000..331e92d --- /dev/null +++ b/toh/toh/urls.py @@ -0,0 +1,22 @@ +"""toh URL Configuration + +The `urlpatterns` list routes URLs to views. For more information please see: + https://docs.djangoproject.com/en/4.1/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('hero/', include('hero.urls')), + path('admin/', admin.site.urls), +] diff --git a/toh/toh/wsgi.py b/toh/toh/wsgi.py new file mode 100644 index 0000000..97b4d40 --- /dev/null +++ b/toh/toh/wsgi.py @@ -0,0 +1,16 @@ +""" +WSGI config for toh 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.1/howto/deployment/wsgi/ +""" + +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'toh.settings') + +application = get_wsgi_application()