728x90
반응형

Client - Server

client   server(WAS, Web Application Server) DB Server
브라우저
요청 url (http://127.0.0.1:8000/index)

요청(request)
web server

Container(Application)

    config라는 폴더의 djang App(ex. firstapp)
    Apache
넘어 온 주소 확인 후 index를 container로 넘김(즉, index 페이지 요청) →
Tomcat
index라는 이름의 pattern이 들어오면 특정 함수를 실행하라고 정의해 둠
이 함수는 java로 따지면 controller에 있는 함수. 
django로 따지면 views.py에 있는 함수
파싱(parsing)
html을 다시 읽어냄

응답(reponse)
html을 요청한 사람한테 넘김 함수가 실행되면서 html에 담긴 데이터를 web server로 다시 보내줌  

 

 

Django

  • Python 프레임워크 : Django, Flask 
  • 가상환경 새로 생성하여 진행
> conda create -n gj_django python=3.9
> conda activate gj_django
> pip install jupyter notebook
> python -m ipykernel install --user --name gj_django --display-name gj_django_kernel
> pip install ipython jupyter matplotlib pandas xlrd seaborn scikit-learn(python 버전 11이상이면 sklearn)
> pip install openpyxl
> conda install -c conda-forge django==4.0.1

Django 프로젝트 생성하기

  • Django 서버 생성
tutorial 파일로 이동
> django-admin startproject config . (config 한칸 띄우고 점. 찍기 > 현재 폴더에 config 폴더 생성 됨)

서버 테스트(웹은 생성시 마다 서버에 문제 없는지 확인 필요)
> python manage.py runserver

ctrl 누르고 아래 주소 클릭
> http://127.0.0.1:8000/

Django 페이지 등장🚀

Django VScode 설정 사항

  • vscode 실행 방법
    Prompt에서 가상환경 실행 후 totutorial 파일로 이동
(gj_django) C:\Users\user\gj_202311\11_Django\edu_django\tutorial>code .

 

  • config > settings.py 설
1. ALLOWED_HOSTS = [] 에 "127.0.0.1" 입력
결과 > ALLOWED_HOSTS = ["127.0.0.1"]

2. TEMPLATES에서 DIRS': []에 BASE_DIR/"templates" 입력
결과 > 'DIRS': [BASE_DIR/"templates"]

3. 언어 설정
> LANGUAGE_CODE = 'ko-kr'

4. 시간 설정
> TIME_ZONE = 'Asia/Seoul'

5. 파일 위치 설정
STATIC_URL = 'static/' 아래에
> STATICFILES_DIRS = [BASE_DIR/"static"] 추가

6. 나중에 사용할 부분

> INSTALLED_APPS
> DATABASES
 

  Web Site 만들기

  • firstapp 생성
Prompt tutoral 폴더 안에서 
> python manage.py startapp firstapp

영역을 app으로 나눠서 사용함 (ex. loginapp, joinapp)

  • firstapp 실행
INSTALLED_APPS 리스트에 'firstapp' 추가

  Web Site 만들기_함수

  • views.py
    앱의 시작점은 views.py (Spring으로 따지면 Controller에 해당)
from django.shortcuts import render

from django.http import HttpResponse

# Create your views here.
def index(request) :
    return HttpResponse("<u>firstapp의 index 페이지!!</u>")
  • urls.py
from django.contrib import admin
from django.urls import path
from firstapp import views as firstapp_view

urlpatterns = [
    ### http://127.0.0.1:8000/index
    path('index/', firstapp_view.index),

    path('admin/', admin.site.urls),
]

 

  Web Site 만들기_html

  • views.py
from django.shortcuts import render

from django.http import HttpResponse

# Create your views here.
def index(request) :
    return HttpResponse("<u>firstapp의 index 페이지!!</u>")

### http://127.0.0.1:8000/index_html
def indexHtml(request) :
    return render(
        request,
        "firstapp/index.html",
        {} # 어떤값을 줄건지 딕셔너리에 넣기
    )
  • templates\firstapp 파일 생성 후 index.html 작성
<!DOCTYPE html>
<html lang="ko">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>FirstApp - index.html</title>
  </head>
  <body>
    <h2>FirstApp-index.html</h2>
    <p>firstapp의 index.html 페이지 입니다.</p>
  </body>
</html>
  • urls.py
from django.contrib import admin
from django.urls import path
from firstapp import views as firstapp_view

urlpatterns = [
  
    ### http://127.0.0.1:8000/index
    path('index/', firstapp_view.index),
    
    ### http://127.0.0.1:8000/index_html
    path('index_html/', firstapp_view.indexHtml),

    path('admin/', admin.site.urls),
]

 

 

MainApp 생성

  •  mainapp 생성
Prompt tutoral 폴더 안에서 
> python manage.py startapp mainapp

INSTALLED_APPS 리스트에 'mainapp' 추가
  • view.py
from django.shortcuts import render

# Create your views here.

### http://127.0.0.1:8000/main_index
def index(requset) :
    return render(
        requset,
        "mainapp/index.html",
        {}
    )
  • templates\mainapp 파일 생성 후 index.html 작성
<!DOCTYPE html>
<html lang="ko">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>FirstApp - index.html</title>
  </head>
  <body>
    <h2>MainApp-index.html</h2>
    <p>mainapp의 index.html 페이지 입니다.</p>
  </body>
</html>
  • urls.py
from django.contrib import admin
from django.urls import path
from firstapp import views as firstapp_view
from mainapp import views as mainapp_view

urlpatterns = [
    ### http://127.0.0.1:8000/main_index
    path('', mainapp_view.index),
    
    ### http://127.0.0.1:8000/main_index
    path('main_index/', mainapp_view.index),
  
    ### http://127.0.0.1:8000/index
    path('index/', firstapp_view.index),
    
    ### http://127.0.0.1:8000/index_html
    path('index_html/', firstapp_view.indexHtml),

    path('admin/', admin.site.urls),
]

  • 설치 라이브러리
더보기

Python 관련

Python

Python Extension Pack

Python Extended

Python Indent

Python Debugger

Python snippetes

 

HTML, CSS, JS 관련

HTML CSS Support

HTML5 extension pack

html5-skelton

Extended Html5 Boilerplate

Html5 Reset Css

CSS Snippets

VS Code JavaScript (ES6) snippets

 

Django 관련

Django

Django Snippets

Django Templates

Django Snippets

 

url을 각 app에서 관리하게 하기 _firstapp

  • config에 있는 urls.py를 firstapp에 복사
  • config에 있는 urls.py
from django.contrib import admin
from django.urls import path, include
# from firstapp import views as firstapp_view
# from mainapp import views as mainapp_view

urlpatterns = [
    ### firstapp의 urls.py 사용하기
    # http://127.0.0.1:8000/first/index
    path("first/", include("firstapp.urls")),
    
    # ### http://127.0.0.1:8000/main_index
    # path('', mainapp_view.index),
    
    # ### http://127.0.0.1:8000/main_index
    # path('main_index/', mainapp_view.index),
  
    # ### http://127.0.0.1:8000/index
    # path('index/', firstapp_view.index),
    
    # ### http://127.0.0.1:8000/index_html
    # path('index_html/', firstapp_view.indexHtml),

    path('admin/', admin.site.urls),
]
  • firstapp에 있는 urls.py
from django.urls import path
from . import views

urlpatterns = [
    # http://127.0.0.1:8000/first/index
    path('index/', views.indexHtml ),
    
    # http://127.0.0.1:8000/first/
    path('', views.indexHtml ),
]

 

url을 각 app에서 관리하게 하기 _mainapp

  • firstapp에 있는 urls.py를 firstapp에 복사
  • config에 있는 urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    ### firstapp의 urls.py 사용하기
    # http://127.0.0.1:8000/first/index
    path("first/", include("firstapp.urls")),
    
    ### mainapp의 urls.py 사용하기
    # http://127.0.0.1:8000/main/index
    path("main/", include("mainapp.urls")),

    path('admin/', admin.site.urls),
]
  • mainapp에 있는 urls.py
from django.urls import path
from . import views

urlpatterns = [
    # http://127.0.0.1:8000/main/index
    path('index/', views.index ),
    
    # http://127.0.0.1:8000/main/
    path('', views.index ),
]

 

  • http://127.0.0.1:8000/ 만 입력 했을 때 main의 index가 뜨게 하는 방법
from django.contrib import admin
from django.urls import path, include
from mainapp import views as mainapp_view

urlpatterns = [
    ### firstapp의 urls.py 사용하기
    # http://127.0.0.1:8000/first/index
    path("first/", include("firstapp.urls")),
    
    ### mainapp의 urls.py 사용하기
    # http://127.0.0.1:8000/main/index
    path("main/", include("mainapp.urls")),
    
    # http://127.0.0.1:8000/
    path("", mainapp_view.index),
    path("index/", mainapp_view.index),
    
    path('admin/', admin.site.urls),
]

 

페이지 이동하기

  • mainapp > index.html (firstapp > index.html도 동일)
<!DOCTYPE html>
<html lang="ko">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>FirstApp - index.html</title>
  </head>
  <body>
    <h2>MainApp-index.html</h2>
    <p>mainapp의 index.html 페이지 입니다.</p>
    <p>
      <a href="/first/">firstapp/index 바로가기</a>
    </p>
  </body>
</html>

클릭 시 해당 페이지로 이동

 

이미지 삽입하기

  • firstapp > static\firstapp > images 생성
  • firstapp의 index.html
    {% load static %} > static 폴더를 사용하겠다는 의미
{% load static %}
<!DOCTYPE html>
<html lang="ko">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>FirstApp - index.html</title>
  </head>
  <body>
    <h2>FirstApp-index.html</h2>
    <p>firstapp의 index.html 페이지 입니다.</p>
    <p>
      <a href="/main/">Home 바로가기</a>
    </p>
    <p>
      <img
        src="{% static '/firstapp/images/fashion739.jpg' %}"
        width="300"
        height="300"
      />
    </p>
  </body>
</html>

  • 이미지 안불러와지면 settings.py에 가서 / 앞뒤로 띄어쓰기 한번 씩 하기 
STATICFILES_DIRS = [BASE_DIR / "static"]

 

jupyter 파일 웹에 적용하기_파일 생성해서 불러오기

  • 방법
    1. jupyter 에 있는 파일을 파이썬으로 저장
    2. firstapp에 ml_view 폴더 생성 후 안에 파이썬으로 저장한 파일 넣기
    3. 파이썬 내용 함수로 감싸기
  • firstapp > ml_view > ml_view.py 생성(여기 안에서는 항상 함수로 진행)
  • firstapp > ml_view.py
def getView() :
    ### 이미지 처리 수행 후
    ### 이미지를 static 위치에 저장까지만 하면 됨
    # - return은 안해도 됨. 테스트를 위해
    return "test"
  • firstapp > views.py
from firstapp.ml_view import ml_view

### http://127.0.0.1:8000/first/ml_view
def ml_View(request) :
    ### getView() 함수 호출하기
    rs_data = ml_view.getView()
    
    return render(
        request,
        "firstapp/ml_view/ml_view.html",
        {"rs_data" : rs_data}
    )
  • templates\firstapp > ml_view > ml_view.html 생성
<!DOCTYPE html>
<html lang="ko">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>FirstApp - index.html</title>
  </head>
  <body>
    <h2>ML-View 페이지</h2>
    <p>받아온 값 rs_data ={{rs_data}}</p>
  </body>
</html>
  • firstapp > urls.py
from django.urls import path
from . import views

urlpatterns = [
    # http://127.0.0.1:8000/first/ml_view/
    path('ml_view/', views.ml_View ),
]

 

jupyter 파일 웹에 적용하기_기존 py 파일(Class) 사용하기

  • data_view.py 파일 사용
    그래프 저장 위치 변경하기

  • firstapp > views.py
from firstapp.data_view.data_view import Data_View

### http://127.0.0.1:8000/first/data_view/
def data_View(request) :
    ### Data_View 클래스 호출하기
    data_view = Data_View()
    
    return render(
        request,
        "firstapp/data_view/data_view.html",
        {}
    )
  • templates\firstapp > data_view > data_view.html 생성
{% load static %}
<!DOCTYPE html>
<html lang="ko">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>FirstApp - index.html</title>
  </head>
  <body>
    <h2>Data-View 페이지</h2>
    <p>
      <img
        src="{% static '/firstapp/images/fig.png' %}"
        width="300"
        height="300"
      />
    </p>
  </body>
</html>
  • firstapp > views.py
from django.urls import path
from . import views

urlpatterns = [
    # http://127.0.0.1:8000/first/data_view/
    path('data_view/', views.data_View ),
]

model 웹에 적용하기

  • model_view.py 파일 사용
    데이터 읽어들이기 / 훈련모델 저장시키기 / 훈련모델 불러오기 파일 경로 변경하기
  • firstapp > views.py
from firstapp.model_view.ml_view import ML_View

### http://127.0.0.1:8000/first/model_view/
def model_View(request) :
    ### ML_View 클래스 호출하기
    ml_view = ML_View()
    
    ### 정확도
    score = ml_view.getModelScore()
    
    ### 예측하기
    # 사용할 예측 데이터
    # - [[200.0, 23.0, 25.8, 10.34, 3.66]]
    x_input = [[200.0, 23.0, 25.8, 10.34, 3.66]]
    pred_data = ml_view.getModelPredict(x_input)
    
    return render(
        request,
        "firstapp/data_view/data_view.html",
        {"score" : score,
         "pred_data" : pred_data}
    )
  • templates\firstapp > model_view > model_view.html 생성
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <h2>Model-View 페이지</h2>
    <p>정확도 : {{score}}</p>
    <p>예측 : {{pred_data}}</p>
  </body>
</html>
  • firstapp > urls.py
from django.urls import path
from . import views

urlpatterns = [
    # http://127.0.0.1:8000/first/model_view/
    path('model_view/', views.model_View ),
]

지도 웹에 적용하기

  • map_view.py 데이터 사용
    데이터 읽어들이기 파일 경로 변경하기
    folium 라이브러리 설치
  • firstapp > views.py
from firstapp.map_view.map_view import Map_View

### http://127.0.0.1:8000/first/map_view/
def map_View(request) :
    ### Map_View 클래스 호출하기
    map_view = Map_View()
    
    ### 지도 결과를 html로 받아오기
    map_html = map_view.getMapHtml() 
    
    ### 지도 시각화에 사용한 데이터 프레임 받아오기
    
    map_data = map_view.getDataFrame()
    
    return render(
        request,
        "firstapp/map_view/map_view.html",
        {
          "map_html" : map_html,
            "map_data" : map_data.to_html(),
         }
    )
  • templates\firstapp > map_view > map_view.html 생성
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <h2>Map-View 페이지</h2>
    <p>{{map_html | safe}}</p>
    <p>{{map_data | safe}}</p>
  </body>
</html>
  • firstapp > urls.py
from django.urls import path
from . import views

urlpatterns = [
    # http://127.0.0.1:8000/first/map_view/
    path('map_view/', views.map_View ),
]

728x90
반응형

+ Recent posts