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

SQLite Flask

Python ha un supporto nativo per SQLite. Il modulo SQLite3 è incluso nel rilascio di Python. In questa sezione, vedremo come l'applicazione Flask interagisce con SQLite.

Crea un database SQLite ‘database.db’e crea una tabella student.

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : it.oldtoolbag.com
# Date : 2020-08-08
import sqlite3
 conn = sqlite3.connect('database.db')
 print "Database aperto con successo";
 conn.execute('CREATE TABLE students (name TEXT, addr TEXT, city TEXT, pin TEXT)')
 print "Tabella creata con successo";
 conn.close()

L'applicazione Flask ha tre funzioni di vista.

La funzione new_student() è associata alla regola di URL (‘/addnew’). Mostra il file HTML del modulo delle informazioni dello studente.

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

Ecco lo script HTML di 'student.html' -

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : it.oldtoolbag.com
# Date : 2020-08-08
<html>
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <title>Esempio Flask</title>
 </head>
    <body>
     <form action="{{ url_for('addrec') }}" method="POST">
          <h3>Informazioni dello studente</h3>
          Nome<br>
          <input type="text" name="nm"/></br>
          Indirizzo<br>
          <textarea name="add"/><br>
          Città<br>
          <input type="text" name="city"/><br>
          Codice postale<br>
          <input type="text" name="pin"/><br>
          <input type="submit" value="Invia" /><br>
       </form>
    </body>
 </html>

Si può notare che i dati del modulo vengono inviati al funzione addrec() associata a URL => ‘/addrec’.

La funzione addrec() recupera i dati del modulo tramite il metodo POST e li inserisce nella tabella studenti. I messaggi corrispondenti al successo o all'errore dell'operazione di inserimento vengono presentati in ‘result.html’.

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : it.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 Lo script HTML contiene espressioni di escape per visualizzare il risultato dell'operazione di inserimento {{ msg }}.

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : it.oldtoolbag.com
# Date : 2020-08-08
<html>
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <title>Esempio Flask</title>
 </head>
    <body>
       Risultato dell'operazione: {{ msg }}
       <h2><a href="/">Torna alla pagina principale</a></h2>
    </body>
 </html>

L'applicazione contiene un'altra funzione list() rappresentata dalla URL => ‘/list’. Questa funzione riempie ‘righe’ con un oggetto MultiDict contenente tutti i record della tabella studenti. Questo oggetto viene passato al template list.html.

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : it.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)

Questo file list.html è un template che itera attraverso l'insieme di righe e presenta i dati in una tabella HTML.

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : it.oldtoolbag.com
# Date : 2020-08-08
<html>
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <title>Esempio Flask</title>
 </head>
    <body>
       <table border="1">
          <thead>
             <td>Rinomina</td>
             <td>Indirizzo</td>
             <td>Città</td>
             <td>Codifica</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="/">Torna alla pagina principale</a>
    </body>
 </html>

Infine, la regola URL => ‘/’ presenta ‘home.html’ come punto di ingresso dell'applicazione.

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

Ecco il codice completo dell'applicazione Flask-SQLite.

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : it.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("Database aperto con successo")
     conn.execute('CREATE TABLE students (name TEXT, addr TEXT, city TEXT, pin TEXT)')
     print("Tabella creata con successo")
     conn.close()
     return None
 if __name__ == '__main__':
     app.run(debug=True)

Esegui questo script dal shell di Python e avvia il server di sviluppo. Accedi a: http://localhost:5000/ per visualizzare un menu semplice come questo nel browser -

Clicca Aggiungi informazioni studentesche Il link apre il modulo di inserimento delle informazioni degli studenti.

Compila il modulo e invialo. La funzione di basso livello inserisce questa registrazione nella tabella degli studenti.

Torna alla pagina principale e clicca sul link "Visualizza elenco" per visualizzare la tabella dei dati di esempio.