how to save form data to database in flask\ code example
Example: how to save form data to database in flask\
import sqlite3 as sql
from my_app import app
from flask import render_template, request
con = sql.connect('qa_database.db')
con.execute('CREATE TABLE IF NOT EXISTS tbl_QA (ID INTEGER PRIMARY KEY AUTOINCREMENT,'
+ 'question TEXT, answer TEXT)')
con.close
@app.route('/')
def index():
return render_template('index.html')
@app.route('/create', methods=['GET', 'POST'])
def create():
if request.method == 'GET':
return render_template('create.html')
else:
question = request.form['question']
answer = request.form['answer']
try:
con = sql.connect('qa_database.db')
c = con.cursor()
c.execute("INSERT INTO tbl_QA (question, answer) VALUES (?,?)",
(question, answer))
con.commit()
return render_template('createThanks.html', question=question)
except con.Error as err:
return render_template('database_error.html', error=err)
finally:
con.close()
@app.route('/question/<int:id>', methods=['GET', 'POST'])
def question(id):
if request.method == 'GET':
try:
con = sql.connect('qa_database.db')
c = con.cursor()
query = "Select question FROM tbl_QA where id = {0}".format(id)
c.execute(query)
question = c.fetchone()
con.commit()
return render_template('question.html', question=question[0])
except con.Error as err:
return render_template('database_error.html', error=err)
finally:
con.close()
return render_template('question.html', question=question)
else:
submitted_answer = request.form['answer']
try:
con = sql.connect('qa_database.db')
c = con.cursor()
query = "Select answer FROM tbl_QA where id = {0}".format(id)
c.execute(query)
correct_answer = c.fetchone()[0]
con.commit()
except con.Error as err:
return render_template('database_error.html', error=err)
finally:
con.close()
if submitted_answer == correct_answer:
return render_template('correct.html');
else:
return render_template('sorry.html',
answer = correct_answer,
yourAnswer = submitted_answer
)