기본 설정
axios는 라이브러리에 추가해야되기 때문에 vue프로젝트가 설정된 폴더에서 cmd 입력
npm install axios
myflask.py
from flask import Flask, redirect
from flask.json import jsonify
from flask.globals import request
from day15_server.daoemp import DaoEmp
from flask_cors.extension import CORS
app = Flask(__name__,static_url_path="",static_folder="static")
CORS(app)
@app.route('/')
def main():
return redirect('/index.html')
@app.route('/emp_list.ajax', methods=['POST', 'GET'])
def ajax_emp_list():
dao = DaoEmp()
data = dao.selectList()
return jsonify({"data" : data})
@app.route('/emp_one.ajax', methods=['POST'])
def ajax_emp_one():
dao = DaoEmp()
e_id = request.get_json()['e_id']
data = dao.selectOne(e_id)
return jsonify({"data" : data})
@app.route('/emp_add.ajax', methods=['POST'])
def ajax_emp_add():
data = request.get_json()
e_id = data['e_id']
e_name = data['e_name']
gen = data['gen']
addr = data['addr']
dao = DaoEmp()
cnt = dao.insert(e_id, e_name, gen, addr)
return jsonify({"cnt" : cnt})
@app.route('/emp_modify.ajax', methods=['POST'])
def ajax_emp_modify():
data = request.get_json()
e_id = data['e_id']
e_name = data['e_name']
gen = data['gen']
addr = data['addr']
dao = DaoEmp()
cnt = dao.update(e_id, e_name, gen, addr)
return jsonify({"cnt" : cnt})
@app.route('/emp_remove.ajax', methods=['POST'])
def ajax_emp_remove():
data = request.get_json()
e_id = data['e_id']
dao = DaoEmp()
cnt = dao.delete(e_id)
return jsonify({"cnt" : cnt})
if __name__ == '__main__':
# app.run(debug=True)
app.run(host="0.0.0.0", port=80, debug=True)
empdao.py
더보기
import pymysql
class DaoEmp :
def __init__(self):
self.conn = pymysql.connect(host='127.0.0.1',
port=3305,
user='root',
password='python',
db='python',
charset='utf8')
# DictCursor, Python에서 MySQL 쿼리 결과에 컬럼 자동으로 붙이기
# 칼럼이름 : value형식으로 출력됨
self.cur = self.conn.cursor(pymysql.cursors.DictCursor)
def selectList(self):
# sql문
sql = f"""
SELECT *
FROM emp
"""
# sql문을 cur에 입력
self.cur.execute(sql)
# 데이타 Fetch (가져오기)
rows = self.cur.fetchall()
return rows
def selectOne(self, eId):
# sql문
sql = f"""
SELECT *
FROM emp
WHERE e_id='{eId}'
"""
# sql문을 cur에 입력
self.cur.execute(sql)
# 데이타 Fetch (가져오기)
vo = self.cur.fetchone()
return vo
# list = self.cur.fetchall()
# return list[0]
def insert(self, eId, eName, gen, addr):
# sql문
sql = f"""
INSERT INTO emp
VALUES({eId}, {eName}, {gen}, {addr})
"""
# sql문을 cur에 입력
cnt = self.cur.execute(sql)
self.conn.commit()
return cnt
def update(self, eId, eName, gen, addr):
# sql문
sql = f"""
UPDATE emp
SET e_name='{eName}', gen='{gen}', addr='{addr}'
WHERE e_id='{eId}'
"""
# sql문을 cur에 입력
cnt = self.cur.execute(sql)
self.conn.commit()
return cnt
def delete(self, eId):
# sql문
sql = f"""
DELETE FROM emp
WHERE e_id ='{eId}'
"""
# sql문을 cur에 입력
cnt = self.cur.execute(sql)
self.conn.commit()
return cnt
def __del__(self):
self.cur.close()
self.conn.close()
if __name__ == '__main__':
de = DaoEmp()
cnt = de.insert(6, 6, 6, 6)
print(cnt)
list = de.selectOne(6)
print(list)
Emp.vue
<script setup>
import {onMounted, reactive} from "vue";
import axios from "axios";
// 방법 2
const empdata = reactive({
e_id : "",
e_name : "",
gen : "",
addr : "",
emp : [
{e_id : '1', e_name : '1', gen : '1', addr: '1'},
{e_id : '2', e_name : '2', gen : '2', addr: '1'},
{e_id : '3', e_name : '3', gen : '3', addr: '1'}
]
});
onMounted(()=>{
fn_list();
})
function fn_list(){
// emp_list.ajax
axios.post('http://localhost/emp_list.ajax').then(function(res){
//console.log(res.data.data);
empdata.emp = res.data.data;
let str = "";
if(empdata.emp.length==0){
str = `<tr>
<td colspan="4">검색된 데이터가 없습니다</td>
</tr>`;
document.querySelector('#my_tbody').innerHTML = str;
}
});
}
function fn_one(e){
var eId = e.target.textContent;
// console.log(this.text) // 위와 동일
axios.post('http://localhost/emp_one.ajax', {"e_id" : eId} ).then(function(res){
//console.log(res.data.data);
let empone = res.data.data;
empdata.e_id = empone.e_id;
empdata.e_name = empone.e_name;
empdata.gen = empone.gen;
empdata.addr = empone.addr;
});
}
function add(){
/*
emp.push({e_id : '4', e_name : '4', gen : '4', addr: '4'});
emp = emp.filter(item => item.e_id%2==0); // 바로 넣기 위해서 filter작성
*/
let data = {
"e_id" : empdata.e_id,
"e_name" : empdata.e_name,
"gen" : empdata.gen,
"addr" : empdata.addr
};
axios.post('http://localhost/emp_add.ajax', data ).then(function(res){
//console.log(res.data);
var cnt = res.data.cnt;
if(cnt==0){
alert('문제가 생겨 추가가 완료되지 않았습니다')
return;
}
fn_list();
reset();
});
}
function modify(){
let data = {
"e_id" : empdata.e_id,
"e_name" : empdata.e_name,
"gen" : empdata.gen,
"addr" : empdata.addr
};
axios.post('http://localhost/emp_modify.ajax', data ).then(function(res){
//console.log(res.data);
var cnt = res.data.cnt;
if(cnt==0){
alert('문제가 생겨 수정이 완료되지 않았습니다')
return;
}
fn_list();
reset();
});
}
function remove(){
let data = {
"e_id" : empdata.e_id,
};
if(confirm("정말로 삭제하시겠습니까?")){
axios.post('http://localhost/emp_remove.ajax', data ).then(function(res){
//console.log(res.data);
var cnt = res.data.cnt;
if(cnt==0){
alert('문제가 생겨 수정이 완료되지 않았습니다')
return;
}
fn_list();
reset();
});
}
}
function reset(){
empdata.e_id = "";
empdata.e_name = "";
empdata.gen = "";
empdata.addr = "";
}
</script>
<template>
<table border="1">
<thead>
<tr>
<th>사번</th>
<th>이름</th>
<th>성별</th>
<th>주소</th>
</tr>
</thead>
<tbody id="my_tbody">
<tr v-for="(e) in empdata.emp">
<td><a @click=fn_one>{{ e.e_id }}</a></td>
<td>{{ e.e_name }}</td>
<td>{{ e.gen }}</td>
<td>{{ e.addr }}</td>
</tr>
</tbody>
</table>
<br>
<table border="1">
<tbody>
<tr>
<th>사번</th>
<td><input type="text" id="e_id" v-model="empdata.e_id"></td>
</tr>
<tr>
<th>이름</th>
<td><input type="text" id="e_name" v-model="empdata.e_name"></td>
</tr>
<tr>
<th>성별</th>
<td><input type="text" id="gen" v-model="empdata.gen"></td>
</tr>
<tr>
<th>주소</th>
<td><input type="text" id="addr" v-model="empdata.addr"></td>
</tr>
<tr>
<td colspan="2">
<input type="button" value="추가" @click=add>
<input type="button" value="수정" @click=modify>
<input type="button" value="삭제" @click=remove>
</td>
</tr>
</tbody>
</table>
</template>
'Python' 카테고리의 다른 글
[Python] react (0) | 2024.07.17 |
---|---|
[Python] emp - svelte로 crud(fetch) (0) | 2024.07.16 |
[Python] node.js - vue.js (0) | 2024.07.12 |
7/11 Homework - (svelte) 구구단, 가위바위보 (0) | 2024.07.12 |
[Python] node.js - svelte (0) | 2024.07.11 |