From c066b3fcdc4dfcec83d94dc2750051f3d66dae0f Mon Sep 17 00:00:00 2001 From: Donghyun Koh Date: Thu, 13 Oct 2022 14:31:05 +0900 Subject: [PATCH] Finish Lab --- toh/hero/__init__.py | 0 toh/hero/admin.py | 3 + toh/hero/apps.py | 6 + toh/hero/migrations/0001_initial.py | 21 ++++ toh/hero/migrations/0002_hero_age.py | 18 +++ toh/hero/migrations/0003_alter_hero_age.py | 18 +++ toh/hero/migrations/0004_team.py | 23 ++++ toh/hero/migrations/0005_hero_score.py | 18 +++ toh/hero/migrations/__init__.py | 0 toh/hero/models.py | 32 ++++++ toh/hero/tests.py | 3 + toh/hero/urls.py | 10 ++ toh/hero/views.py | 64 +++++++++++ toh/manage.py | 22 ++++ toh/toh/__init__.py | 0 toh/toh/asgi.py | 16 +++ toh/toh/settings.py | 124 +++++++++++++++++++++ toh/toh/urls.py | 22 ++++ toh/toh/wsgi.py | 16 +++ 19 files changed, 416 insertions(+) create mode 100644 toh/hero/__init__.py create mode 100644 toh/hero/admin.py create mode 100644 toh/hero/apps.py create mode 100644 toh/hero/migrations/0001_initial.py create mode 100644 toh/hero/migrations/0002_hero_age.py create mode 100644 toh/hero/migrations/0003_alter_hero_age.py create mode 100644 toh/hero/migrations/0004_team.py create mode 100644 toh/hero/migrations/0005_hero_score.py create mode 100644 toh/hero/migrations/__init__.py create mode 100644 toh/hero/models.py create mode 100644 toh/hero/tests.py create mode 100644 toh/hero/urls.py create mode 100644 toh/hero/views.py create mode 100755 toh/manage.py create mode 100644 toh/toh/__init__.py create mode 100644 toh/toh/asgi.py create mode 100644 toh/toh/settings.py create mode 100644 toh/toh/urls.py create mode 100644 toh/toh/wsgi.py 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..b1b4884 --- /dev/null +++ b/toh/hero/migrations/0001_initial.py @@ -0,0 +1,21 @@ +# Generated by Django 4.1.2 on 2022-10-12 10:48 + +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..64c87c9 --- /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:29 + +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_alter_hero_age.py b/toh/hero/migrations/0003_alter_hero_age.py new file mode 100644 index 0000000..c541764 --- /dev/null +++ b/toh/hero/migrations/0003_alter_hero_age.py @@ -0,0 +1,18 @@ +# Generated by Django 4.1.2 on 2022-10-12 11:33 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('hero', '0002_hero_age'), + ] + + operations = [ + migrations.AlterField( + model_name='hero', + name='age', + field=models.IntegerField(blank=True, default=25), + ), + ] diff --git a/toh/hero/migrations/0004_team.py b/toh/hero/migrations/0004_team.py new file mode 100644 index 0000000..ea674b8 --- /dev/null +++ b/toh/hero/migrations/0004_team.py @@ -0,0 +1,23 @@ +# Generated by Django 4.1.2 on 2022-10-13 05:07 + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + dependencies = [ + ('hero', '0003_alter_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/0005_hero_score.py b/toh/hero/migrations/0005_hero_score.py new file mode 100644 index 0000000..8cd9835 --- /dev/null +++ b/toh/hero/migrations/0005_hero_score.py @@ -0,0 +1,18 @@ +# Generated by Django 4.1.2 on 2022-10-13 05:28 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('hero', '0004_team'), + ] + + operations = [ + migrations.AddField( + model_name='hero', + name='score', + field=models.IntegerField(default=0), + ), + ] 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..00149c1 --- /dev/null +++ b/toh/hero/models.py @@ -0,0 +1,32 @@ +from sre_constants import MAX_UNTIL +from django.db import models + +# Create your models here. + + +class Hero(models.Model): + name = models.CharField(max_length=120) + age = models.IntegerField(blank=True, default=25) + score = models.IntegerField(default=0) + + def __str__(self): + return self.name + + def introduce(self): + print(f"Hello, my name is {self.name} and my score is {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 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..d8d8f06 --- /dev/null +++ b/toh/hero/urls.py @@ -0,0 +1,10 @@ +from django.urls import path + +from . import views + +urlpatterns = [ + path("", views.hero_list), + path("", views.hero_id, name="hero_id"), + path("", views.hero_name, name="hero_name"), + path("info/", views.hero_info, name="hero_info"), +] diff --git a/toh/hero/views.py b/toh/hero/views.py new file mode 100644 index 0000000..066c430 --- /dev/null +++ b/toh/hero/views.py @@ -0,0 +1,64 @@ +import re +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 + +# Create your views here. + + +def index(request): + return HttpResponse("Hello, world!") + + +def hero_id(request, id=0): + return HttpResponse("Your id is %d!" % id) + + +def hero_name(request, name=""): + return HttpResponse("Your name is %s!" % name) + + +@csrf_exempt +def hero_info(request, id=0): + if request.method == "GET": + hero = Hero.objects.get(id=id) + return JsonResponse({"id": hero.id, "name": hero.name, "age": hero.age}) + elif request.method == "PUT": + try: + body = request.body.decode() + except: + return HttpResponseBadRequest() + hero = Hero.objects.get(id=id) + hero.name = json.loads(body)["name"] + hero.age = json.loads(body)["age"] + hero.save() + response_dict = {"id": hero.id, "name": hero.name, "age": hero.age} + return JsonResponse(response_dict) + else: + return HttpResponseNotAllowed(["GET", "PUT"]) + + +@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"] + except (KeyError, JSONDecodeError) as e: + return HttpResponseBadRequest() + hero = Hero(name=hero_name) + hero.save() + response_dict = {"id": hero.id, "name": hero.name} + return JsonResponse(response_dict, status=201) + else: + return HttpResponseNotAllowed(["GET", "POST"]) diff --git a/toh/manage.py b/toh/manage.py new file mode 100755 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..0077303 --- /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-+hg^7u_27m4u)4((x8d_x$e7ab$_$5lh+c2^l9n^&(vt_be52w" + +# 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..138be6d --- /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 include, path + +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()