DAY62
DAY62

flask 페이지를 장고로 구축해보자 1


cd /opt/stack
su
sudo passwd root
su

cd horizon(web frontends)
ls
babel-django.cfg, babel-djangojs.cfg등을 확인 가능
=> 대시보드가 장고로 구성되어 있음을 확인

cmd
mysite
경로
c:\projects\django
django 디렉터리 생성

c:\venvs
mysite.cmd
@echo off
cd c:\projects/django
c:\projects\mysite\scripts\activate

cmd
pip install django

mysite
경로
c:\projects\django
django-admin startproject config .

python manage.py runserver
(=flask run)
자동으로 디렉토리와 파일이 생성됨(편리)

=> http://127.0.0.1:8000/
로켓모양 사이트 뜸 !!

openstack과 비교해보기---------------------------------------------
django
settings.py
# Application definition
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

# Database
# https://docs.djangoproject.com/en/5.1/ref/settings/#databases
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}

-> flask도 sqlite였는데 mysqldb로 변경해 사용했었음


openstack
settings.py
INSTALLED_APPS = [
    'openstack_dashboard',
    'django.contrib.contenttypes',
    'django.contrib.auth',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.humanize',
    'debreach',
    'compressor',
    'horizon',
    'openstack_auth',
]
------------------------------------------------------------------------
settings.py
수정하기
LANGUAGE_CODE = 'ko-kr'
TIME_ZONE = 'Asia/Seoul'

python manage.py runserver

=> http://127.0.0.1:8000/ 한글패치됨

새 cmd 창
django-admin startapp security
security 디렉터리 및 파일 생성됨

c:\projects\django\config
urls.py 추가
from security import views
path('admin/', admin.site.urls),

c:\projects\django\security
views.py
from django.shortcuts import render

# Create your views here.

def index():
	pass

=> index()는 작동되는 것을 에러메세지로 확인가능하나 돌아가진 않음

c:\projects\django\security
views.py 수정
from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.

def index(request):
	return HttpResponse("장고입니다")

=> 사이트에서 장고입니다라는 글자를 확인할 수 있음

c:\projects\django\config
urls.py
from django.contrib import admin
from django.urls import path, include
from security import views

urlpatterns = [
    path('admin/', admin.site.urls),
	path('security/', include('security.urls')),
]


c:\projects\django\security
urls.py (경로 확인 잘하기)
#127.0.0.1/security/
from django.urls import path
from . import views

urlpatterns = [
	path('', views.index),
]


openstack 비교하기
settings.py
# configure templates
if not TEMPLATES[0]['DIRS']:
    TEMPLATES[0]['DIRS'] = [os.path.join(ROOT_PATH, 'templates')]

TEMPLATES[0]['DIRS'] += ADD_TEMPLATE_DIRS

django
settings.py
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',
            ],
        },
    },
]


c:\projects\django\templates\security (templates, security 디렉토리 생성)
index.html 생성

c:\projects\django\security
views.py
from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.

def index(request):
	logs = [1,2,3,4,5,6,7,8,9,10]
	return render(request, 'security/index.html', logs)
	#return HttpResponse("장고입니다")

=> 에러메세지 : list[]보다 dict{} 사용해라

c:\projects\django\security
views.py
from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.

def index(request):
	logs = {'key':'value'}
	return render(request, 'security/index.html', logs)
	#return HttpResponse("장고입니다")


c:\projects\django\security
index.html
{% if key %}
	{% for value in key %}
	< li>{{value}}
	{% endfor %}
{% else %}
	< li>데이터가 없다!
{% endif %}

c:\projects\django\config\settings.py
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / 'templates'], < - 수정하기
        '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',
            ],
        },
    },
]


c:\projects\flask\security\templates\syslog
index.html을
c:\projects\django\templates\security
index.html에 붙이기

c:\projects\flask\security\templates
base.html을
c:\projects\django\templates
base.html에 붙이기
수정본 붙여넣기

c:\projects\flask\security\static 디렉터리 복사
c:\projects\django 에 붙여넣기

c:\projects\django\config
settings.py 수정하기
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.1/howto/static-files/

STATIC_URL = 'static/'
STATICFILES_DIRS = [
	BASE_DIR / 'static',
]


c:\projects\django\security
views.py
from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.

def index(request):
	logs = {'syslog':'value'} <<<수정
	return render(request, 'security/index.html', logs)
	#return HttpResponse("장고입니다")



1. 데이터베이스 연결하기
mysql db 95번 가져오기

로컬에 mysql을 설치한다
장고와 mysql연결방법을 찾는다
models.py를 수정한다
마이그레이션을 진행한다

local에 mysql 설치하기

https://dev.mysql.com/downloads/mysql/
MySQL Community Server 8.4.4 LTS
Windows (x86, 64-bit), MSI Installer
No thanks, just start my download.


mysql 설치 시
root 비밀번호
123456

add user
rsyslog
123456/123456

workbench
rsyslog
123456
127.0.0.1 (3306)
Syslog

= > 연결 에러: Syslog 데이터베이스 찾을 수 없음

MySQL 8.4 Command Line Client
create database Syslog; (Syslog데이터베이스 생성)
show databases; (확인)

pip install mysql


c:\projects\django\security
models.py

장고용
class SystemEvents(models.Model):
    ID = models.IntegerField(default=0)
    CustomerID = models.CharField(max_length=200)
    ReceivedAt = 
    DeviceReportedTime = 
    Facility = 
    Priority = 
    FromHost = 
    Message = 
    NTSeverity = 
    Importance = 
    EventSource = 
    EventUser = 
    EventCategory = 
    EventID = 
    EventBinaryData = 
    MaxAvailable = 
    CurrUsage = 
    MinUsage = 
    MaxUsage = 
    InfoUnitID = 
    SysLogTag = 
    EventLogType = 
    GenericFileName = 
    SystemID = 

django 참고사이트
https://docs.djangoproject.com/ko/5.1/intro/tutorial01/
https://docs.djangoproject.com/ko/5.1/intro/tutorial02/

완성본
from django.db import models

class SystemEvents(models.Model):
    # 테이블 이름 정의
    class Meta:
        db_table = 'SystemEvents'

    # 필드 정의
    ID = models.AutoField(primary_key=True)  # 자동 증가하는 ID 필드
    CustomerID = models.BigIntegerField(null=True, blank=True)  # BigInteger 타입
    ReceivedAt = models.DateTimeField(null=True, blank=True)  # DateTime 타입
    DeviceReportedTime = models.DateTimeField(null=True, blank=True)  # DateTime 타입
    Facility = models.SmallIntegerField(null=True, blank=True)  # SmallInteger 타입
    Priority = models.SmallIntegerField(null=True, blank=True)  # SmallInteger 타입
    FromHost = models.CharField(max_length=60, null=True, blank=True)  # CharField (60자까지)
    Message = models.TextField()  # TextField는 null=False로 설정되어 있음
    NTSeverity = models.IntegerField(null=True, blank=True)  # Integer 타입
    Importance = models.IntegerField(null=True, blank=True)  # Integer 타입
    EventSource = models.CharField(max_length=60, null=True, blank=True)  # CharField (60자까지)
    EventUser = models.CharField(max_length=60, null=True, blank=True)  # CharField (60자까지)
    EventCategory = models.IntegerField(null=True, blank=True)  # Integer 타입
    EventID = models.IntegerField(null=True, blank=True)  # Integer 타입
    EventBinaryData = models.TextField(null=True, blank=True)  # TextField (null=True로 설정)
    MaxAvailable = models.IntegerField(null=True, blank=True)  # Integer 타입
    CurrUsage = models.IntegerField(null=True, blank=True)  # Integer 타입
    MinUsage = models.IntegerField(null=True, blank=True)  # Integer 타입
    MaxUsage = models.IntegerField(null=True, blank=True)  # Integer 타입
    InfoUnitID = models.IntegerField(null=True, blank=True)  # Integer 타입
    SysLogTag = models.CharField(max_length=60, null=True, blank=True)  # CharField (60자까지)
    EventLogType = models.CharField(max_length=60, null=True, blank=True)  # CharField (60자까지)
    GenericFileName = models.CharField(max_length=60, null=True, blank=True)  # CharField (60자까지)
    SystemID = models.IntegerField(null=True, blank=True)  # Integer 타입

    # 모델의 문자열 표현 정의 (옵션)
    def __str__(self):
        return f"Event {self.ID} from {self.FromHost}"


flask용과 비교하기
class SystemEvents(db.Model):
    __tablename__ = 'SystemEvents'
    ID = db.Column(db.Integer, primary_key=True)
    CustomerID = db.Column(db.BigInteger, nullable=True)
    ReceivedAt = db.Column(db.DateTime(), nullable=True)
    DeviceReportedTime = db.Column(db.DateTime(), nullable=True)
    Facility = db.Column(db.SmallInteger, nullable=True)
    Priority = db.Column(db.SmallInteger, nullable=True)
    FromHost = db.Column(db.String(60), nullable=True)
    Message = db.Column(db.Text, nullable=False)
    NTSeverity = db.Column(db.Integer, nullable=True)
    Importance = db.Column(db.Integer, nullable=True)
    EventSource = db.Column(db.String(60), nullable=True)
    EventUser = db.Column(db.String(60), nullable=True)
    EventCategory = db.Column(db.Integer, nullable=True)
    EventID = db.Column(db.Integer, nullable=True)
    EventBinaryData = db.Column(db.Text, nullable=True)
    MaxAvailable = db.Column(db.Integer, nullable=True)
    CurrUsage = db.Column(db.Integer, nullable=True)
    MinUsage = db.Column(db.Integer, nullable=True)
    MaxUsage = db.Column(db.Integer, nullable=True)
    InfoUnitID = db.Column(db.Integer, nullable=True)
    SysLogTag = db.Column(db.String(60), nullable=True)
    EventLogType = db.Column(db.String(60), nullable=True)
    GenericFileName = db.Column(db.String(60), nullable=True)
    SystemID = db.Column(db.Integer, nullable=True)


c:\projects\django\config
settings.py
# Database
# https://docs.djangoproject.com/en/5.1/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME' : 'Syslog',   #사용하려는 데이터베이스 이름
        'USER' : 'rsyslog',   #MYSQL 사용자 이름
        'PASSWORD' : '123456',   #MYSQL 비밀번호
        'HOST' : 'localhost',   #MYSQL 서버 호스트
        'PORT' : '3306',
        #'ENGINE': 'django.db.backends.sqlite3',
        #'NAME': BASE_DIR / 'db.sqlite3',
    }
}

c:\projects\django\config\settings.py
# Application definition

INSTALLED_APPS = [
    'security.apps.SecurityConfig', < - 추가
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]


마이그레이션하기
cmd
mysite
python manage.py makemigrations
python manage.py migrate

데이터베이스 내용넣기
c:\projects\django\security
views.py
from django.shortcuts import render
from django.http import HttpResponse
from .models import SystemEvents

# Create your views here.

def index(request):
	syslog = SystemEvents.objects.order_by('-ID')
	context={'syslog':syslog}
	return render(request, 'security/index.html', context)
	#return HttpResponse("장고입니다")


\\192.168.0.94
syslog.sql 가져오기

심화
kisa 사이트에서 장고 취약점 공부하기
안전하지 않은 코드 예시....