是否可以在应用程序中使用X-AppEngine-Country

qdi*_*dii 3 python google-app-engine geolocation

在提供请求时,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)
Run Code Online (Sandbox Code Playgroud)

但打开页面会导致崩溃:

  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'
Run Code Online (Sandbox Code Playgroud)

有没有办法在应用程序中使用此值?

小智 13

您正在尝试获取响应的标头(您将要创建的标头),而不是请求的标头.试试这个.

country = self.request.headers.get('X-AppEngine-Country')
Run Code Online (Sandbox Code Playgroud)

http://code.google.com/appengine/docs/python/tools/webapp/requestclass.html#Request_headers

请求标头,类似字典的对象.密钥不区分大小写.