Adrián Vázquez Adrián Vázquez - 1 month ago 8
Python Question

Inserting a value with SQLite3 and Python/Flask

I am working in a small website where I want to show, insert, edit and delete elements from the database

I accomplished showing the data with this route:

@app.route('/objects')
def objects():
g.db = sqlite3.connect(db_location)
cur = g.db.execute('SELECT * FROM milkyway ORDER BY type')
objects = [dict(id=row[0], type=row[1], name=row[2], description=row[3], size=row[4], mass=row[5],distance=row[6], discoverer=row[7], image_url=row[8]) for row in cur.fetchall()]
g.db.close()
return render_template("objects.html",objects=objects)


And now I am trying to insert an element but I receive an error "AttributeError: '_AppCtxGlobals' object has no attribute 'db'"

@app.route('/insert_value',methods = ['POST', 'GET'])
def insert_value():
atype = request.form['type']
name = request.form['name']
description = request.form['description']
size = request.form['size']
mass = request.form['mass']
distance = request.form['distance']
discoverer = request.form['discoverer']
image_url = request.form['image_url']

g.db.execute('INSERT INTO milkyway (type,name,description,size,mass,distance,discoverer,image_ur) VALUES (?,?,?,?,?,?,?,?)', [atype], [name], [description], [size], [mass], [distance], [discoverer], [image_url] )

g.db.commit()
return redirect(url_for('objects'))


I search everywhere but the thing is, there are so many different ways to do this and I cannot make it works. I followed for instance this example; http://opentechschool.github.io/python-flask/extras/databases.html

xli xli
Answer

The connection, g.db, needs to be added with each request. You only create it in objects, so it doesn't exist for insert_value. g is an object which is created in the context of each request.

As the example code shows, you should create the connection before each request and add it to g.

@app.before_request
def before_request():
    g.db = sqlite3.connect(db_location)

Be sure to also close it in @app.teardown_request.

Comments