问题
When serving a request, GAE automatically inserts response header X-AppEngine-Country set to a value indicating the country from which the request was emitted. However, before GAE issues the response, I’d like to be able to use this value in a snippet of mine.
I wrote this code:
class TestPage(webapp2.RequestHandler):
def get(self):
country = self.response.headers["X-AppEngine-Country"]
self.response.out.write("<pre>country %s </pre>" % country)
But opening the page results in a crash:
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'
Is there any ways to use this value within the application?
回答1:
You're trying to get the headers of the response (which you're about to make), rather than the headers of the request. Try this instead.
country = self.request.headers.get('X-AppEngine-Country')
http://code.google.com/appengine/docs/python/tools/webapp/requestclass.html#Request_headers
The request headers, a dictionary-like object. Keys are case-insensitive.
来源:https://stackoverflow.com/questions/9500604/is-it-possible-to-use-x-appengine-country-within-an-application