From b172945fc559cba6d5af631619d2248283ee351b Mon Sep 17 00:00:00 2001 From: icurfer Date: Tue, 20 May 2025 08:29:52 +0900 Subject: [PATCH] =?UTF-8?q?=EC=9E=91=EC=97=85=EB=8C=80=EA=B8=B0=20?= =?UTF-8?q?=EC=8B=9C=EB=A6=AC=EC=96=BC=EB=9D=BC=EC=9D=B4=EC=A0=80=EB=B6=80?= =?UTF-8?q?=ED=84=B0=20=ED=95=B4=EC=95=BC=ED=95=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 34 +++++ ansible/__init__.py | 0 ansible/admin.py | 3 + ansible/apps.py | 6 + ansible/authentication.py | 17 +++ ansible/migrations/__init__.py | 0 ansible/models.py | 3 + ansible/tests.py | 3 + ansible/views.py | 3 + ansible_prj/__init__.py | 0 ansible_prj/asgi.py | 16 +++ ansible_prj/settings.py | 236 +++++++++++++++++++++++++++++++++ ansible_prj/urls.py | 22 +++ ansible_prj/wsgi.py | 16 +++ manage.py | 22 +++ 15 files changed, 381 insertions(+) create mode 100644 ansible/__init__.py create mode 100644 ansible/admin.py create mode 100644 ansible/apps.py create mode 100644 ansible/authentication.py create mode 100644 ansible/migrations/__init__.py create mode 100644 ansible/models.py create mode 100644 ansible/tests.py create mode 100644 ansible/views.py create mode 100644 ansible_prj/__init__.py create mode 100644 ansible_prj/asgi.py create mode 100644 ansible_prj/settings.py create mode 100644 ansible_prj/urls.py create mode 100644 ansible_prj/wsgi.py create mode 100755 manage.py diff --git a/README.md b/README.md index 46e79f7..a473e4f 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,36 @@ # msa-django-ansible +```bash +python3 -m venv ./venv +``` + +```bash +source ./venv/bin/activate +``` + +```bash +# 1. Django 및 DRF +pip install django==4.2.14 djangorestframework==3.15.2 + +# 2. 태그 기능 + CORS +pip install django-taggit django-cors-headers + +# 3. JWT 인증 +pip install djangorestframework-simplejwt + +# 4. Swagger 문서 자동화 +pip install drf-yasg + +``` +## start project +```bash +django-admin startproject ansible_prj . +``` + +## create app +```bash +python manage.py startapp ansible +``` + +ansible==10.7.0 +ansible-core==2.17.7 \ No newline at end of file diff --git a/ansible/__init__.py b/ansible/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/ansible/admin.py b/ansible/admin.py new file mode 100644 index 0000000..8c38f3f --- /dev/null +++ b/ansible/admin.py @@ -0,0 +1,3 @@ +from django.contrib import admin + +# Register your models here. diff --git a/ansible/apps.py b/ansible/apps.py new file mode 100644 index 0000000..48ec3b1 --- /dev/null +++ b/ansible/apps.py @@ -0,0 +1,6 @@ +from django.apps import AppConfig + + +class AnsibleConfig(AppConfig): + default_auto_field = 'django.db.models.BigAutoField' + name = 'ansible' diff --git a/ansible/authentication.py b/ansible/authentication.py new file mode 100644 index 0000000..e197a55 --- /dev/null +++ b/ansible/authentication.py @@ -0,0 +1,17 @@ +from rest_framework_simplejwt.authentication import JWTAuthentication +from rest_framework_simplejwt.exceptions import InvalidToken + +class StatelessUser: + def __init__(self, email): + self.email = email + self.is_authenticated = True + + def __str__(self): + return self.email + +class StatelessJWTAuthentication(JWTAuthentication): + def get_user(self, validated_token): + email = validated_token.get("email") # msa-django-auth에서 넣어준 필드 + if not email: + raise InvalidToken("Token에 'email' 항목이 없습니다.") + return StatelessUser(email=email) diff --git a/ansible/migrations/__init__.py b/ansible/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/ansible/models.py b/ansible/models.py new file mode 100644 index 0000000..71a8362 --- /dev/null +++ b/ansible/models.py @@ -0,0 +1,3 @@ +from django.db import models + +# Create your models here. diff --git a/ansible/tests.py b/ansible/tests.py new file mode 100644 index 0000000..7ce503c --- /dev/null +++ b/ansible/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/ansible/views.py b/ansible/views.py new file mode 100644 index 0000000..91ea44a --- /dev/null +++ b/ansible/views.py @@ -0,0 +1,3 @@ +from django.shortcuts import render + +# Create your views here. diff --git a/ansible_prj/__init__.py b/ansible_prj/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/ansible_prj/asgi.py b/ansible_prj/asgi.py new file mode 100644 index 0000000..b082088 --- /dev/null +++ b/ansible_prj/asgi.py @@ -0,0 +1,16 @@ +""" +ASGI config for ansible_prj 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.2/howto/deployment/asgi/ +""" + +import os + +from django.core.asgi import get_asgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ansible_prj.settings') + +application = get_asgi_application() diff --git a/ansible_prj/settings.py b/ansible_prj/settings.py new file mode 100644 index 0000000..f8f7960 --- /dev/null +++ b/ansible_prj/settings.py @@ -0,0 +1,236 @@ +""" +Django settings for ansible_prj project. + +Generated by 'django-admin startproject' using Django 4.2.14. + +For more information on this file, see +https://docs.djangoproject.com/en/4.2/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/4.2/ref/settings/ +""" + +import os +from dotenv import load_dotenv +from pathlib import Path +import sys + +LOGGING = { + 'version': 1, + 'disable_existing_loggers': False, # 기존 로거 사용 허용 + 'handlers': { + 'console': { + 'class': 'logging.StreamHandler', + 'stream': sys.stdout, # ✅ stdout으로 출력되도록 지정 + }, + }, + 'root': { + 'handlers': ['console'], + 'level': 'DEBUG', # DEBUG 레벨로 모두 출력 + }, +} + +# Build paths inside the project like this: BASE_DIR / 'subdir'. +BASE_DIR = Path(__file__).resolve().parent.parent + +# 우선순위: .env.dev > .env.prd > .env +if os.path.exists(os.path.join(BASE_DIR, '.env.dev')): + print("Read Environment File > Used : .env.dev") + load_dotenv(os.path.join(BASE_DIR, '.env.dev')) +elif os.path.exists(os.path.join(BASE_DIR, '.env.prd')): + print("Read Environment File > Used : .env.prd") + load_dotenv(os.path.join(BASE_DIR, '.env.prd')) +else: + print("None Environment File > Used : local_env") + +# Quick-start development settings - unsuitable for production +# See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = os.environ.get('SECRET_KEY', 'django-insecure-ec9me^z%x7-2vwee5#qq(kvn@^cs!!22_*f-im(320_k5-=0j5') + +# SECURITY WARNING: don't run with debug turned on in production! +DEBUG = int(os.environ.get('DEBUG', 1)) + +LOGGING = { + 'version': 1, + 'disable_existing_loggers': False, # Django 기본 로거 유지 + 'formatters': { + 'standard': { + 'format': '[{asctime}] {levelname} {name}:{lineno} {message}', + 'style': '{', + }, + }, + 'handlers': { + 'console': { + 'class': 'logging.StreamHandler', # 콘솔 출력 + 'formatter': 'standard', + }, + }, + 'root': { + 'handlers': ['console'], + 'level': 'INFO', # 기본 레벨 (애플리케이션 코드) + }, + 'loggers': { + 'django': { + 'handlers': ['console'], + 'level': 'INFO', # Django 프레임워크 전반 + 'propagate': False, + }, + 'django.request': { + 'handlers': ['console'], + 'level': 'ERROR', # 요청 관련 에러만 (500 에러 같은 것) + 'propagate': False, + }, + 'django.db.backends': { + 'handlers': ['console'], + 'level': 'WARNING', # DB 쿼리 경고만 + 'propagate': False, + }, + 'django.security': { + 'handlers': ['console'], + 'level': 'WARNING', # 보안 관련 경고 + 'propagate': False, + }, + # mattermost send message log 너무 많이 나와서 조정 + 'apscheduler': { + 'handlers': ['console'], + 'level': 'WARNING', # INFO 로그 안 보이게 함 | 'CRITICAL'로 맞추면 사실상 아무것도 안 찍힘 + 'propagate': False, + }, + }, +} + +AUTH_VERIFY_URL = os.environ.get('AUTH_VERIFY_URL', 'NONE') + +ALLOWED_HOSTS = ["*"] + +# Application definition + +INSTALLED_APPS = [ + 'django.contrib.admin', + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.messages', + 'django.contrib.staticfiles', + # by.sdjo 2025-05-19 + 'rest_framework', + 'rest_framework_simplejwt', + 'drf_yasg', + 'corsheaders', + # create by.sdjo 2025-05-19 + 'ansible', # 2025-05-19 custom app create +] + +# AUTH_USER_MODEL = 'users.CustomUser' + +MIDDLEWARE = [ + 'corsheaders.middleware.CorsMiddleware', + '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', +] + +# by.sdjo 2025-04-22 +CORS_ALLOWED_ORIGINS = [ + "http://localhost:3000", + "http://127.0.0.1:3000", + "http://192.168.0.100:3000", + "https://sample.test", + "http://sample.test", + "http://www.sample.test", + "https://www.icurfer.com", + "https://icurfer.com", +] + +# by.sdjo 2025-04-22 +REST_FRAMEWORK = { + 'DEFAULT_AUTHENTICATION_CLASSES': ( + 'ansible.authentication.StatelessJWTAuthentication', + ), + 'DEFAULT_PERMISSION_CLASSES': ( + 'rest_framework.permissions.IsAuthenticated', + ) +} + +ROOT_URLCONF = 'ansible_prj.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 = 'ansible_prj.wsgi.application' + + +# Database +# https://docs.djangoproject.com/en/4.2/ref/settings/#databases + +DATABASES = { + "default": { + 'ENGINE': os.environ.get('SQL_ENGINE', 'django.db.backends.sqlite3'), + 'NAME': os.environ.get('SQL_DATABASE', BASE_DIR / 'db.sqlite3'), + 'USER': os.environ.get('SQL_USER', 'user'), + 'PASSWORD': os.environ.get('SQL_PASSWORD', 'password'), + 'HOST': os.environ.get('SQL_HOST', 'localhost'), + 'PORT': os.environ.get('SQL_PORT', '3306'), + } +} + + +# Password validation +# https://docs.djangoproject.com/en/4.2/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.2/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.2/howto/static-files/ + +STATIC_URL = 'static/' + +# Default primary key field type +# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field + +DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' diff --git a/ansible_prj/urls.py b/ansible_prj/urls.py new file mode 100644 index 0000000..65340e8 --- /dev/null +++ b/ansible_prj/urls.py @@ -0,0 +1,22 @@ +""" +URL configuration for ansible_prj project. + +The `urlpatterns` list routes URLs to views. For more information please see: + https://docs.djangoproject.com/en/4.2/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 + +urlpatterns = [ + path('admin/', admin.site.urls), +] diff --git a/ansible_prj/wsgi.py b/ansible_prj/wsgi.py new file mode 100644 index 0000000..b86d035 --- /dev/null +++ b/ansible_prj/wsgi.py @@ -0,0 +1,16 @@ +""" +WSGI config for ansible_prj 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.2/howto/deployment/wsgi/ +""" + +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ansible_prj.settings') + +application = get_wsgi_application() diff --git a/manage.py b/manage.py new file mode 100755 index 0000000..3a44581 --- /dev/null +++ b/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', 'ansible_prj.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()