我使用修改后的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))
那是什么意思?为什么父母(即webapp.RequestHandler's)self.request
被执行后没有__init__
?
答案 0 :(得分:6)
初始化(请求,响应) 使用初始化处理程序实例 请求和响应对象。 通常,WSGIApplication会这样做 在实例化处理程序之后 类。
如果您希望已经填充了请求对象,则看起来要覆盖initialize而不是init。