main.py
from flask import Flask, render_template, request
import sqlite3
from flask import g
app = Flask(__name__)
DATABASE = 'cs.db'
def connect_db():
return sqlite3.connect(DATABASE)
@app.before_request
def before_request():
g.db = connect_db()
@app.teardown_request
def teardown_request(exception):
if hasattr(g, 'db'):
g.db.close()
@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']
g.db.execute(
"INSERT INTO students(name, addr, city, pin) VALUES(?, ?, ?, ?)", (nm, addr, city, pin))
g.db.commit()
msg = "Record successfully added"
except:
g.db.rollback()
msg = "error in insert operation"
finally:
return render_template("result.html", msg=msg)
g.db.close()
@app.route('/list')
def list():
g.db.row_factory = sqlite3.Row
cur = g.db.execute("select * from students")
rows = cur.fetchall()
return render_template("list.html", rows=rows)
if __name__ == '__main__':
app.run(debug=True)
补充getjson:
@app.route('/getjson')
def getjson():
g.db.row_factory = sqlite3.Row
cur = g.db.execute("select * from students")
rows = cur.fetchall()
l = [dict(name=row[0], addr=row[1], city=row[2], pin=row[3])
for row in rows]
# a = [{"Id": 1, "Name": "zs"}, {"Id": 2, "Name": "lisi"}]
return json.dumps(l, ensure_ascii=False)
home.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=a, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<a href="/enternew">Add New Record</a>
<a href="/list">Show List</a>
</body>
</html>
result.html:
<!DOCTYPE html>
<html>
<body>
result of addition : {{ msg }}
<h2><a href="\">go back to home page</a></h2>
</body>
</html>
list.html:
<!DOCTYPE html>
<html>
<body>
<table border="1">
<thead>
<td>Name</td>
<td>Address>/td<</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>
student.html:
<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>
|