繁体   English   中英

无需复制即可将烧瓶插入数据库

[英]Flask insert into database without duplicating

我正在使用Flaskr示例,并希望显示没有重复的数据库内容,所以我将show_entries.html修改为:

 {% extends "layout.html" %}
 {% block body %}
   {% if session.logged_in %}
     <form action="{{ url_for('add-entry') }}" method=post class=add-entry>
       <dl>
        <dt>Available:
        <dd><input type=text size=25 name=attribute1>
        <dt>Used:
        <dd><input type=text size=25 name=attribute2>
        <dd><input type=submit value=Update>
       </dl>
     </form>
   {% endif %}
     <table border="1" style="width:300px">
       <ul class=myDB>
       <tr>
         <th>Available</th>
         <td>{% for entry in myDB %} {{ entry.attribute1 }} {% endfor %}</td>
       </tr>
       <tr>
         <th>Used</th>
         <td>{% for entry in myDB %} {{ entry.attribute2 }} {% endfor %}</td>                  
       </tr>
       </ul>            
     </table>
 {% endblock %}

myDB.py看起来像:

.
.
.
@app.route('/')
def showEntries():
    db = get_db()
    cur = db.execute('select distinct attribute1, attribute2 from myDB order by id desc')
    myDB = cur.fetchall()
    return render_template('show_entries.html', myDB=myDB)

@app.route('/add', methods=['POST'])
def add-entry():
    if not session.get('logged_in'):
        abort(401)
    db = get_db()
    db.execute('insert or replace into myDB (attribute1, attribute2) values (?, ?)',
             [request.form['attribute1'], request.form['attribute2']])                   
    db.commit()
    flash('Database Updated')
    return redirect(url_for('showEntries'))
.
.
.

我的问题是,每当我更新数据库并刷新Web服务器时,我仍然看到重复项:因此,有什么方法可以显示没有重复项的attribute1,attribute2的更新值:即除了在这里使用for循环并调用myDB的所有条目之外:

<td>{% for entry in myDB %} {{ entry.attribute1 }} {% endfor %}</td>

<td>{% for entry in myDB %} {{ entry.attribute2 }} {% endfor %}</td>

因为行不通

<td> {{ myDB.attribute1 }} </td>

<td> {{ myDB.attribute2 }} </td>

不能100%确定这是您要的内容,但是无论如何,这是我的答案。

创建数据库时,可以选择是否要允许重复的变量/插入。

例如:

"create table registratedClients (id INTEGER PRIMARY KEY, clientLogin TEXT unique)"

该代码仅允许插入唯一的clientLogin。 如果我使用此代码:

"insert into registratedClients values (null," + "\'" + "Kalle" + "\')"
"insert into registratedClients values (null," + "\'" + "Duck" + "\')"
"insert into registratedClients values (null," + "\'" + "Kalle" + "\')"

我的数据库仅包含:

id = 1个客户端登录= Kalle

id = 2 clientLogin =鸭子

编辑:对于多列中的唯一列,请在创建表时执行此操作:

 "create table registratedClients (id INTEGER PRIMARY KEY, clientLogin TEXT, chatName TEXT, UNIQUE(clientLogin, chatName) ON CONFLICT REPLACE)"

最后一件事是可以替换为任何您想发生的事情。

暂无
暂无

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

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