관리 메뉴

거니의 velog

231108_Django 개론 1 본문

대덕인재개발원/대덕인재개발원_파이썬 프로그래밍

231108_Django 개론 1

Unlimited00 2023. 11. 8. 08:37

[HELLO_DJANGO.views]

from django.http import HttpResponse


def index(request):
    return HttpResponse("Hello, Django.")

[HELLO_DJANGO.urls]

"""
URL configuration for HELLO_DJANGO 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
from HELLO_DJANGO import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('myhello/', views.index),
]

- http://127.0.0.1:8000/myhello/


* manage가 메인 엔트리 페이지이다. 여기서 run python 실행

맨 밑에 renserver 복사

* 이 다음부터는 그냥 기존의 방법대로 crtl + f11 하면 실행됨.


* CMD로 접속하는 방법임


[HELLO_DJANGO.urls]

"""
URL configuration for HELLO_DJANGO 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
from HELLO_DJANGO import views

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

http://127.0.0.1:8000/ , 루트로 접속이 가능하게 됨.


from django.http import HttpResponse


def index(request):
    return HttpResponse("Hello, Django.")

def param(request):
    return HttpResponse("PARAM")
"""
URL configuration for HELLO_DJANGO 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
from HELLO_DJANGO import views

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

- http://127.0.0.1:8000/param


from django.http import HttpResponse
from django.shortcuts import render


def index(request):
    return HttpResponse("Hello, Django.")

def param(request):
    # return HttpResponse("PARAM")
    menu = request.GET.get('menu', '탕수육')
    return HttpResponse("PARAM : " + menu)

- http://127.0.0.1:8000/param?menu=%EC%A7%AC%EB%BD%95

파라미터 값이 없으면 기본값인 '탕수육'이 셋팅된다.


from django.http import HttpResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt


def index(request):
    return HttpResponse("Hello, Django.")

def param(request):
    # return HttpResponse("PARAM")
    menu = request.GET.get('menu', '탕수육')
    return HttpResponse("PARAM : " + menu)

@csrf_exempt
def post(request):
    return HttpResponse("POST")
"""
URL configuration for HELLO_DJANGO 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
from HELLO_DJANGO import views

urlpatterns = [
    path('', views.index),
    path('param', views.param),
    path('post', views.post),
]
<!DOCTYPE html>
<html lang="ko">
	<head>
		<meta charset="UTF-8">
		<title>Insert title here</title>
	</head>
	<body>
		<form action="http://127.0.0.1:8000/post" method="post">
			<button type="submit">파라미터 전송</button>
		</form>
	</body>
</html>

- file:///C:/workspace_python/HELLO_DJANGO/post.html

바로 넘어온다.

* 서버를 공격하는 url이 된다.

[HELLO_DJANGO.settings]

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',
]

<!DOCTYPE html>
<html lang="ko">
	<head>
		<meta charset="UTF-8">
		<title>Insert title here</title>
	</head>
	<body>
		<form action="http://127.0.0.1:8000/post" method="post">
			<input type="text" name="menu" value="김치찌개" />
			<button type="submit">파라미터 전송</button>
		</form>
	</body>
</html>
from django.http import HttpResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt


def index(request):
    return HttpResponse("Hello, Django.")

def param(request):
    # return HttpResponse("PARAM")
    menu = request.GET.get('menu', '탕수육')
    return HttpResponse("PARAM : " + menu)

@csrf_exempt
def post(request):
    menu = request.POST['menu']
    return HttpResponse("POST : " + menu)

- file:///C:/workspace_python/HELLO_DJANGO/post.html


from django.http import HttpResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt


def index(request):
    return HttpResponse("Hello, Django.")

def param(request):
    # return HttpResponse("PARAM")
    menu = request.GET.get('menu', '탕수육')
    return HttpResponse("PARAM : " + menu)

@csrf_exempt
def post(request):
    menu = request.POST['menu']
    return HttpResponse("POST : " + menu)

def forw(request):
    return render(request, "forw.html")
"""
URL configuration for HELLO_DJANGO 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
from HELLO_DJANGO import views

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

[HELLO_DJANGO.settings]

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'HELLO_DJANGO',
]

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>Insert title here</title>
	</head>
	<body>
		<p>FORW HTML 1</p>
	</body>
</html>

- http://127.0.0.1:8000/forw


from django.http import HttpResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt


def index(request):
    return HttpResponse("Hello, Django.")

def param(request):
    # return HttpResponse("PARAM")
    menu = request.GET.get('menu', '탕수육')
    return HttpResponse("PARAM : " + menu)

@csrf_exempt
def post(request):
    menu = request.POST['menu']
    return HttpResponse("POST : " + menu)

def forw(request):
    a = "홍길동"
    b = ["전우치", "일지매"]
    data = {
        'a' : a,
        'b' : b
    }
    return render(request, "forw.html", data)
"""
URL configuration for HELLO_DJANGO 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
from HELLO_DJANGO import views

urlpatterns = [
    path('', views.index),
    path('param', views.param),
    path('post', views.post),
    path('forw', views.forw),
]
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>Insert title here</title>
	</head>
	<body>
		<p>FORW HTML 1</p>
		<p>{{ a }}</p>
		<p>{{ b }}</p>
	</body>
</html>

- http://127.0.0.1:8000/forw


<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>Insert title here</title>
	</head>
	<body>
		<p>FORW HTML 1</p>
		<p>{{ a }}</p>
		<p>{{ b }}</p>
		{% for bObj in b %}
			<p>{{bObj}}</p>
		{% endfor %}
	</body>
</html>


from django.http import HttpResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt


def index(request):
    return HttpResponse("Hello, Django.")

def param(request):
    # return HttpResponse("PARAM")
    menu = request.GET.get('menu', '탕수육')
    return HttpResponse("PARAM : " + menu)

@csrf_exempt
def post(request):
    menu = request.POST['menu']
    return HttpResponse("POST : " + menu)

def forw(request):
    a = "홍길동"
    b = ["전우치", "일지매"]
    c = [
            {
                'e_id' : 1,
                'e_name' : 1,
                'gen' : 1,
                'addr' : 1
            },
            {
                'e_id' : 2,
                'e_name' : 2,
                'gen' : 2,
                'addr' : 2
            },
            {
                'e_id' : 3,
                'e_name' : 3,
                'gen' : 3,
                'addr' : 3
            },
    ]
    data = {
        'a' : a,
        'b' : b,
        'c' : c
    }
    return render(request, "forw.html", data)
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>Insert title here</title>
	</head>
	<body>
		<p>FORW HTML 1</p>
		<p>{{ a }}</p>
		<p>{{ b }}</p>
		
		<h1>b 반복시키기</h1>
		{% for bObj in b %}
			<p>{{bObj}}</p>
		{% endfor %}
		
		<h1>c 반복시키기</h1>
		<table border="1">
			<tr>
				<th>사번</th>
				<th>이름</th>
				<th>성별</th>
				<th>주소</th>
			</tr>
			{% for cObj in c %}
				<tr>
					<td>{{cObj.e_id}}</td>
					<td>{{cObj.e_name}}</td>
					<td>{{cObj.gen}}</td>
					<td>{{cObj.addr}}</td>
				</tr>
			{% endfor %}
		</table>
	</body>
</html>

- http://127.0.0.1:8000/forw


from django.http import HttpResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
import pymysql # PyMySQL-1.1.0

def index(request):
    return HttpResponse("Hello, Django.")

def param(request):
    # return HttpResponse("PARAM")
    menu = request.GET.get('menu', '탕수육')
    return HttpResponse("PARAM : " + menu)

@csrf_exempt
def post(request):
    menu = request.POST['menu']
    return HttpResponse("POST : " + menu)

def forw(request):
    a = "홍길동"
    b = ["전우치", "일지매"]
    c = [
            {
                'e_id' : 1,
                'e_name' : 1,
                'gen' : 1,
                'addr' : 1
            },
            {
                'e_id' : 2,
                'e_name' : 2,
                'gen' : 2,
                'addr' : 2
            },
            {
                'e_id' : 3,
                'e_name' : 3,
                'gen' : 3,
                'addr' : 3
            },
    ]
    data = {
        'a' : a,
        'b' : b,
        'c' : c
    }
    return render(request, "forw.html", data)

def dbconnect():
    conn = pymysql.connect(host='127.0.0.1', port=3305, user='root', password='python', db='python', charset='utf8') # 접속 정보
    return conn

def emp(request):
    conn = dbconnect() # DB 연결
    
    cur = conn.cursor(pymysql.cursors.DictCursor)
    sql = "select * from emp"
    cur.execute(sql)
    rows = cur.fetchall()
    
    data = {
        'rows' : rows
    }
    # DB에 접근해서 HTML에 데이터 뿌리기
    return render(request, "emp.html", data)

    conn.close() # 종료
"""
URL configuration for HELLO_DJANGO 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
from HELLO_DJANGO import views

urlpatterns = [
    path('', views.index),
    path('param', views.param),
    path('post', views.post),
    path('forw', views.forw),
    path('emp', views.emp),
]
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>Insert title here</title>
	</head>
	<body>
		<h1>EMP</h1>
		<table border="1">
			<tr>
				<th>사번</th>
				<th>이름</th>
				<th>성별</th>
				<th>주소</th>
			</tr>
			{% for rowsObj in rows %}
				<tr>
					<td>{{rowsObj.e_id}}</td>
					<td>{{rowsObj.e_name}}</td>
					<td>{{rowsObj.gen}}</td>
					<td>{{rowsObj.addr}}</td>
				</tr>
			{% endfor %}
		</table>
	</body>
</html>

- http://127.0.0.1:8000/emp


import pymysql # PyMySQL-1.1.0

class DaoEmp:
    def __init__(self):
        print("생성자")
        self.conn = pymysql.connect(host='127.0.0.1', port=3305, user='root', password='python', db='python', charset='utf8') # 접속 정보
        self.cur = self.conn.cursor(pymysql.cursors.DictCursor)
    
    def selectList(self):
        sql = "select * from emp"
        self.cur.execute(sql)
        
        lists = self.cur.fetchall()
        return lists
        
    # 소멸자 : destroyer
    def __del__(self):
        print("소멸자")
        self.cur.close()
        self.conn.close()
        
if __name__ == '__main__':
    de = DaoEmp()
    list = de.selectList()
    print(list)


import pymysql # PyMySQL-1.1.0

class DaoEmp:
    def __init__(self):
        print("생성자")
        self.conn = pymysql.connect(host='127.0.0.1', port=3305, user='root', password='python', db='python', charset='utf8') # 접속 정보
        self.cur = self.conn.cursor(pymysql.cursors.DictCursor)
    
    def selectList(self):
        sql = "select * from emp"
        self.cur.execute(sql)
        
        lists = self.cur.fetchall()
        return lists
    
    def selectOne(self, e_id):
        sql = f"""
            select * from emp 
            where e_id = '{e_id}'
        """
        self.cur.execute(sql)
        
        vo = self.cur.fetchone()
        return vo
        
    # 소멸자 : destroyer
    def __del__(self):
        print("소멸자")
        self.cur.close()
        self.conn.close()
        
if __name__ == '__main__':
    de = DaoEmp()
    
    # list = de.selectList()
    # print(list)
    
    vo = de.selectOne('1')
    print(vo)


import pymysql # PyMySQL-1.1.0

class DaoEmp:
    def __init__(self):
        print("생성자")
        self.conn = pymysql.connect(host='127.0.0.1', port=3305, user='root', password='python', db='python', charset='utf8') # 접속 정보
        self.cur = self.conn.cursor(pymysql.cursors.DictCursor)
    
    def selectList(self):
        sql = "select * from emp"
        self.cur.execute(sql)
        
        lists = self.cur.fetchall()
        return lists
    
    def selectOne(self, e_id):
        sql = f"""
            select * from emp 
            where e_id = '{e_id}'
        """
        self.cur.execute(sql)
        
        vo = self.cur.fetchone()
        return vo
    
    def insert(self, e_id, e_name, gen, addr):
        sql = f"""
            INSERT INTO emp (e_id, e_name, gen, addr) 
                 VALUES ('{e_id}', '{e_name}', '{gen}', '{addr}')
        """
        cnt = self.cur.execute(sql)
        self.conn.commit()
        return cnt
        
    # 소멸자 : destroyer
    def __del__(self):
        print("소멸자")
        self.cur.close()
        self.conn.close()
        
if __name__ == '__main__':
    de = DaoEmp()
    
    list = de.selectList()
    print(list)
    
    vo = de.selectOne('1')
    print(vo)
    
    cnt = de.insert('10', '10', '10', '10')
    print(cnt)


import pymysql # PyMySQL-1.1.0

class DaoEmp:
    def __init__(self):
        print("생성자")
        self.conn = pymysql.connect(host='127.0.0.1', port=3305, user='root', password='python', db='python', charset='utf8') # 접속 정보
        self.cur = self.conn.cursor(pymysql.cursors.DictCursor)
    
    def selectList(self):
        sql = "select * from emp"
        self.cur.execute(sql)
        
        lists = self.cur.fetchall()
        return lists
    
    def selectOne(self, e_id):
        sql = f"""
            select * from emp 
            where e_id = '{e_id}'
        """
        self.cur.execute(sql)
        
        vo = self.cur.fetchone()
        return vo
    
    def insert(self, e_id, e_name, gen, addr):
        sql = f"""
            INSERT INTO emp (e_id, e_name, gen, addr) 
                 VALUES ('{e_id}', '{e_name}', '{gen}', '{addr}')
        """
        cnt = self.cur.execute(sql)
        self.conn.commit()
        return cnt
    
    def update(self, e_id, e_name, gen, addr):
        sql = f"""
            UPDATE emp SET 
                e_name = '{e_name}'
                , gen = '{gen}'
                , addr = '{addr}'
                WHERE e_id = '{e_id}'
        """
        cnt = self.cur.execute(sql)
        self.conn.commit()
        return cnt
    
    def delete(self, e_id):
        sql = f"""
            DELETE FROM emp 
            WHERE e_id = '{e_id}'
        """
        cnt = self.cur.execute(sql)
        self.conn.commit()
        return cnt
        
    # 소멸자 : destroyer
    def __del__(self):
        print("소멸자")
        self.cur.close()
        self.conn.close()
        
if __name__ == '__main__':
    de = DaoEmp()
    
    list = de.selectList()
    print(list)
    
    # vo = de.selectOne('10')
    # print(vo)
    
    # cnt = de.insert('10', '10', '1', '10')
    # print(cnt)
    
    # cnt = de.update('10', '123', '1', '123')
    # print(cnt)
    
    # cnt = de.delete('10')
    # print(cnt)

10번 데이터 업데이트


10번 데이터 삭제


from django.http import HttpResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
import pymysql # PyMySQL-1.1.0
from HELLO_DJANGO.daoEmp import DaoEmp

def index(request):
    return HttpResponse("Hello, Django.")

def param(request):
    # return HttpResponse("PARAM")
    menu = request.GET.get('menu', '탕수육')
    return HttpResponse("PARAM : " + menu)

@csrf_exempt
def post(request):
    menu = request.POST['menu']
    return HttpResponse("POST : " + menu)

def forw(request):
    a = "홍길동"
    b = ["전우치", "일지매"]
    c = [
            {
                'e_id' : 1,
                'e_name' : 1,
                'gen' : 1,
                'addr' : 1
            },
            {
                'e_id' : 2,
                'e_name' : 2,
                'gen' : 2,
                'addr' : 2
            },
            {
                'e_id' : 3,
                'e_name' : 3,
                'gen' : 3,
                'addr' : 3
            },
    ]
    data = {
        'a' : a,
        'b' : b,
        'c' : c
    }
    return render(request, "forw.html", data)


def emp(request):
    daoEmp = DaoEmp()
    rows = daoEmp.selectList()
    
    data = {
        'rows' : rows
    }
    # DB에 접근해서 HTML에 데이터 뿌리기
    return render(request, "emp.html", data)

- http://127.0.0.1:8000/emp

 

똑같이 나온다...


import pymysql # PyMySQL-1.1.0

class DaoMem:
    def __init__(self):
        print("생성자")
        self.conn = pymysql.connect(host='127.0.0.1', port=3305, user='root', password='python', db='python', charset='utf8') # 접속 정보
        self.cur = self.conn.cursor(pymysql.cursors.DictCursor)
    
    def selectList(self):
        sql = "select * from member"
        self.cur.execute(sql)
        
        lists = self.cur.fetchall()
        return lists
    
    def selectOne(self, m_id):
        sql = f"""
            select * from member 
            where m_id = '{m_id}'
        """
        self.cur.execute(sql)
        
        vo = self.cur.fetchone()
        return vo
    
    def insert(self, m_id, m_name, tel, email):
        sql = f"""
            INSERT INTO member (m_id, m_name, tel, email) 
                 VALUES ('{m_id}', '{m_name}', '{tel}', '{email}')
        """
        cnt = self.cur.execute(sql)
        self.conn.commit()
        return cnt
    
    def update(self, m_id, m_name, tel, email):
        sql = f"""
            UPDATE member SET 
                m_name = '{m_name}'
                , tel = '{tel}'
                , email = '{email}'
                WHERE m_id = '{m_id}'
        """
        cnt = self.cur.execute(sql)
        self.conn.commit()
        return cnt
    
    def delete(self, m_id):
        sql = f"""
            DELETE FROM member 
            WHERE m_id = '{m_id}'
        """
        cnt = self.cur.execute(sql)
        self.conn.commit()
        return cnt
        
    # 소멸자 : destroyer
    def __del__(self):
        print("소멸자")
        self.cur.close()
        self.conn.close()
        
if __name__ == '__main__':
    dm = DaoMem()
    
    list = dm.selectList()
    print(list)
    
    # vo = dm.selectOne('10')
    # print(vo)
    
    # cnt = dm.insert('10', '10', '1', '10')
    # print(cnt)
    
    # cnt = dm.update('10', '123', '1', '123')
    # print(cnt)
    
    # cnt = dm.delete('10')
    # print(cnt)

'대덕인재개발원 > 대덕인재개발원_파이썬 프로그래밍' 카테고리의 다른 글

231109_Django 과제 1  (0) 2023.11.09
231109_Django 개론 2  (0) 2023.11.09
231107_DB 개론 2  (0) 2023.11.07
231106_DB 개론 1  (0) 2023.11.06
231106_파이썬 기초 8  (0) 2023.11.06