当服务请求时,gae会自动插入设置为指示发出请求的国家的值的响应头X-AppEngine-Country
。但是,在gae发出响应之前,我希望能够在我的代码片段中使用这个值。
我写了这段代码:
class TestPage(webapp2.RequestHandler):
def get(self):
country = self.response.headers["X-AppEngine-Country"]
self.response.out.write("<pre>country %s </pre>" % country)
但是打开页面会导致崩溃:
File "/base/python27_runtime/python27_lib/versions/third_party/webob-1.1.1/webob/headers.py", line 16, in __getitem__
raise KeyError(key)
KeyError: 'x-appengine-country'
有什么方法可以在应用程序中使用这个值吗?
最佳答案
您正在尝试获取响应的头(您将要创建响应),而不是请求的头试试这个。
country = self.request.headers.get('X-AppEngine-Country')
http://code.google.com/appengine/docs/python/tools/webapp/requestclass.html#Request_headers
请求头,一个类似字典的对象。密钥不区分大小写。