简体   繁体   English

使用SQLite3和Python / Flask插入值

[英]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'" 现在,我尝试插入一个元素,但是收到错误消息“ AttributeError:'_ AppCtxGlobals'对象没有属性'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 http://opentechschool.github.io/python-flask/extras/databases.html

The connection, g.db , needs to be added with each request. 每个请求都需要添加g.db连接。 You only create it in objects , so it doesn't exist for insert_value . 您只能在objects创建它,因此insert_value不存在insert_value g is an object which is created in the context of each request. g是在每个请求的上下文中创建的对象。

As the example code shows, you should create the connection before each request and add it to g . 如示例代码所示,您应该在每个请求之前创建连接并将其添加到g

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

Be sure to also close it in @app.teardown_request . 确保还要在@app.teardown_request其关闭。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM