变量访问,获取和发布

时间:2011-07-10 10:09:25

标签: python google-app-engine variables

如何获取这些变量。 这可能很容易,但我今天想不到。

class Contact(webapp.RequestHandler):
    def get(self):

        self.a = random.randint(1,4)
        self.b = random.randint(0,4)

        template_values = {
            'a': self.a,
            'b': self.b
        }

        path = os.path.join(os.path.dirname(__file__), 'contact.html')
        self.response.out.write(template.render(path, template_values))

    def post(self):
        self.response.out.write(self.a)
        self.response.out.write(self.b)

引用:

Traceback (most recent call last):
  File "C:\Program Files\Google\google_appengine\google\appengine\ext\webapp\__init__.py", line 702, in __call__
    handler.post(*groups)
  File "D:\My Dropbox\project\main.py", line 133, in post
    self.response.out.write(self.a)
AttributeError: 'Contact' object has no attribute 'a'

1 个答案:

答案 0 :(得分:4)

每个请求都会创建一个新的处理程序实例。例如,您可以将此构造函数添加到处理程序:

class AppHandler(webapp.RequestHandler):
    def __init__(self, *args, **kwargs):
        logging.debug('handler "%s" created' % self)
        super(AppHandler, self).__init__(*args, **kwargs)
    <...>

并提出两个请求,然后在您的日志中,您可以看到类似的内容:

DEBUG    2011-07-10 13:36:17,009 app.py:19] handler "<__main__.AppHandler object at 0x98dad8c>" created
<...>
DEBUG    2011-07-10 13:36:52,563 app.py:19] handler "<__main__.AppHandler object at 0x98de14c>" created

如果您想在请求之间获取一些数据,可以尝试使用某种会话实现。例如:https://github.com/dound/gae-sessions