我正在尝试学习使用 postgreSQL 和 Python DB-API 将后端添加到一个简单的 Web 应用程序。
运行app时, forumdb.get_posts ()函数为什么会报错?python 使用c. execute ("SELECT * FROM posts ORDER BY time;)
而不是SELECT content, time FROM posts ORDER BY time;)
?
其次,任何人都可以解释为什么c.execute("INSERT INTO posts VALUES (content)")
不起作用,我们必须使用forumdb.py('%s') % content
中函数add_post(content)中的东西吗?
下面是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)
下面是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()
谢谢!