在Flask中删除数据库中的元素

时间:2014-07-17 02:40:37

标签: python web flask

我想确保我遵循此处的最佳做法。我有一个从数据库中提取的数据表,在最后一列中我有链接来编辑或删除该行。我觉得我总是被告知不要使用GET请求修改服务器上的数据。除了GET请求之外,我如何处理删除此数据行? 这是数据表的代码:

<table class="table table-hover notifications">
    <thead><tr><th>Search Parameter</th><th>Subreddits</th><th>Actions</th></thead>
    {% for notification in notifications %}
    <tr>
        <td>{{ notification.q }}</td>
        <td>{% for s in notification.subreddits %} {{ s.r }}<br>  {% endfor %}</td>
        <td><a href="{{ url_for('main.edit_notification', id=notification.id) }}">Edit</a> | <a href="">Delete</a></td>
    </tr>
    {% endfor %}
</table>

我想我不确定如何建立删除网址。我可以构建一个删除方法并传递我想要删除的元素的id(例如:/ delete / 1),但那是不是用GET请求修改数据呢?

1 个答案:

答案 0 :(得分:4)

您可以创建一个表单,在提交时发出POST请求,连接到在request.method为POST时删除对象的视图(如您所述,在URL中传递对象ID)。

我不是Flask专家,但以this code为例,您的观点应如下所示:

@app.route('/delete/<int:id>', methods=['POST'])
def remove(id):
    object = Object.query.get_or_404(id)
    delete(object)
    return redirect(url_for('index'))

你的表格如下:

<form method="post" action="{{ url_for('remove', id=object.id) }}">
  <button type="submit">Delete</button>
</form>

表单action属性强制表单将其信息提交给给定的URL /视图。