English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Flask SQLite

Python은 SQLite에 내장된 지원을 가지고 있습니다. SQlite3모듈은 Python 배포판에 포함되어 있습니다. 이 장에서는 Flask 애플리케이션이 SQLite와 어떻게 상호작용하는지 보여드립니다。

SQLite 데이터베이스를 생성합니다 ‘database.db’그리고 그 안에 student 테이블을 생성합니다。

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : ko.oldtoolbag.com
# Date : 2020-08-08
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()

Flask 애플리케이션은 세 가지 뷰 함수를 가지고 있습니다。

첫 번째 new_student() 함수는 URL 규칙(‘/addnew())。 이는 학생 정보 양식을 포함한 HTML 파일을 표시합니다。

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : ko.oldtoolbag.com
# Date : 2020-08-08
@app.route('/enternew')
 def new_student():
     return render_template('student.html')

‘student.html’의 HTML 스크립트는 다음과 같습니다 -

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : ko.oldtoolbag.com
# Date : 2020-08-08
<html>
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <title>Flask 예제</title>
 </head>
    <body>
     <form action="{{ url_for('addrec') }}" method="POST">
          <h3>학생 정보</h3>
          이름<br>
          <input type = "text" name = "nm" /></br>
          주소<br>
          <textarea name = "add" /><br>
          도시<br>
          <input type = "text" name = "city" /><br>
          우편번호<br>
          <input type = "text" name = "pin" /><br>
          <input type = "submit" value = "제출" /><br>
       </form>
    </body>
 </html>

보면, 양식 데이터는 addrec() 함수에 연결된 URL => ‘/addrec’

이 addrec() 함수는 POST 메서드를 통해 양식 데이터를 검색하고 학생 테이블에 삽입합니다. 삽입 작업에서 성공이나 오류와 관련된 메시지는 'result.html'로 표시됩니다。

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : ko.oldtoolbag.com
# Date : 2020-08-08
@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("result.html", msg = msg)
           con.close()

result.html 의 HTML 스크립트는 삽입 작업 결과를 표시하는 응축 문장 {{ msg }}을 포함하고 있습니다。

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : ko.oldtoolbag.com
# Date : 2020-08-08
<html>
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <title>Flask 예제</title>
 </head>
    <body>
       작업 결과 : {{ msg }}
       <h2><a href = "/">홈페이지로 돌아가기</a></h2>
    </body>
 </html>

이 애플리케이션은 URL => ‘/list’은 다른 list() 함수를 나타냅니다. 이 함수는 학생 테이블에 모든 기록을 포함한 MultiDict 객체를 '행'으로 채웁니다. 이 객체는 list.html 템플릿으로 전달됩니다。

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : ko.oldtoolbag.com
# Date : 2020-08-08
@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("list.html", rows=rows)

이 list.html은 템플릿으로, 행 집합을 순회하며 HTML 테이블에 데이터를 표시합니다。

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : ko.oldtoolbag.com
# Date : 2020-08-08
<html>
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <title>Flask 예제</title>
 </head>
    <body>
       <table border = 1>
          thead>
             <td>이름</td>
             <td>주소</td>
             <td>도시</td>
             <td>编码</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 = "}}/">홈페이지로 돌아가기</a>
    </body>
 </html>

마지막으로, URL => ‘/‘규칙 표현하다’ home.html’를 애플리케이션의 진입점으로 설정합니다.

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : ko.oldtoolbag.com
# Date : 2020-08-08
@app.route('/)
 def home():
     return render_template('home.html')

이곳에 Flask-SQLite 애플리케이션의 전체 코드.

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : ko.oldtoolbag.com
# Date : 2020-08-08
from flask import Flask, render_template, request
 import sqlite3 as sql
 import sqlite3
 app = Flask(__name__)
 @app.route('/)
 def home():
     return render_template('home.html')
 @app.route('/enternew')
 def new_student():
     return render_template('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("result.html", msg = msg)
           con.close()
 @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("list.html", rows=rows)
 @app.route('/init())
 def init():
     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()
     return None
 if __name__ == '__main__':
     app.run(debug=True)

이 스크립트를 Python 셸에서 실행하고 개발 서버가 실행될 때까지 실행합니다. 접근: http:// localhost:5000/ 이러한 간단한 메뉴가 브라우저에서 표시됩니다 -

클릭 학생 정보 추가 학생 정보 입력 양식을 추가하는 링크를 열어주세요。

양식을 작성하고 제출하세요. 하위 함수는 이 레코드를 학생 테이블에 삽입합니다。

메인 페이지로 돌아가고 "리스트 표시" 링크를 클릭하면 샘플 데이터 테이블이 표시됩니다。