Flask 405方法错误

时间:2014-01-30 17:05:38

标签: python html sqlite flask

您好我正在尝试向我的sqlite数据库添加联系人,尽管我一直收到405方法错误。任何想法??

我的方法:

@app.route('/addcontact/', methods=['POST'])
    def contact_add():
        if request.method == 'POST':
            g.db.execute('insert into address (surname, firstname, email, mobile),values (?, ?, ?, ?)',
                     [request.form['firstname'], request.form['surname'], request.form['email']
                    , request.form['mobile']])
            g.db.commit()
            flash('New entry was successfully posted')
            return redirect(url_for('contacts')) #redirect to the contacts page

我的HTML:

<html>
  <body>
      <h1>Add new contact</h1>
      <form action='/addcontact/' method="post">
        <dl>
          <dt>First Name:
          <dd><input type="text" size=30 name="firstname">
          <dt>Surname:
          <dd><input type="text" size=30 name="surname">
          <dt>Email:
          <dd><input type="text" size=30 name="email">
          <dt>Mobile:
          <dd><input type="text" size=30 name="mobile">            
          <dd><input type="submit" value="Add New Contact">
        </dl>
      </form>
      <a href="/">Home</a>
      <a href="/contact">List of contacts</a>
  </body>
</html>

2 个答案:

答案 0 :(得分:1)

你错过了GET方法。

您需要在视图中添加GET和POST方法。原因是,最初,它将是显示表单的GET方法。然后在输入项目后,点击提交然后使用POST。所以我将编辑你的代码:

@app.route('/addcontact/', methods=['GET','POST'])
def contact_add():
    if request.method == 'POST':
        g.db.execute('insert into address (surname, firstname, email, mobile),values (?, ?, ?, ?)',
                 [request.form['firstname'], request.form['surname'], request.form['email']
                , request.form['mobile']])
        g.db.commit()
        flash('New entry was successfully posted')
        return redirect(url_for('contacts')) #redirect to the contacts page

    # If not POST, then you should render the initial form below (GET will be used)
    return render_template('form.html')

答案 1 :(得分:-1)

猜测:

request.method != 'POST'

所以

print request.method