一名 Google App Engine (GAE) 的新手希望在用户提交评论之前检查是否存在新评论,并使用一个弹出框提示用户“评论框中有一个新评论,您是否要继续?是或否?”。
2、解决方案
- 在 Shout 模型中添加一个 last_comment_time 属性,用于存储最新的评论时间。
- 在 MainPage 类的 get 方法中,获取最新的评论时间并将其存储在 last_comment_time 变量中。
- 在 MainPage 类的 post 方法中,检查提交的评论时间是否晚于 last_comment_time,如果是,则弹出提示框。
代码示例
import webapp2
import datetime
import time
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.webapp \
import template
class Shout(db.Model):
message = db.StringProperty(required=True)
when = db.DateTimeProperty(auto_now_add=True)
who = db.StringProperty()
last_comment_time = db.DateTimeProperty()
class MainPage(webapp2.RequestHandler):
def get(self):
shouts = db.GqlQuery('SELECT * FROM Shout ORDER BY when ASC')
last_comment_time = shouts.get().last_comment_time
values = {
'shouts': shouts,
'last_comment_time': last_comment_time
}
self.response.out.write(template.render('main.html', values))
def post(self):
shout = Shout (
message = self.request.get('message'),
who = self.request.get('who'))
shout.put()
last_comment_time = shout.when
self.redirect('/')
application = webapp2.WSGIApplication([
('/', MainPage),
], debug=True)
main.html
<!DOCTYPE html>
<html>
<head>
<title>Comment System</title>
<link rel="stylesheet" href="./css/main.css" media="screen" />
</head>
<body>
<h1>Cloud Comment System</h1>
{% for shout in shouts %}
<div>
<div id="fl">
{{shout.when}}
from
{% ifequal shout.who "" %}
Anonymous
{% else %}
{{shout.who}}
{% endifequal %}
</div>
{{shout.message}}
</div>
{% endfor %}
<form action="" method="post" accept-charset="utf-8">
<p>From:<input type="text" name="who" value="" id="who"></p>
<p>Message:<input type="text" name="message" value="" id="message"></p>
<p><input type="submit" name="" value="comment"></p>
</form>
<script>
var last_comment_time = "{{last_comment_time}}";
var current_comment_time = new Date();
if (current_comment_time > last_comment_time) {
alert("The comment box has a new comment, do you want continue?! Yes or No?");
}
</script>
</body>
</html>
在以上代码中,我们在 Shout 模型中添加了 last_comment_time 属性,并在 MainPage 类的 get 方法中获取最新的评论时间并将其存储在 last_comment_time 变量中。在 MainPage 类的 post 方法中,我们检查提交的评论时间是否晚于 last_comment_time,如果是,则弹出提示框。我们在 main.html 中添加了一个 JavaScript 脚本,用于比较当前评论时间和最新的评论时间,如果当前评论时间晚于最新的评论时间,则弹出提示框。这样,我们就实现了在用户提交评论之前检查是否存在新评论并弹出提示框的功能。