Flask Sqlite3 python Web App Tutorial
1) Creating Database
import sqlite3
conn = sqlite3.connect('bookapp.db')
conn.execute("create table Books (id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
quantity INT NOT NULL,
edition INT NOT NULL,
year INT NOT NULL,
price INT NOT NULL)")
conn.close()
2) need to create template folder and add html files to it
2.1)Html Form (Template folder)
<html>
<head>
<title>form</title>
</head>
<body>
<form action="/input" method="post">
<p>Bookname</p>
<input name="name" type="text" /><br /><br />
<p>Bookquantity</p>
<input name="quantity" type="text" /><br /><br />
<p>edition</p>
<input name="edition" type="text" /><br /><br />
<p>Bookyear</p>
<input name="year" type="text" /><br /><br />
<p>Bookprice</p>
<input name="price" type="text" /><br /><br />
<tr><td><input type="submit" value="Submit" /></td></tr>
</form>
<a href="/view">View Data</a><br /><br />
</body>
</html>
2.2)Data view (Template Folder)
<html>
<head>
</head>
<body>
<table border="5">
<thead>
<td>ID</td>
<td>name</td>
<td>quantity</td>
<td>edition</td>
<td>year</td>
<td>price</td>
</thead>
{% for row in rows %}
<tr>
<td>{{row["id"]}}</td>
<td>{{row["name"]}}</td>
<td>{{row["quantity"]}}</td>
<td>{{row["edition"]}}</td>
<td>{{row["year"]}}</td>
<td>{{row["price"]}}</td>
</tr>
{% endfor %}
</table>
<br /><br />
<a href="/">Home Page</a><br /><br />
</body>
</html>
3)main.py
import sqlite3
from flask import Flask, render_template, request, redirect, url_for
app = Flask(__name__) # creating the Flask class object
@app.route("/")
def home():
return render_template("index.html")
@app.route("/input",methods = ["POST","GET"])
def input():
if request.method == "POST":
name = request.form["name"]
quantity= request.form["quantity"]
edition =request.form["edition"]
year =request.form["year"]
price = request.form["price"]
with sqlite3.connect("bookapp.db") as con:
cur = con.cursor()
cur.execute("INSERT into Books (name, quantity, edition,year, price) values (?,?,?,?,?)", (name, quantity,edition,year,price))
con.commit()
return redirect(url_for('view'))
@app.route("/view")
def view():
con = sqlite3.connect("bookapp.db")
con.row_factory = sqlite3.Row
cur = con.cursor()
cur.execute("select * from books")
rows = cur.fetchall()
return render_template("view.html",rows = rows)
if __name__ == '__main__':
app.run(debug=True)
Comments
Post a Comment