【问题标题】:Visits on a page not incrementing python google app engine页面上的访问量不会增加 python google app engine
【发布时间】:2015-08-07 12:04:24
【问题描述】:

我正在尝试使用此代码检查页面上的访问次数。 我的浏览器是 firefox v 39。 不知何故,计数没有增加。 谁能告诉我这里的问题是什么?

        import os
        import webapp2
        import jinja2
        import re
        from google.appengine.ext import db
        from functions import check_secure_val,make_secure_val

        temp_dir = os.path.join(os.path.dirname(__file__),'templates')
        jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(temp_dir), autoescape = True)

        class Handler(webapp2.RequestHandler):
            def write(self,*a,**az):
                self.response.write(*a,**az)
            def render_template(self,template,**params):
                t = jinja_env.get_template(template)
                return t.render(params)
            def render_page(self, template, **az):
                self.write(self.render_template(template,**az))

        class MainHandler(Handler):
                def get(self):
                        self.response.headers['Content-Type'] = 'text/plain'
                        visits = 0
                        visit_cookie_str = self.request.cookies.get('visits')
                        if visit_cookie_str:
                                cookie_val = check_secure_val(visit_cookie_str)
                                if cookie_val:
                                        visits = int(cookie_val)

                        visits += 1

                        new_cookie_val = make_secure_val(str(visits))

                        self.response.headers.add_header('Set-Cookie', 'visits=%s' % new_cookie_val)

                        if visits > 100:
                                self.write("You are the best ever!")
                        else:
                                self.write("You've been here %s times!" % visits)






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

【问题讨论】:

  • 您为什么要尝试通过添加标头来设置 cookie,而不是使用 available methods
  • 我是一个新手,正在努力适应 Web 开发。你有我可以看的例子吗?

标签: python google-app-engine cookies jinja2


【解决方案1】:

在你的代码中访问是一个局部变量。它不会跨请求重用。无论如何,这不是保持反击的最佳方式。 AppEngine 会将您的应用程序分片到多台机器上,并且会不时移动它。您需要使用数据存储、memcached 或其他一些持久存储方式来正确实现页面查看计数。另外请记住,您需要您的页面禁用浏览器缓存。

【讨论】:

  • 谢谢弗拉德,您对我如何以更好的方式使用计数器有什么建议吗?有代码示例吗?
猜你喜欢
  • 2011-04-25
  • 1970-01-01
  • 2011-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-15
相关资源
最近更新 更多