ddit/Python

220906파이썬 web과 MariaDB연동하기

ssong2ku 2022. 9. 7. 20:45
728x90

new Django 프로젝트 만들기 -> Run as ->장고 start

주소복사->로켓표시가 나오면 실행성공

@csrf_exempt 추가해주기

->오류나는 페이지 전

추가한 일부분에만 적용

 

settings- >위의 코드 추가-> 전체프로젝트에 대해서 오류방지

 

 

-views

from django.shortcuts import render, redirect
import pymysql

from HELLOEMP.daoemp import DaoEmp
from django.views.decorators.csrf import csrf_exempt
from aiohttp.client import request

de=DaoEmp()

def emp_list(request):
    
    de= DaoEmp()
    mylist=de.mylist()
    
    attr={
        'mylist':mylist
    }
    
    return render(request,"emp_list.html",attr)

def emp_add(request):
    return render(request,"emp_add.html")

@csrf_exempt 
def emp_add_act(request):
    e_id=request.POST.get("e_id")
    e_name=request.POST.get("e_name")
    sex=request.POST.get("sex")
    addr=request.POST.get("addr")
    
    de=DaoEmp()
    cnt=de.myinsert(e_id, e_name, sex, addr)
    
    attr={
        "cnt":cnt
    }   
    #return render(request,"emp_add_act.html", {"cnt":cnt} )
    return render(request,"emp_add_act.html", attr)

def emp_detail(request):
    e_id=request.GET.get("e_id")
    emp=de.myone(e_id)
    attr={
        "emp":emp
        } 
    return render(request, "emp_detail.html",attr)

def emp_mod(request):
    e_id=request.GET.get("e_id")
    emp=de.myone(e_id)
    attr={
        "emp":emp
        } 
    
    return render(request,"emp_mod.html",attr)

@csrf_exempt 
def emp_mod_act(request):
    e_id=request.POST.get("e_id")
    e_name=request.POST.get("e_name")
    sex=request.POST.get("sex")
    addr=request.POST.get("addr")
    print(e_id, e_name, sex, addr)
    cnt=de.myupdate(e_id, e_name, sex, addr)
    print(cnt)
    
    attr={
        "cnt":cnt
    }   
    return render(request,"emp_mod_act.html", attr)

def emp_delete(request):
    e_id=request.POST.get("e_id")
    emp=de.mydelete(e_id)
    attr={
        "emp":emp
        } 
    print(attr)
    return render(request,"emp_delete.html",attr)

 

 

--urls

"""HELLOEMP URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/4.1/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 HELLOEMP import views

urlpatterns = [
    # path('admin/', admin.site.urls),
    path('', views.emp_list),
    path('emp_list', views.emp_list),
    path('emp_add', views.emp_add),
    path('emp_add_act', views.emp_add_act),
    path('emp_detail', views.emp_detail),
    path('emp_mod', views.emp_mod),
    path('emp_mod_act', views.emp_mod_act),
    path('emp_delete', views.emp_delete),
]

 

-DaoEmp

import pymysql

class DaoEmp:
    def __init__(self):
        self.con = pymysql.connect(host='127.0.0.1', user='root', password='python',
                       db='python', charset='utf8', port=3305) # 한글처리 (charset = 'utf8')
 
        #DictCursor은  json이랑 비슷한 형식
        self.cur = self.con.cursor(pymysql.cursors.DictCursor)
        
    def mylist(self):
        sql = "SELECT * FROM EMP"
        self.cur.execute(sql)
        mylist = self.cur.fetchall()
        
        return mylist
    
    def myone(self,e_id):
        sql = f"""SELECT e_id,e_name,sex,addr FROM EMP where e_id='{e_id}'"""
        self.cur.execute(sql)
        myone = self.cur.fetchall()
        
        return myone[0]
        
        
    #소멸자 GC없어서 메모리를 소멸시켜줘야함    
    def __del__(self):
        self.cur.close()
        self.con.close()  
    
    def myinsert(self,e_id,e_name,sex,addr):
       
        sql=f"""insert into emp(e_id, e_name, sex, addr) 
               values('{e_id}','{e_name}','{sex}','{addr}')"""
        cnt=0       
        try:
            cnt = self.cur.execute(sql)
            self.con.commit()
        except:
            cnt=0       
        
        return cnt
    
    def myupdate(self,e_id,e_name,sex,addr):
        sql = f"""update emp 
        set e_name='{e_name}',sex='{sex}',addr='{addr}' 
        where e_id='{e_id}'"""

        emp=self.cur.execute(sql)

        self.con.commit()
        
        return emp
    
    def mydelete(self,e_id):
        sql = f"""delete from emp where e_id='{e_id}'"""
        emp = self.cur.execute(sql)
        self.con.commit()     
        
        return emp
        
if __name__ == '__main__':
    de = DaoEmp()
    list = de.mylist()
    #print("list",list[3]["addr"])
    # emp=de.myone('3')
    # print("emp",emp)
    
    cnt=de.myinsert('5','5','5','5')
    print("cnt",cnt)
    
    # emp=de.myupdate('7', '7', '7', '7', '5')
    # print("emp",emp)
    
    # emp = de.mydelete('2')
    # print("emp : ",emp)

 

●templete

-emp_list

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
	function fn_add(){
		location.href="emp_add"
	}
</script>
</head>
<body>
EMP_LIST<br/>
<table border='1'>
<th>사번</th><th>이름</th><th>성별</th><th>주소</th>
{%for e in mylist%}
	<tr>
	<td><a href="emp_detail?e_id={{e.e_id}}">{{e.e_id}}</a></td>
	<td>{{e.e_name}}</td>
	<td>{{e.sex}}</td>
	<td>{{e.addr}}</td>
	</tr>
{%endfor%}
</table>
<input type="button" value="추가" onclick="fn_add()"/>
</body>
</html>

-emp_detail

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
	function fn_mod(){
		var e_id ="{{emp.e_id}}"
		location.href="emp_mod?e_id="+e_id
	}
	function fn_del(){
		//[idx]가 없으면 배열로 받음
		var frm = document.getElementsByName("frm")[0];
		frm.submit();
	}
</script>
</head>
<body>
	EMP_Detail
	<br/>
	<form id="frm" name="frm" action="emp_delete" method="post">
		<input type="hidden" name="e_id" value="{{emp.e_id}}">
	</form>
	<form action="">
	<input type="hidden" name="e_id" value="{{emp.e_id}}">
	<table border="1">
	
		<tr>
			<td>사번</td>
			<td colspan="2">{{emp.e_id}}</td>
		</tr>
		<tr>	
			<td>이름</td>
			<td colspan="2">{{emp.e_name}}</td>
		</tr>	
		<tr>
			<td>성별</td>
			<td colspan="2">{{emp.sex}}</td>
		</tr>	
			<td>주소</td>
			<td colspan="2">{{emp.addr}}</td>
		</tr>
		<tr>
			<!-- <td colspan="2"><input type="submit" value="수정"/></td> -->
			<td colspan="2"><input type="button" value="수정"  onclick="fn_mod()"/></td>
			<td colspan="2"><input type="button" value="삭제"  onclick="fn_del()"/></td>
	</table>
	</form>
</body>
</html>

-emp_add

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	EMP_ADD
	<br/>
	<form action="emp_add_act" method="post">
	<table border="1">
	
		<tr>
			<td>사번</td>
			<td><input type="text" name="e_id"></td>
		</tr>
		<tr>	
			<td>이름</td>
			<td><input type="text" name="e_name"></td>
		</tr>	
		<tr>
			<td>성별</td>
			<td><input type="text" name="sex"></td>
		</tr>	
			<td>주소</td>
			<td><input type="text" name="addr"></td>
		</tr>
		<tr>
			<td colspan="2"><input type="submit" value="실행"></td>
		</tr>
	</table>
	</form>
</body>
</html>

-emp_add_act

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript">
function fn_add(){
	var cnt='{{cnt}}';
	if(cnt=='1'){
		alert('성공적으로 추가되었습니다.');
		location.href="emp_list";
	}else{
		alert('추가에 실패하였습니다.');
		//history.back();
		history.go(-1);
	}
}
</script>
<title>Insert title here</title>
</head>
<body onload="fn_add()">
	
</body>
</html>

-emp_mod

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	EMP_MOD
	<br/>
	<form action="emp_mod_act" method="post">
	<table border="1">
		<tr>
			<td>사번</td>
			<td><input type="text" name="e_id" value="{{emp.e_id}}" readonly ></td>
		</tr>
		<tr>	
			<td>이름</td>
			<td><input type="text" name="e_name" value="{{emp.e_name}}"></td>
		</tr>	
		<tr>
			<td>성별</td>
			<td><input type="text" name="sex" value="{{emp.sex}}"></td>
		</tr>	
			<td>주소</td>
			<td><input type="text" name="addr" value="{{emp.addr}}"></td>
		</tr>
		<tr>
			<td colspan="2"><input type="submit" value="수정"></td>
		</tr>
	</table>
	</form>
</body>
</html>

 

-emp_mod_act

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript">
function fn_add(){
	var cnt='{{cnt}}';
	if(cnt=='1'){
		alert('성공적으로 수정되었습니다.');
		location.href="emp_list";
	}else{
		alert('수정에 실패하였습니다.');
		//history.back();
		history.go(-1);
	}
}
</script>
<title>Insert title here</title>
</head>
<body onload="fn_add()">
	
</body>
</html>

 

-emp_delete

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript">
function fn_delete(){
	var cnt='{{emp}}';
	if(cnt=='1'){
		alert('성공적으로 삭제되었습니다.');
		location.href="emp_list";
	}else{
		alert('삭제에 실패하였습니다.');
		//history.back();
		history.go(-1);
	}
}
</script>
<title>Insert title here</title>
</head>
<body onload="fn_delete()">
	
</body>
</html>
728x90