From 6526a163ff3eb05c393cc36e96a8088ddb9f15a1 Mon Sep 17 00:00:00 2001 From: insung151 Date: Thu, 13 Oct 2022 11:02:20 +0900 Subject: [PATCH] pratice 6 --- Pipfile | 12 +++ Pipfile.lock | 67 +++++++++++++ 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_team.py | 23 +++++ toh/hero/migrations/0004_hero_score.py | 18 ++++ toh/hero/migrations/__init__.py | 0 toh/hero/models.py | 27 ++++++ toh/hero/tests.py | 3 + toh/hero/urls.py | 9 ++ toh/hero/views.py | 53 +++++++++++ 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 ++++ 20 files changed, 460 insertions(+) create mode 100644 Pipfile create mode 100644 Pipfile.lock 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_team.py create mode 100644 toh/hero/migrations/0004_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/Pipfile b/Pipfile new file mode 100644 index 0000000..4ffc25f --- /dev/null +++ b/Pipfile @@ -0,0 +1,12 @@ +[[source]] +url = "https://pypi.org/simple" +verify_ssl = true +name = "pypi" + +[packages] +django = "==4.1" + +[dev-packages] + +[requires] +python_version = "3.8" diff --git a/Pipfile.lock b/Pipfile.lock new file mode 100644 index 0000000..876f57e --- /dev/null +++ b/Pipfile.lock @@ -0,0 +1,67 @@ +{ + "_meta": { + "hash": { + "sha256": "177a152b6d274bd594bfefead19f8d1981a5cb9fac7358056130ffe353efad4f" + }, + "pipfile-spec": 6, + "requires": { + "python_version": "3.8" + }, + "sources": [ + { + "name": "pypi", + "url": "https://pypi.org/simple", + "verify_ssl": true + } + ] + }, + "default": { + "asgiref": { + "hashes": [ + "sha256:1d2880b792ae8757289136f1db2b7b99100ce959b2aa57fd69dab783d05afac4", + "sha256:4a29362a6acebe09bf1d6640db38c1dc3d9217c68e6f9f6204d72667fc19a424" + ], + "markers": "python_version >= '3.7'", + "version": "==3.5.2" + }, + "backports.zoneinfo": { + "hashes": [ + "sha256:17746bd546106fa389c51dbea67c8b7c8f0d14b5526a579ca6ccf5ed72c526cf", + "sha256:1b13e654a55cd45672cb54ed12148cd33628f672548f373963b0bff67b217328", + "sha256:1c5742112073a563c81f786e77514969acb58649bcdf6cdf0b4ed31a348d4546", + "sha256:4a0f800587060bf8880f954dbef70de6c11bbe59c673c3d818921f042f9954a6", + "sha256:5c144945a7752ca544b4b78c8c41544cdfaf9786f25fe5ffb10e838e19a27570", + "sha256:7b0a64cda4145548fed9efc10322770f929b944ce5cee6c0dfe0c87bf4c0c8c9", + "sha256:8439c030a11780786a2002261569bdf362264f605dfa4d65090b64b05c9f79a7", + "sha256:8961c0f32cd0336fb8e8ead11a1f8cd99ec07145ec2931122faaac1c8f7fd987", + "sha256:89a48c0d158a3cc3f654da4c2de1ceba85263fafb861b98b59040a5086259722", + "sha256:a76b38c52400b762e48131494ba26be363491ac4f9a04c1b7e92483d169f6582", + "sha256:da6013fd84a690242c310d77ddb8441a559e9cb3d3d59ebac9aca1a57b2e18bc", + "sha256:e55b384612d93be96506932a786bbcde5a2db7a9e6a4bb4bffe8b733f5b9036b", + "sha256:e81b76cace8eda1fca50e345242ba977f9be6ae3945af8d46326d776b4cf78d1", + "sha256:e8236383a20872c0cdf5a62b554b27538db7fa1bbec52429d8d106effbaeca08", + "sha256:f04e857b59d9d1ccc39ce2da1021d196e47234873820cbeaad210724b1ee28ac", + "sha256:fadbfe37f74051d024037f223b8e001611eac868b5c5b06144ef4d8b799862f2" + ], + "markers": "python_version < '3.9'", + "version": "==0.2.1" + }, + "django": { + "hashes": [ + "sha256:031ccb717782f6af83a0063a1957686e87cb4581ea61b47b3e9addf60687989a", + "sha256:032f8a6fc7cf05ccd1214e4a2e21dfcd6a23b9d575c6573cacc8c67828dbe642" + ], + "index": "pypi", + "version": "==4.1" + }, + "sqlparse": { + "hashes": [ + "sha256:0323c0ec29cd52bceabc1b4d9d579e311f3e4961b98d174201d5622a23b85e34", + "sha256:69ca804846bb114d2ec380e4360a8a340db83f0ccf3afceeb1404df028f57268" + ], + "markers": "python_version >= '3.5'", + "version": "==0.4.3" + } + }, + "develop": {} +} 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..e9c983b --- /dev/null +++ b/toh/hero/migrations/0001_initial.py @@ -0,0 +1,21 @@ +# Generated by Django 4.1.2 on 2022-10-10 15:37 + +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..e5ef436 --- /dev/null +++ b/toh/hero/migrations/0002_hero_age.py @@ -0,0 +1,18 @@ +# Generated by Django 4.1.2 on 2022-10-10 18:06 + +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..3551922 --- /dev/null +++ b/toh/hero/migrations/0003_team.py @@ -0,0 +1,23 @@ +# Generated by Django 4.1.2 on 2022-10-10 18:25 + +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..5577e28 --- /dev/null +++ b/toh/hero/migrations/0004_hero_score.py @@ -0,0 +1,18 @@ +# Generated by Django 4.1.2 on 2022-10-10 18:35 + +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(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..b10832f --- /dev/null +++ b/toh/hero/models.py @@ -0,0 +1,27 @@ +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) + + 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 \ 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..7384e1e --- /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.id, name='hero_id'), + path('/', views.name, name='hero_name'), + path('info//', views.hero_info, name='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..d86c570 --- /dev/null +++ b/toh/hero/views.py @@ -0,0 +1,53 @@ +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 id(request, id): + return HttpResponse(f'Your id is {id}!') + +def name(request, name): + return HttpResponse(f'Your name is {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'] + 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']) + +@csrf_exempt +def hero_info(request, id): + 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() + 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, status=200) + else: + return HttpResponseNotAllowed(['GET', 'PUT']) \ No newline at end of file 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..731ead0 --- /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-x*cal+4dr^5wqe&0modde7$72#ck2zxe-&e=uhfvdal6(22!o)' + +# SECURITY WARNING: don't run with debug turned on in production! +DEBUG = True + +ALLOWED_HOSTS = ['127.0.0.1','0.0.0.0', 'localhost'] + + +# 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..8c57ad4 --- /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()