[Flask] Sqlite3, Flask 응용-2 : 실습

 ※ 실습 전체적인 흐름 정리




1. sqlform url 요청
2. sqlform.html 페이지 이동
3. form 데이터 post
4. 테이블 데이터 추가 및 print_data 자체적인 redirect 수행 후, print_data.html 페이지 render_template 수행
5. print_data.html 에서 결과 확인

※ 그 외, print_data.html 에서 모든 데이터의 출력, 출력된 데이터에 대해 javaScript를 통한 수정 기능 사용


flask 스크립트 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
from flask import Flask, render_template, request, url_for, redirect, jsonify
import sqlite3
 
app = Flask(__name__)
DB = 'myDB.db'
 
#DB(데이터베이스)와 연결
def get_db():
    conn = sqlite3.connect(DB)
    return conn
 
#테이블 사전 설정
#스크립트 실행과 함께 테이블이 생성됨
@app.before_request
def setTable():
    conn = get_db()
    cursor = conn.cursor()
    cursor.execute("""CREATE TABLE IF NOT EXISTS usertable(
            index_num INTEGER PRIMARY KEY AUTOINCREMENT,
            id TEXT,
            passwd TEXT,
            review TEXT,
            check_ TEXT default 'X'
    )""")
    conn.close()
 
#테이블의 모든 값을 가져오는 메소드
def all_select():
    conn = get_db()
    cursor = conn.execute("select * from usertable")
    rows = cursor.fetchall()
    for row in rows :
        print(row)
    conn.close()
    return rows
 
#데이터를 테이블에 추가하는 메소드
#index_num과 check_ 는 자동 추가됨(각각 자동 증가, 기본값 'X')
def insert_data(id, passwd, review):
    conn = get_db()
    cursor = conn.execute(f"insert into usertable(id, passwd, review) values('{id}','{passwd}','{review}')")
    conn.commit()
    conn.close()
 
 
#입력 폼 이동
@app.route("/")
def home():
    return render_template("sqlform.html")
 
#입력 폼의 데이터를 처리
#post 방식으로 값을 전달받아, 테이블에 추가 후 다시 리다이렉트 과정을 거쳐 조회 페이지로 이동
@app.route("/print_data", methods=["GET","POST"])
def printData():
    if request.method == 'POST' :
        #데이터 조회        
        rows = all_select()
        
        #form 태그 값 수집 및 추가
        id = request.form.get("id")
        passwd = request.form.get("password")
        review = request.form.get("review")
        insert_data(id, passwd, review)
 
        #redirect 수행
        return redirect(url_for("printData"))    return render_template("print_data.html", rows=all_select())
 
 
#json 데이터를 전달 받아 현재 상태(check_) 갱신
@app.route("/update_status", methods=["POST"])
def update_status():
    data = request.json
    item_id = data.get("id")
    new_status = data.get("status")
 
    # 데이터베이스 연결
    conn = get_db()
    cursor = conn.cursor()
    
    # 업데이트 쿼리 실행
    cursor.execute("UPDATE usertable SET check_ = ? WHERE index_num = ?", (new_status, item_id))
    conn.commit()
    conn.close()
    return jsonify({"status""success"})
 
 
if __name__ == "__main__" :
    app.run(host = "0.0.0.0", port=5000)
cs

- sqlite3에 대한 갱신, 추가, 조회 등에 대한 기능을 메소드로 구현

- print_data 에서 post는 값의 받아 테이블에 추가 후 redirect 후 전체 조회 페이지로 이

- update_status 는 print_data.html의 javaScript 에서 값 갱신 작업 수행

→ update 테이블 명 set 바꿀 속성 명 = 데이터 where 특정 조건

(조건에 맞는 데이터의 속성의 값을 갱신)


sqlform.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<!DOCTYPE html>
<html>
<body>
    <!--post 방식으로 데이터를 전송하는 양식 -->
    <form method="post" action="/print_data">
        <table>
            <tr>
                <td>id</td><td><input type="text" placeholder="id" name="id" /></td>
            </tr>
            <tr>
                <td>password</td><td><input type="password" placeholder="password" name="password" /></td>
            </tr>
            <tr>
                <td>review</td><td><textarea name = review></textarea></td>
            </tr>
        </table>
        <button type="submit">send</button>
    </form>
 
    <table>
    </table>
</body>
</html>
cs


print_data.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<!DOCTYPE html>
<html>
    <body>
    <table>
        <tr>
            <td>index</td><td>id</td><td>passwd</td><td>review</td><td>check</td>
        </tr>
    <!--jinja2, 반복문을 사용하여 모든 데이터 출력-->
    <!--sqlite3 데이터는 tuple들을 원소로 갖는 list 자료형-->
    {% for row in rows %}
        <tr>
            <td>{{ row[0] }}</td>
            <td>{{ row[1] }}</td>
            <td>{{ row[2] }}</td>
            <td>{{ row[3] }}</td>
            <!-- onclick : 해당 객체 클릭시 함수 동작-->
            <td id="{{row[0]}}" onclick="check(this)">{{row[4]}}</td>
        </tr>
    {% endfor %}
    </table>
    <script>
    // 자바 스크립트를 이용하여 데이터 갱신 작업 수행    
        function check(element){
            // 클릭한 객체의 id 값은 테이블의 index_num 로 사용되고 있음
            var itemID = element.id;
 
            // '/update_status' 로 값을 post 방식으로 전달
            fetch('/update_status',{
                method:'POST',
                headers:{
                    'Content-Type''application/json' // json 데이터 전달
                },
                body: JSON.stringify({ //갱신을 할 데이터의 index_num, 바꿀 값을 전달
                    id : itemID,
                    status : 'O'
                })
            }).then(Response => Response.json()). //데이터 전달 후 응답 데이터를 받음
            then(data => {
                    if(data.status == 'success'){ //응답 데이터에 따라 버튼의 형태를 바꾸거나, 오류 내역 
                        element.textContent = 'O';
                    }
                }).catch(error => console.log('error : ', error));
        }
    </script>
    </body>
</html>
cs

- 데이터의 갱신은 javaScrpt 의 json 데이터 전송을 사용하여 진생

- javaScrpt 의 onclick 적용 방법을 참고하여 수행

- 이후 전체 데이터의 조회의 경우 javaScrpt를 이용하여 출력 구현 예정


댓글