0

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

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

5 Comments

I have another error, TypeError: function takes at most 2 arguments (9 given). I think its because I did not add the first one the ID. The id is autoincrement, how can leave it blank in order to do it automaticly?
In g.db.execute, [atype, name, description,...] not [atype], [name].... Pass in a list of statement parameters, not each parameter as an argument in its own list.
You are awesome! last question, any good resources for these? books, tutorials or examples?
This is a good Flask tutorial. See this explanation of flask g. This explains how to use the DB API.
Thank very much :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.