Flask:Sqlite,浏览器(或代理)发送了此服务器无法理解的请求

时间:2017-03-02 13:38:44

标签: python sqlite web flask

我正在尝试制作更新方法,但我收到了此错误消息。

这是错误消息

Bad Request

The browser (or proxy) sent a request that this server could not understand.

控制台中没有任何内容。起初我认为查询有问题,所以我多次更改查询但结果是一样的。

这是views.py

@app.route('/edit_todo/<int:todo_id>', methods=['GET'])
def edit_todo(todo_id):
    flash('You are going to edit message')
    return render_template('edit_todo.html', 
                           todo=query_db('''select * from todo 
                           where todo_id = ?''', [todo_id]))


@app.route('/update_todo', methods=['POST'])
def update_todo():
    if request.form['todo_id', 'text', 'pub_date']:
        g.db.execute('''update todo set todo.text=?, todo.pub_date=?
                        where todo.todo_id = ?''', request.form['text'],
                                                   int(time.time(), 
                                                   request.form['todo_id']))
        g.db.commit()
        flash('Your message is updated')
     return redirect(url_for('index'))

这是模板

{% extends "layout.html" %}
{% block body %}
<div class="container">
<div class=twitbox>
    <h3>Edit message of {{ g.user.username }}?</h3>
  </div>
  <ul class=messages>
  {% for todo in todo %}
   <li>
   <form action="{{ url_for('update_todo') }}" method=post>
   <p><input type=text value="{{ todo.todo_id }}" name=todo_id readonly=true style="background-color:gray;">
   <input type=text value="{{ todo.text }}" name=text>
   <input type=submit value="Update">
   </form>
  {% else %}
   <li><em>None</em>
  {% endfor %}
  </ul>
</div>
{% endblock %}

1 个答案:

答案 0 :(得分:0)

request.form['todo_id', 'text', 'pub_date']正在request.form查找单键,它是三个字符串的元组。表单数据键入字符串,而不是元组,因此键不存在,Flask返回其标准400错误。

在这种情况下,if语句没有用处,你可以删除它。

如果要访问多个密钥,则需要单独访问它们。使用in或设置表示法来测试密钥是否存在。

if 'todo_id' in request.form and 'text' in request.form: