Python:向数据库添加数据但在刷新之前无法显示在前面

时间:2017-04-29 14:58:01

标签: python google-app-engine google-cloud-datastore webapp2

这是我的代码:

template.py

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, *arg, **kwargs):
        self.response.out.write(*arg, **kwargs)

    def render_str(self, template, **params):
        t = jinja_env.get_template(template)
        return t.render(params)

    def render(self, template, **kwargs):
        self.write(self.render_str(template, **kwargs))


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(title, art, error)


app = webapp2.WSGIApplication([('/', MainPage)], debug=True)

front.html

<!DOCTYPE html>
<html>
<head>
    <title>/ascii/</title>
</head>
<body>
<h1>/ascii/</h1>

<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>
</html>

当我在“标题”,“艺术”中输入一些文字并按“提交”时,它应该发布我的大部分输入并返回数据库查询的结果。但是我必须刷新页面否则看不到我的内容交。

1 个答案:

答案 0 :(得分:0)

看起来好像同花顺有帮助,但实际上是时间的流逝,而“最终的一致性”赶上了。

详情见https://cloud.google.com/datastore/docs/concepts/structuring_for_strong_consistency