본문 바로가기
PRACTICE/Basic

[Flask] SQLite 예제

by 1005 2020. 9. 24.

 

 

Flask – SQLite - Tutorialspoint

Flask – SQLite Python has an in-built support for SQlite. SQlite3 module is shipped with Python distribution. For a detailed tutorial on using SQLite database in Python, please refer to this link. In this section we shall see how a Flask application inte

www.tutorialspoint.com

 

< 폴더 경로 >

 

 

 

< create_db.py >

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import sqlite3
 
conn = sqlite3.connect('database.db')
print('데이터베이스 생성 성공!')
 
conn.execute(
    '''
    create table students (name text, addr text, city text, pin text)
    '''
)
print('테이블 생성 성공!')
 
conn.close()
 

 

activate edge1(가상환경이름)

conda list sqlite (sqlite를 실행하기위해 패키지를 설치함.)

python create_db.py

 

create_db.py파일이 정상적으로 실행되면

동일한 경로상에 datebase.db 파일이 생성된다.

 

< DB 스키마 > 

 

DB Browser(SQLite)를 통해서

students 테이블이 정상적으로 만들어진 것을 확인할 수 있다.

 

 

 

< app.py >

 

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
from flask import Flask, render_template, request
import sqlite3 as sql
app = Flask(__name__)
 
@app.route('/')
def home():
    return render_template('home.html')
 
@app.route('/enternew'#데이터 입력 form.
def new_student():
   return render_template('student.html')
 
@app.route('/addrec',methods = ['POST''GET']) #student.html에서 입력한 값들을 post로 전달받음.
def addrec():
   if request.method == 'POST':
      try:
         nm = request.form['nm']
         addr = request.form['add']
         city = request.form['city']
         pin = request.form['pin']
         
         with sql.connect("database.db"as con:
             #db 입력창에 입력커서 놓기.
            cur = con.cursor()
            
            #db에 값 입력. (메모리상 입력o, db에 입력x)
            cur.execute("INSERT INTO students (name,addr,city,pin) VALUES (?,?,?,?)",(nm,addr,city,pin) )
            
            con.commit() #db에 값 저장. (데이터베이스에 입력됨.)
            msg = "Record successfully added"
 
      except:
         con.rollback()
         msg = "error in insert operation"
      
      finally: #try를 하던 except을 하던 finally는 무조건 한번 실행됨. 
         return render_template("result.html",msg = msg) #파이썬에 있는 msg객체를 result.html에 전달.
         con.close() #db 닫음.
 
@app.route('/list')
def list():
   con = sql.connect("database.db"#database.db파일에 접근.
   con.row_factory = sql.Row 
   # row_factory: 값을 지정하여 개별 행을 원하는 파이썬 타입으로 변환.
   # sqlite3.Row: 기본적인 key, value 로 액세스가 가능한 객체가 리턴됨. 
   
   cur = con.cursor() #입력커서 놓기.
   cur.execute("select * from students"#데이터 검색 
   
   rows = cur.fetchall(); #레코드 단위로 데이터를 전달받음.
   return render_template("list.html",rows = rows) #rows객체를 리스트 타입으로 list.html에 전달.
 
if __name__ == '__main__':
   app.run(host='0.0.0.0', port = 80, debug = True)

 

< home.html >

 

1
2
3
4
5
6
7
8
9
10
11
12
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>home</title>
</head>
<body>
    <h1>HOME</h1>
    <a href = "/list">show list</a> 
</body>
</html>

 

 

< student.html >

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<html>
   <body>
      <form action = "{{ url_for('addrec') }}" method = "POST">
         <h3>Student Information</h3>
         Name<br>
         <input type = "text" name = "nm" /></br>
         
         Address<br>
         <textarea name = "add" ></textarea><br>
         
         City<br>
         <input type = "text" name = "city" /><br>
         
         PINCODE<br>
         <input type = "text" name = "pin" /><br>
         <input type = "submit" value = "submit" /><br>
      </form>
   </body>
</html>

 

< result.html >

 

1
2
3
4
5
6
<!doctype html>
<
html>
   <body>
       result of addition: {{ msg }}
         <h2><a href = "\">go back to home page</h2>
   </body>
</html>

 

 

< list.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
<!doctype html>
<html>
   <body>
      <table border = 1>
         <thead>
            <td>Name</td>
            <td>Address</td>
            <td>city</td>
            <td>Pincode</td>
         </thead>
         
         {% for row in rows %} <!-- rows는 리스트 타입으로 전달받았음.-->
            <tr>
               <td>{{row["name"]}}</td>    <!--키 값을 통해 value 값 출력.-->
               <td>{{row["addr"]}}</td>
               <td>{{row["city"]}}</td>
               <td>{{row['pin']}}</td>    
            </tr>
         {% endfor %}
      </table>
      
      <a href = "/">Go back to home page</a>
   </body>
</html>

댓글