참고 arr - filter
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script>
var arr = [1,2,3,4];
function isEven(value){
return value % 2 == 0;
}
arr = arr.filter(isEven); // [2,4]
arr = arr.filter(item => item%2 == 0); // 위와 동일
console.log(arr);
</script>
</head>
<body>
</body>
</html>
svelte
해당 flask와 svelte를 따로 구동하기 위해선 flask에 CORS를 포함해야한다
pip install flask-cors
한 후 flask에서
CORS(app)을 추가해 줄것
myflask.py
from flask import Flask, redirect
from flask.json import jsonify
from flask.globals import request
from day14_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)
daoemp.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.svelte
<script>
import {onMount} from "svelte";
let e_id = "";
let e_name = "";
let gen = "";
let addr = "";
let 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'}
]
// 생명주기 window.onload와 유사
onMount(async ()=>{
fn_list();
})
function fn_list(){
// emp_list.ajax
fetch('http://localhost/emp_list.ajax', {
method : "POST"
}).then(function(res) {
return res.json();
}).then(function(data) {
//console.log(data);
emp = data.data;
let str = "";
if(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) // 위와 동일
fetch('http://localhost/emp_one.ajax', {
method : "POST",
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({"e_id" : eId})
}).then(function(res) {
return res.json();
}).then(function(data) {
// console.log(data);
let empone = data.data;
e_id = empone.e_id;
e_name = empone.e_name;
gen = empone.gen;
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" : e_id,
"e_name" : e_name,
"gen" : gen,
"addr" : addr
};
fetch('http://localhost/emp_add.ajax', {
method : "POST",
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
}).then(function(res) {
return res.json();
}).then(function(data) {
// console.log(data);
var cnt = data.cnt;
if(cnt==0){
alert('문제가 생겨 추가가 완료되지 않았습니다')
return;
}
fn_list();
reset();
});
}
function modify(){
let data = {
"e_id" : e_id,
"e_name" : e_name,
"gen" : gen,
"addr" : addr
};
fetch('http://localhost/emp_modify.ajax', {
method : "POST",
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
}).then(function(res) {
return res.json();
}).then(function(data) {
// console.log(data);
var cnt = data.cnt;
if(cnt==0){
alert('문제가 생겨 수정이 완료되지 않았습니다')
return;
}
fn_list();
reset();
});
}
function remove(){
let data = {
"e_id" : e_id,
};
if(confirm("정말로 삭제하시겠습니까?")){
fetch('http://localhost/emp_remove.ajax', {
method : "POST",
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
}).then(function(res) {
return res.json();
}).then(function(data) {
// console.log(data);
var cnt = data.cnt;
if(cnt==0){
alert('문제가 생겨 삭제가 완료되지 않았습니다');
return;
}
fn_list();
reset();
});
}
}
function reset(){
e_id = "";
e_name = "";
gen = "";
addr = "";
}
</script>
<style>
input[type="text"]{
width: 100px;
}
</style>
<table border="1">
<thead>
<tr>
<th>사번</th>
<th>이름</th>
<th>성별</th>
<th>주소</th>
</tr>
</thead>
<tbody id="my_tbody">
{#each emp as e}
<tr>
<td><a href="#" on:click={fn_one}>{e.e_id}</a></td>
<td>{e.e_name}</td>
<td>{e.gen}</td>
<td>{e.addr}</td>
</tr>
{/each}
</tbody>
</table>
<br>
<table border="1">
<tbody>
<tr>
<th>사번</th>
<td><input type="text" id="e_id" bind:value="{e_id}"></td>
</tr>
<tr>
<th>이름</th>
<td><input type="text" id="e_name" bind:value="{e_name}"></td>
</tr>
<tr>
<th>성별</th>
<td><input type="text" id="gen" bind:value="{gen}"></td>
</tr>
<tr>
<th>주소</th>
<td><input type="text" id="addr" bind:value="{addr}"></td>
</tr>
<tr>
<td colspan="2">
<input type="button" value="추가" on:click={add}>
<input type="button" value="수정" on:click={modify}>
<input type="button" value="삭제" on:click={remove}>
</td>
</tr>
</tbody>
</table>
'Python' 카테고리의 다른 글
[Python] react (0) | 2024.07.17 |
---|---|
[Python] emp - vue.js로 crud(axios) (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 |