0

我使用修改后的 webapp.RequestHandler 来处理我的应用程序中的请求:

class MyRequestHandler(webapp.RequestHandler):
    """
    Request handler with some facilities like user.
    self.out is the dictionary to pass to templates 
    """
    def __init__(self, *args, **kwargs):
        super(MyRequestHandler, self).__init__(*args, **kwargs)
        self.out = {
            'user': users.get_current_user(),
            'logout_url': users.create_logout_url(self.request.uri)
            }

    def render(self, template_name):
        """
        Shortcut to render templates
        """
        self.response.out.write(template.render(template_name, self.out))


class DeviceList(MyRequestHandler):
    def get(self):
        self.out['devices'] = GPSDevice.all().fetch(1000)
        self.render('templates/device_list.html')

但我得到一个例外:

line 28, in __init__
    self.out['logout_url'] = users.create_logout_url(self.request.uri)
AttributeError: 'DeviceList' object has no attribute 'request'

当导致异常的代码被移出__init__一切正常时:

class MyRequestHandler(webapp.RequestHandler):
    """
    Request handler with some facilities like user.
    self.out is the dictionary to pass to templates and initially it contains user object for example
    """
    def __init__(self, *args, **kwargs):
        super(MyRequestHandler, self).__init__(*args, **kwargs)
        self.out = { 'user': users.get_current_user(), }

    def render(self, template_name):
        """
        Shortcut to render templates
        """
        self.out['logout_url'] = users.create_logout_url(self.request.uri)
        self.response.out.write(template.render(template_name, self.out))

那是什么?为什么执行self.request父母(即webapp.RequestHandler)之后没有__init__

4

1 回答 1

6

http://code.google.com/appengine/docs/python/tools/webapp/requesthandlerclass.html#RequestHandler_initialize

initialize(request, response) 使用 Request 和 Response 对象初始化处理程序实例。通常,WSGIApplication 在实例化处理程序类之后执行此操作。

如果您期望请求对象已经被填充,看起来您想要覆盖初始化而不是初始化。

于 2010-06-02T19:21:37.340 回答