Flask插入数据库而不重复

时间:2014-05-05 21:55:12

标签: python html sqlite flask

我正在使用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>

1 个答案:

答案 0 :(得分:0)

不是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 clientLogin = Kalle

id = 2 clientLogin = Duck

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

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

最后一件事可以用你想要发生的任何东西替代。

相关问题