Flask - Sqlite Unable to send data to DB from webform

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • vento
    New Member
    • Oct 2015
    • 1

    #1

    Flask - Sqlite Unable to send data to DB from webform

    I have struggled to get this code to work for some days now. This should be just simple web form where text is added to 2 fields and posted to the Sqlite-database.

    I am able to display data from db to index.html but accessing below address results to 405 error -'The method is not allowed for the requested URL' when I try to access
    http://localhost:5000/post. What is wrong with app.py file likely relating to @app.route('/post', methods=['POST']) and its method?

    app.py
    Code:
    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']
        return redirect(url_for('/post'))
    
    if __name__=='__main__':
      app.run(debug=True)
    post.html
    Code:
    <!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>
    sql.py
    Code:
    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("this is title", "this is description.")')
  • dwblas
    Recognized Expert Contributor
    • May 2008
    • 626

    #2
    Try something like this to verify that the select is working
    Code:
        c.execute('select * from posts')
        recs_list=c.fetchall()
        for row in recs_list:
            ## print it to verify that the select is correct
            print row
    as I think the insert statement is the problem and should be
    Code:
    c.execute('INSERT INTO posts values (?,?)', ("this is title", "this is description.")')

    Comment

    Working...