【发布时间】:2013-07-14 10:04:33
【问题描述】:
我正在开发一个应用程序来了解 python 和 Google App Engine。我想从 cookie 中获取值并在模板上打印以隐藏或显示一些内容。
有可能吗?
什么样的会话系统最适合谷歌应用引擎?
在 gae 和模板上使用会话的最佳方式是什么?
如何使用模板验证 cookie 的值?
【问题讨论】:
标签: python google-app-engine cookies
我正在开发一个应用程序来了解 python 和 Google App Engine。我想从 cookie 中获取值并在模板上打印以隐藏或显示一些内容。
有可能吗?
什么样的会话系统最适合谷歌应用引擎?
在 gae 和模板上使用会话的最佳方式是什么?
如何使用模板验证 cookie 的值?
【问题讨论】:
标签: python google-app-engine cookies
请记住,Google App Engine 是一个平台,而不是一个框架, 所以你的问题是 webapp2 (GAE 中使用的默认框架) 有一个很好的界面来处理cookies。即使框架没有 有这个接口,只要你能访问到 Cookie 头 您可以访问 cookie 的请求。
这里有两个示例,一个使用 webapp2 cookies 接口,另一个使用 其他只使用 Cookie 标头。
webapp2:
class MyHandler(webapp2.RequestHandler):
def get(self):
show_alert = self.request.cookies.get("show_alert")
...
Cookie 标头(使用 webapp2):
# cookies version 1 is not covered
def get_cookies(request):
cookies = {}
raw_cookies = request.headers.get("Cookie")
if raw_cookies:
for cookie in raw_cookies.split(";"):
name, value = cookie.split("=")
for name, value in cookie.split("="):
cookies[name] = value
return cookies
class MyHandler(webapp2.RequestHandler):
def get(self):
cookies = get_cookies(self.request)
show_alert = cookies.get("show_alert")
...
会话也是如此,尽管制作自己的会话库 比较难,反正webapp2有你覆盖:
from webapp2_extras import sessions
class MyBaseHandler(webapp2.RequestHandler):
def dispatch(self):
# get a session store for this request
self.session_store = sessions.get_store(request=self.request)
try:
# dispatch the request
webapp2.RequestHandler.dispatch(self)
finally:
# save all sessions
self.session_store.save_sessions(self.response)
@webapp2.cached_property
def session(self):
# returns a session using the backend more suitable for your app
backend = "securecookie" # default
backend = "datastore" # use app engine's datastore
backend = "memcache" # use app engine's memcache
return self.session_store.get_session(backend=backend)
class MyHandler(MyBaseHandler):
def get(self):
self.session["foo"] = "bar"
foo = self.session.get("foo")
...
有关会话和 cookie 的更多信息,请参阅 webapp documentation。
关于您关于模板的问题,您应该再次查看您使用的模板引擎的文档并查找您需要了解的内容。
【讨论】: