IT/Flask
[Flask] SQLite3
Dragonz
2020. 9. 9. 15:29
반응형
Flask 는 SQLite 를 내장지원한다. 우선 임시 프로그램을 이용하여 데이터베이스와 connection 을 맺고 테이블을 하나 생성한다.
파일명 : sqlite_temp.py
import sqlite3
conn = sqlite3.connect('database.db')
print ('Opened database successfully')
conn.execute('CREATE TABLE STUDENTS (NAME TEXT, ADDR TEXT, CITY TEXT, PIN TEXT)')
print ('Table created successfully')
conn.close()
프로그램이 정상 종료 되었다면 'database.db' 라는 파일이 생성되어 있을 것이다.
파일명 : 16_sqlite3.py
from flask import Flask, render_template, request
import sqlite3 as sql
app = Flask(__name__)
@app.route('/')
def home() :
return render_template('16_home.html')
@app.route('/enternew')
def new_student() :
return render_template('16_student.html')
@app.route('/addrec', methods = ['POST','GET'])
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 :
cur = con.cursor()
cur.execute('INSERT INTO STUDENTS (NAME, ADDR, CITY, PIN) VALUES (?,?,?,?)', (nm, addr, city, pin))
con.commit()
msg = 'Record successfully added'
except :
con.rollback()
msg = 'Error in insert operation'
finally :
return render_template('16_result.html', msg = msg)
con.close()
return ''
@app.route('/list')
def list() :
con = sql.connect('database.db')
con.row_factory = sql.Row
cur = con.cursor()
cur.execute('SELECT * FROM STUDENTS')
rows = cur.fetchall()
return render_template('16_list.html', rows = rows)
if __name__ == '__main__' :
app.run(debug = True)
파일명 : 16_home.html
<!doctype html>
<html>
<body>
<p><h2><a href = "http://localhost:5000/enternew">Add New Record</a></h2></p>
<p><h2><a href = "http://localhost:5000/list">Show List</a></h2></p>
</body>
</html>
파일명 : 16_student.html
<!doctype html>
<html>
<body>
<form action = "{{ url_for('addrec') }}" method = "POST">
<h3>Student Information</h3>
<p>Name<br/>
<input type = "text" name = "nm" />
</p>
<p>Address<br/>
<textarea name = "add"></textarea>
</p>
<p>City<br/>
<input type = "text" name = "city" />
</p>
<p>PINCODE<br/>
<input type = "text" name = "pin" />
</p>
<p>
<input type = "submit" />
</p>
</form>
</body>
</html>
파일명 : 16_result.html
<!doctype html>
<html>
<body>
<p>result of addition : {{ msg }}</p>
<p><h2><a href="\">Go back to home page</a></h2></p>
</body>
</html>
파일명 : 16_list.html
<!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 %}
<tr>
<td>{{ row["name"] }}</td>
<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>
END
반응형