我刚刚完成了关于阻止论坛数据库中的垃圾邮件的部分,现在是清理它们的时候了。
目标是使用update
语句更新数据库记录并删除标记为垃圾邮件的帖子。在挠头并从在线讲师(这是针对在线课程)那里收到模糊的提示和指示后,我遇到了一个错误。
这可能不是正确的方法,我在谷歌上没有运气后正在寻找指导。这是一个片段forumdb.py
:
# "Database code" for the DB Forum.
import bleach
import psycopg2
import datetime
DBNAME = "forum"
def get_posts():
"""Return all posts from the 'database', most recent first."""
db = psycopg2.connect(database=DBNAME)
c = db.cursor()
UPDATE posts
SET content = 'cheese'
WHERE content like 'spam' ;
c.execute("select content, time from posts order by time desc")
return c.fetchall()
db.close()
def add_post(content):
"""Add a post to the 'database' with the current timestamp."""
db = psycopg2.connect(database=DBNAME)
c = db.cursor()
clean_cont = bleach.clean(content)
c.execute("insert into posts values (%s)", (clean_cont,))
db.commit()
db.close()
这是我得到的错误:
Traceback (most recent call last):
File "forum.py", line 7, in <module>
from forumdb import get_posts, add_post
File "/vagrant/forum/forumdb.py", line 13
UPDATE posts
^
SyntaxError: invalid syntax
如果有帮助,这里是 forum.py:
#!/usr/bin/env python3
#
# A buggy web service in need of a database.
from flask import Flask, request, redirect, url_for
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)
提前感谢任何有能力提供帮助的人!