Flask-Sqlite从webform发布到DB

时间:2015-10-15 03:00:33

标签: python sqlite flask webforms

我刚刚开始学习Flask,并试图找到如何从webform发布到SQLite DB的答案。到目前为止,还没有设法使它工作,并有点失去这一点。我设法根据来自simplepython的代码示例从DB打印值,但不知道如何从webform添加新的值。

我需要能够解决元素,打开与数据库的连接,插入值,保存和关闭连接。据我所知,我应该将POST方法添加到app.py并使用request.form语句在按下提交按钮时拉出元素。

然后代码应该自动显示已经有效的索引html上的所有值。你可以帮我解决我需要添加到app.py文件的代码,以便将值添加到数据库以及在html文件中添加什么来形成动作webform-section?

的index.html

<!DOCTYPE html>
<html>
  <head>
    <title>Flask Intro</title>
<!--  <meta name="viewport" content="width=device-width, initial-scale=1.0">  -->
  </head>
  <body>

    <div class="container">


      <h3  potsit </h3>
     {% for post in posts %}
     Titleotsikko: {{post.title }} <br>
     Postotsikko: {{post.description}} 

     {% endfor %}

    </div>

<div>

<form action="/????????????NOT SURE WHERE  TO DIRECT" method="post">
    <div>
        <label for="title">title:</label>
        <input type="text" id="title" />
    </div>
    <div>
        <label for="description">description:</label>
        <input type="text" id="description" />
    </div>


    <div class="button">
        <button type="submit">Add to db</button>
    </div>
</form>
</div>


  </body>
</html>

app.py

from flask import Flask, render_template, request, session, g
import sqlite3


app = Flask(__name__)


@app.route('/')

def home():
      g.db = sqlite3.connect("sample.db")
      cur = g.db.execute('select * from posts')
      posts = [dict(title=row[0], description=row[1]) for row in cur.fetchall()]
      g.db.close()
      return render_template("index.html", posts=posts)



if __name__=='__main__':
 app.run(debug=True)

sql.py

import sqlite3

with sqlite3.connect("sample.db") as connection:
  c = connection.cursor()
  c.execute("DROP TABLE posts")  
  c.execute("CREATE TABLE posts(title TEXT, description TEXT)")
  c.execute('INSERT INTO posts VALUES("Luck", "no luck.")')

修改

我根据Paul Rooney的建议进行了一些更改,并创建了名为post.html的文件,从index.htmland移动了表单,在app.py文件中添加了另一个@route。我相信我并不遥远,但是自从周二试图解决这个问题之后我希望能够让它发挥作用。不幸的是现在我收到错误405'请求的URL不允许这种方法。我尝试了不同的选择后,我坚持不懈。

post.html

<!DOCTYPE html>
<html>
  <head>
    <title>Flask post</title>
<!--  <meta name="viewport" content="width=device-width, initial-scale=1.0">  -->
  </head>
  <body

<div>

<form action="/post" method="post">
    <div>
        <label for="title">title:</label>
        <input type="text" id="title" />
    </div>
    <div>
        <label for="description">description:</label>
        <input type="text" id="description" />
    </div>


    <div class="button">
        <button type="submit">Add to db</button>
    </div>
</form>
</div>


  </body>
</html>

(已编辑)app.py

from flask import Flask, render_template, request, session, g, redirect, url_for
import sqlite3


app = Flask(__name__)


@app.route('/')
def home():
     g.db = sqlite3.connect("sample.db")
     cur = g.db.execute('select * from posts')
     posts = [dict(title=row[0], description=row[1]) for row in cur.fetchall()]

     g.db.close()
     return render_template("index.html", posts=posts)


    @app.route('/post', methods=['POST'])
    def post():
        title=request.form['title']
        description=request.form['description']
        print title, description
        return redirect(url_for('/'))

    if __name__=='__main__':
      app.run(debug=True)

1 个答案:

答案 0 :(得分:0)

要回答您的原始问题,您应该选择一个端点来发布您的数据并在您的烧瓶应用和html表单操作中使用它。

我在评论中提出了post,但它可以是任何内容。我认为你已经掌握了这里要做的事情,但是为了完整性。

HTML

<form action="/post" method="post">

Python代码

添加路由以处理POSTed数据。

@app.route('/post', methods=['POST'])
def post():
    # Do db stuff then redirect back to index page.
    pass

编辑问题

您的代码中有缩进错误,导致405错误。您的post功能位于home功能中。让它更像这样

<强> app.py

from flask import Flask, render_template, request, session, g, redirect, url_for
import sqlite3

app = Flask(__name__)

@app.route('/')
def home():
     g.db = sqlite3.connect("sample.db")
     cur = g.db.execute('select * from posts')
     posts = [dict(title=row[0], description=row[1]) for row in cur.fetchall()]

     g.db.close()
     return render_template("index.html", posts=posts)

# One level of indentation removed from here downwards
@app.route('/post', methods=['POST'])
def post():
    title=request.form['title']
    description=request.form['description']
    return redirect(url_for('home'))

if __name__=='__main__':
  app.run(debug=True)

之后我看到400 Bad Request错误,这是因为您的html表单中没有name个参数。

尝试访问app.py中title dict中的descriptionform值会引发KeyError例外,因为如果没有html中的name参数。

如果你添加它们,例如

...
<input type="text" id="title" name='title'/>
...
<input type="text" id="description" name='description'/>
...

然后它会一直运行你的函数。

下一期将是

redirect(url_for('/'))

改为使用

redirect(url_for('home'))

home是为路径'/'调用的函数的名称。

之后你应该好好去。