每次我点击提交时都会尝试在post方法中重定向(这会为数据库添加更多“艺术”),但我必须在之后刷新以显示新条目。我已经包含了我的main.py代码和下面的html。我该如何解决这个问题,所以我不必在每次提交后手动刷新。 (这来自udacity Web开发课程。)
import os
import webapp2
import jinja2
from google.appengine.ext import db
template_dir = os.path.join(os.path.dirname(__file__), 'templates')
jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir),
autoescape = True)
class Handler(webapp2.RequestHandler):
def write(self, *a, **kw):
self.response.out.write(*a, **kw)
def render_str(self, template, **params):
t = jinja_env.get_template(template)
return t.render(params)
def render(self, template, **kw):
self.write(self.render_str(template, **kw))
class Art(db.Model):
title = db.StringProperty(required = True)
art = db.TextProperty(required = True)
created = db.DateTimeProperty(auto_now_add = True)
class MainPage(Handler):
def render_front(self, title="", art="", error=""):
arts = db.GqlQuery("select * from Art order by created desc")
self.render("front.html", title = title, art = art, error = error, arts = arts)
def get(self):
self.render_front()
def post(self):
title = self.request.get("title")
art = self.request.get("art")
if title and art:
a = Art(title=title, art=art)
a.put()
self.redirect("/")
else:
error = "we need both a title and some artwork!"
self.render_front(error=error, title=title,art=art)
app = webapp2.WSGIApplication([
('/', MainPage),
], debug=True)
HTML:
<form method="post">
<label>
<div>title</div>
<input type="text" name="title" value="{{title}}">
</label>
<label>
<div>art</div>
<textarea name="art">{{art}}</textarea>
<label>
<div class="error">{{error}}</div>
<input type="submit">
</form>
<hr>
{% for art in arts %}
<div class="art">
<div class="art-title">{{art.title}}</div>
<pre class="art-body">{{art.art}}</pre>
</div>
{% endfor %}
</body>
答案 0 :(得分:2)
您的重定向工作正常。新实体未显示的原因是eventual consistency与GAE数据存储区相同。当你放置一个实体时,它可能需要一些时间才能被查询。
有解决方法,但它们取决于特定的应用程序。例如,您可以存储密钥列表,因为按键获取将始终有效,或者您可以使用memcache。