0

I'm trying to learn to add backend to a simple web app using postgreSQL and Python DB-API.

When running the app, why do I get an error if the function get_posts() in forumdb. python uses c. execute ("SELECT * FROM posts ORDER BY time;) instead of SELECT content, time FROM posts ORDER BY time;)?

Secondly, can anyone explain why c.execute("INSERT INTO posts VALUES (content)") doesn't work and we have to use the ('%s') % content thing in the function add_post(content) in forumdb.py?

Below is forum.py

from flask import Flask, request, redirect, url_for

# Using a module called forumdb
from forumdb import get_posts, add_post

app = Flask(__name__)

# HTML template for the forum page
HTML_WRAP = '''\
<!DOCTYPE html>
<html>
  <head>
    <title>DB Forum</title>
    <style>
      h1, form { text-align: center; }
      textarea { width: 400px; height: 100px; }
      div.post { border: 1px solid #999;
                 padding: 10px 10px;
                 margin: 10px 20%%; }
      hr.postbound { width: 50%%; }
      em.date { color: #999 }
    </style>
  </head>
  <body>
    <h1>DB Forum</h1>
    <form method=post>
      <div><textarea id="content" name="content"></textarea></div>
      <div><button id="go" type="submit">Post message</button></div>
    </form>
    <!-- post content will go here -->
%s
  </body>
</html>
'''

# HTML template for an individual comment
POST = '''\
    <div class=post><em class=date>%s</em><br>%s</div>
'''


@app.route('/', methods=['GET'])
def main():
  '''Main page of the forum.'''
  posts = "".join(POST % (date, text) for text, date in get_posts())
  html = HTML_WRAP % posts
  return html


@app.route('/', methods=['POST'])
def post():
  '''New post submission.'''
  message = request.form['content']
  add_post(message)
  return redirect(url_for('main'))


if __name__ == '__main__':
  app.run(host='0.0.0.0', port=8000)

Below is forumdb.py

# "Database code" for the DB Forum.

import psycopg2
import datetime


def get_posts():
    con = psycopg2.connect(dbname="forum")
    c = con.cursor()
    """Return all posts from the 'database', most recent first."""
    c.execute("SELECT content, time FROM posts ORDER BY time;")
    return c.fetchall()
    con.close()


def add_post(content):
    con = psycopg2.connect(dbname="forum")
    c = con.cursor()
    """Add a post to the 'database' with the current timestamp."""
    c.execute("INSERT INTO posts VALUES ('%s')" % content)
    con.commit()
    con.close()

Thank you!

1
  • VALUS should be VALUES in the insert statement Commented Nov 4, 2017 at 6:57

1 Answer 1

0

Because you are using  parameterized query is a query in which placeholders are used for parameters and the parameter values are supplied at execution time.

When we want to use a variable inside a SQL query you need to use a placeholder for it.

Example

query = """Update table set column_a = %s where column_b = %s"""
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.