diff --git a/.DS_Store b/.DS_Store index 272c880..b29301b 100644 Binary files a/.DS_Store and b/.DS_Store differ diff --git "a/11\354\243\274\354\260\250_Django(4)/week11/myblog/.DS_Store" "b/11\354\243\274\354\260\250_Django(4)/week11/myblog/.DS_Store" new file mode 100644 index 0000000..8b48058 Binary files /dev/null and "b/11\354\243\274\354\260\250_Django(4)/week11/myblog/.DS_Store" differ diff --git a/HW12/apiproject/apiproject/__init__.py b/HW12/apiproject/apiproject/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/HW12/apiproject/apiproject/asgi.py b/HW12/apiproject/apiproject/asgi.py new file mode 100644 index 0000000..c3fb0c2 --- /dev/null +++ b/HW12/apiproject/apiproject/asgi.py @@ -0,0 +1,16 @@ +""" +ASGI config for apiproject 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.0/howto/deployment/asgi/ +""" + +import os + +from django.core.asgi import get_asgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'apiproject.settings') + +application = get_asgi_application() diff --git a/HW12/apiproject/apiproject/settings.py b/HW12/apiproject/apiproject/settings.py new file mode 100644 index 0000000..669099e --- /dev/null +++ b/HW12/apiproject/apiproject/settings.py @@ -0,0 +1,126 @@ +""" +Django settings for apiproject project. + +Generated by 'django-admin startproject' using Django 4.0.6. + +For more information on this file, see +https://docs.djangoproject.com/en/4.0/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/4.0/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.0/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = 'django-insecure-vtlx_=#j2b_jdo*7kr3koq87gy@uecjis2l=%iuf7bzs^znfk5' + +# SECURITY WARNING: don't run with debug turned on in production! +DEBUG = True + +ALLOWED_HOSTS = [] + + +# Application definition + +INSTALLED_APPS = [ + 'django.contrib.admin', + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.messages', + 'django.contrib.staticfiles', + 'blogapp', + 'rest_framework', + 'commentapp', +] + +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 = 'apiproject.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 = 'apiproject.wsgi.application' + + +# Database +# https://docs.djangoproject.com/en/4.0/ref/settings/#databases + +DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.sqlite3', + 'NAME': BASE_DIR / 'db.sqlite3', + } +} + + +# Password validation +# https://docs.djangoproject.com/en/4.0/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.0/topics/i18n/ + +LANGUAGE_CODE = 'en-us' + +TIME_ZONE = 'Asia/Seoul' + +USE_I18N = True + +USE_TZ = False + + +# Static files (CSS, JavaScript, Images) +# https://docs.djangoproject.com/en/4.0/howto/static-files/ + +STATIC_URL = 'static/' + +# Default primary key field type +# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field + +DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' diff --git a/HW12/apiproject/apiproject/urls.py b/HW12/apiproject/apiproject/urls.py new file mode 100644 index 0000000..d9e319f --- /dev/null +++ b/HW12/apiproject/apiproject/urls.py @@ -0,0 +1,23 @@ +"""apiproject URL Configuration + +The `urlpatterns` list routes URLs to views. For more information please see: + https://docs.djangoproject.com/en/4.0/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('admin/', admin.site.urls), + path('blog/', include('blogapp.urls')), + path('comment/', include('commentapp.urls')), +] diff --git a/HW12/apiproject/apiproject/wsgi.py b/HW12/apiproject/apiproject/wsgi.py new file mode 100644 index 0000000..ca6d0c8 --- /dev/null +++ b/HW12/apiproject/apiproject/wsgi.py @@ -0,0 +1,16 @@ +""" +WSGI config for apiproject 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.0/howto/deployment/wsgi/ +""" + +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'apiproject.settings') + +application = get_wsgi_application() diff --git a/HW12/apiproject/blogapp/__init__.py b/HW12/apiproject/blogapp/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/HW12/apiproject/blogapp/admin.py b/HW12/apiproject/blogapp/admin.py new file mode 100644 index 0000000..c40b8e4 --- /dev/null +++ b/HW12/apiproject/blogapp/admin.py @@ -0,0 +1,5 @@ +from django.contrib import admin +from blogapp.models import Blog + +# Register your models here. +admin.site.register(Blog) \ No newline at end of file diff --git a/HW12/apiproject/blogapp/apps.py b/HW12/apiproject/blogapp/apps.py new file mode 100644 index 0000000..d50a428 --- /dev/null +++ b/HW12/apiproject/blogapp/apps.py @@ -0,0 +1,6 @@ +from django.apps import AppConfig + + +class BlogappConfig(AppConfig): + default_auto_field = 'django.db.models.BigAutoField' + name = 'blogapp' diff --git a/HW12/apiproject/blogapp/migrations/0001_initial.py b/HW12/apiproject/blogapp/migrations/0001_initial.py new file mode 100644 index 0000000..fab6720 --- /dev/null +++ b/HW12/apiproject/blogapp/migrations/0001_initial.py @@ -0,0 +1,23 @@ +# Generated by Django 4.0.6 on 2022-07-25 14:32 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ] + + operations = [ + migrations.CreateModel( + name='Blog', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('title', models.CharField(max_length=50)), + ('date', models.DateTimeField(auto_now_add=True)), + ('body', models.TextField()), + ], + ), + ] diff --git a/HW12/apiproject/blogapp/migrations/__init__.py b/HW12/apiproject/blogapp/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/HW12/apiproject/blogapp/models.py b/HW12/apiproject/blogapp/models.py new file mode 100644 index 0000000..2241aa5 --- /dev/null +++ b/HW12/apiproject/blogapp/models.py @@ -0,0 +1,13 @@ +from django.db import models + +# Create your models here. +class Blog(models.Model): + title = models.CharField(max_length=50) + date = models.DateTimeField(auto_now_add=True) + body = models.TextField() + + def __str__(self): + return self.title + + def summary(self): + return self.body[:30] diff --git a/HW12/apiproject/blogapp/serializers.py b/HW12/apiproject/blogapp/serializers.py new file mode 100644 index 0000000..45be6c8 --- /dev/null +++ b/HW12/apiproject/blogapp/serializers.py @@ -0,0 +1,12 @@ +from rest_framework import serializers +from blogapp.models import Blog + +class BlogSerializer(serializers.ModelSerializer): # 글 작성 + class Meta: + model = Blog + fields = ('id', 'title', 'date', 'body') + +class BlogListSerializer(serializers.ModelSerializer): # 글 목록 조회 + class Meta: + model = Blog + fields = ('id', 'title', 'date', 'summary') \ No newline at end of file diff --git a/HW12/apiproject/blogapp/tests.py b/HW12/apiproject/blogapp/tests.py new file mode 100644 index 0000000..7ce503c --- /dev/null +++ b/HW12/apiproject/blogapp/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/HW12/apiproject/blogapp/urls.py b/HW12/apiproject/blogapp/urls.py new file mode 100644 index 0000000..9e8e4d1 --- /dev/null +++ b/HW12/apiproject/blogapp/urls.py @@ -0,0 +1,7 @@ +from django.urls import path +from blogapp.views import BlogList, BlogDetail + +urlpatterns = [ + path('main/', BlogList.as_view()), + path('main/', BlogDetail.as_view()), +] diff --git a/HW12/apiproject/blogapp/views.py b/HW12/apiproject/blogapp/views.py new file mode 100644 index 0000000..e4ed551 --- /dev/null +++ b/HW12/apiproject/blogapp/views.py @@ -0,0 +1,48 @@ +from rest_framework import status +from rest_framework.views import APIView +from rest_framework.response import Response + +from .serializers import BlogSerializer, BlogListSerializer +from .models import Blog + +from django.http import Http404 + +# Create your views here. +class BlogList(APIView): + def get(self, request): # 글 목록 조회하는 경우 + blogs = Blog.objects.all() + + serializer = BlogListSerializer(blogs, many=True) # 다수의 쿼리셋 전달 위해서 many = True + return Response(serializer.data) + + def post(self, request): # 글 작성하는 경우 + serializer = BlogSerializer(data = request.data) + if serializer.is_valid(): + serializer.save() + return Response(serializer.data, status=status.HTTP_201_CREATED) + return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) + +class BlogDetail(APIView): + def get_object(self, pk): # blog 객체 가져오기 + try: + return Blog.objects.get(pk=pk) + except Blog.DoesNotExist: + raise Http404 + + def get(self, request, pk): # blog 상세조회 + blog = self.get_object(pk) + serializer = BlogSerializer(blog) + return Response(serializer.data) + + def put(self, request, pk): # blog 수정 + blog = self.get_object(pk) + serializer = BlogSerializer(blog, data=request.data) + if serializer.is_valid(): + serializer.save() + return Response(serializer.data, status=status.HTTP_200_OK) + return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) + + def delete(self, request, pk): + blog = self.get_object(pk) + blog.delete() + return Response(status=status.HTTP_204_NO_CONTENT) diff --git a/HW12/apiproject/commentapp/__init__.py b/HW12/apiproject/commentapp/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/HW12/apiproject/commentapp/admin.py b/HW12/apiproject/commentapp/admin.py new file mode 100644 index 0000000..b992b77 --- /dev/null +++ b/HW12/apiproject/commentapp/admin.py @@ -0,0 +1,5 @@ +from django.contrib import admin +from commentapp.models import Comment + +# Register your models here. +admin.site.register(Comment) \ No newline at end of file diff --git a/HW12/apiproject/commentapp/apps.py b/HW12/apiproject/commentapp/apps.py new file mode 100644 index 0000000..f03b6eb --- /dev/null +++ b/HW12/apiproject/commentapp/apps.py @@ -0,0 +1,6 @@ +from django.apps import AppConfig + + +class CommentappConfig(AppConfig): + default_auto_field = 'django.db.models.BigAutoField' + name = 'commentapp' diff --git a/HW12/apiproject/commentapp/migrations/0001_initial.py b/HW12/apiproject/commentapp/migrations/0001_initial.py new file mode 100644 index 0000000..1c346a7 --- /dev/null +++ b/HW12/apiproject/commentapp/migrations/0001_initial.py @@ -0,0 +1,26 @@ +# Generated by Django 4.0.6 on 2022-07-25 14:32 + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ('blogapp', '0001_initial'), + ] + + operations = [ + migrations.CreateModel( + name='Comment', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('content', models.CharField(max_length=200)), + ('created_at', models.DateTimeField(auto_now_add=True)), + ('updated_at', models.DateTimeField(auto_now=True)), + ('blog', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='blogapp.blog')), + ], + ), + ] diff --git a/HW12/apiproject/commentapp/migrations/__init__.py b/HW12/apiproject/commentapp/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/HW12/apiproject/commentapp/models.py b/HW12/apiproject/commentapp/models.py new file mode 100644 index 0000000..d5d0442 --- /dev/null +++ b/HW12/apiproject/commentapp/models.py @@ -0,0 +1,13 @@ +from django.db import models + +from blogapp.models import Blog + +# Create your models here. +class Comment(models.Model): + blog = models.ForeignKey(Blog, on_delete=models.CASCADE) + content = models.CharField(max_length=200) + created_at = models.DateTimeField(auto_now_add=True) + updated_at = models.DateTimeField(auto_now = True) + + def __str__(self): + return self.content diff --git a/HW12/apiproject/commentapp/serializers.py b/HW12/apiproject/commentapp/serializers.py new file mode 100644 index 0000000..f45faa1 --- /dev/null +++ b/HW12/apiproject/commentapp/serializers.py @@ -0,0 +1,12 @@ +from rest_framework import serializers +from commentapp.models import Comment + +class CommentSerializer(serializers.ModelSerializer): # 댓글 작성 + class Meta: + model = Comment + fields = ('id', 'blog', 'content') + +class CommentListSerializer(serializers.ModelSerializer): # 댓글 조회 + class Meta: + model = Comment + fields = ('id', 'blog', 'content', 'created_at') \ No newline at end of file diff --git a/HW12/apiproject/commentapp/tests.py b/HW12/apiproject/commentapp/tests.py new file mode 100644 index 0000000..7ce503c --- /dev/null +++ b/HW12/apiproject/commentapp/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/HW12/apiproject/commentapp/urls.py b/HW12/apiproject/commentapp/urls.py new file mode 100644 index 0000000..f9db56c --- /dev/null +++ b/HW12/apiproject/commentapp/urls.py @@ -0,0 +1,8 @@ +from django.urls import path +from commentapp.views import CommentList, CommentDetail, BlogCommentList + +urlpatterns = [ + path('main/', CommentList.as_view()), + path('blog/', BlogCommentList.as_view()), + path('main/', CommentDetail.as_view()), +] diff --git a/HW12/apiproject/commentapp/views.py b/HW12/apiproject/commentapp/views.py new file mode 100644 index 0000000..cf7a87c --- /dev/null +++ b/HW12/apiproject/commentapp/views.py @@ -0,0 +1,58 @@ +from rest_framework import status +from rest_framework.views import APIView +from rest_framework.response import Response + +from .serializers import CommentSerializer, CommentListSerializer +from .models import Comment + +from django.http import Http404 + +# Create your views here. +class CommentList(APIView): + def get(self, request): # 모든 댓글 목록 조회하는 경우 + comments = Comment.objects.filter() + + serializer = CommentListSerializer(comments, many=True) # 다수의 쿼리셋 전달 위해서 many = True + return Response(serializer.data) + + def post(self, request): # 댓글 작성하는 경우 + serializer = CommentSerializer(data = request.data) + if serializer.is_valid(): + serializer.save() + return Response(serializer.data, status=status.HTTP_201_CREATED) + return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) + +class BlogCommentList(APIView): + def get(self, request, pk): # 모든 댓글 목록 조회하는 경우 + + comments = Comment.objects.filter( + blog = pk + ) + serializer = CommentListSerializer(comments, many=True) # 다수의 쿼리셋 전달 위해서 many = True + return Response(serializer.data) + + +class CommentDetail(APIView): + def get_object(self, pk): # comment 객체 가져오기 + try: + return Comment.objects.get(pk=pk) + except Comment.DoesNotExist: + raise Http404 + + def get(self, request, pk): # comment 상세조회 + comment = self.get_object(pk) + serializer = CommentSerializer(comment) + return Response(serializer.data) + + def put(self, request, pk): # comment 수정 + comment = self.get_object(pk) + serializer = CommentSerializer(comment, data=request.data) + if serializer.is_valid(): + serializer.save() + return Response(serializer.data, status=status.HTTP_200_OK) + return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) + + def delete(self, request, pk): + comment = self.get_object(pk) + comment.delete() + return Response(status=status.HTTP_204_NO_CONTENT) diff --git a/HW12/apiproject/manage.py b/HW12/apiproject/manage.py new file mode 100755 index 0000000..1d1d514 --- /dev/null +++ b/HW12/apiproject/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', 'apiproject.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()