Im attempting to insert into a SQL database from a form in a flask app.
I have tried altering the way I pass the arguments into query
g.db.execute("INSERT INTO subs(sub_name, price, pay_period, pay_date, user_id) VALUES (?, ?, ?, ?, ?)", [subscription, price, period, pay_date, '1'])
I have tried entering as a tuple. tried individual arguments (this causes an error function only takes 2 arguments).
My SQL table schema
CREATE TABLE subs (id INTEGER PRIMARY KEY AUTOINCREMENT, sub_name TEXT, price FLOAT, pay_period TEXT, pay_date DATE, user_id INTEGER);
Maybe there is something wrong with my overall setup, the "/" get request works as expected so my database is connected.
Here is my full app code
import os
import sqlite3
from flask import Flask, render_template, g, request
from werkzeug.utils import redirect
app = Flask(__name__)
@app.before_request
def before_request():
g.db = sqlite3.connect('subzen.db')
g.db.row_factory = dict_factory
@app.route("/", methods=['GET'])
def index():
subs = []
for sub in g.db.execute('SELECT * FROM subs'):
subs.append(sub)
return render_template("index.html", subs=subs)
@app.route("/add", methods=['POST', 'GET'])
def add_sub():
if request.method == "POST":
subscription = request.form.get("subscription")
price = request.form.get("price")
period = request.form.get("period")
pay_date = request.form.get("pay_date")
g.db.execute("INSERT INTO subs(sub_name, price, pay_period, pay_date, user_id) VALUES (?, ?, ?, ?, ?)", [subscription, price, period, pay_date, '1'])
return redirect('/')
else:
return render_template('add.html')
@app.teardown_request
def teardown_request(exception):
if hasattr(g, 'db'):
g.db.close()
if __name__ == '__main__':
app.run()
def dict_factory(cursor, row):
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d