在我的代码我使用使用python/GAE对cookie进行存在检查的最佳方式是什么?
user_id = self.request.cookies.get('user_id', '')
if user_id != '':
me = User.get_by_id(int(user_id))
,但对我来说这看起来不正确,即使它在技术上的作品...它看起来不精确。有没有更好的方法可以检查cookie的存在?
在我的代码我使用使用python/GAE对cookie进行存在检查的最佳方式是什么?
user_id = self.request.cookies.get('user_id', '')
if user_id != '':
me = User.get_by_id(int(user_id))
,但对我来说这看起来不正确,即使它在技术上的作品...它看起来不精确。有没有更好的方法可以检查cookie的存在?
我从来没有使用AppEngine上,但我想request.cookies
就像例如在Django只是一个普通的字典对象。你可以尝试以下方法:
if 'user_id' in self.request.cookies:
# cookie exists
尝试和除条款是这样的情况下非常有用,你需要一个明确的和明显的工作流与一触即发所有一切无效捕捞。
需要明确的是,这并没有办法参与安全跟踪/留下客户端上的数据,管理用户会话的各种细微差别。
try:
user_id = self.request.cookies['user_id'] #will raise a 'KeyError' exception if not set.
if isinstance(user_id, basestring):
assert user_id # will raise a 'ValueError' exception if user_id == ''.
try:
user_id = int(user_id)
except ValueError:
logging.warn(u'user_id value in cookie was of type %s and could not be '
u'coerced to an integer. Value: %s' % (type(user_id), user_id))
if not isinstance(user_id, int):
raise AssertionError(u'user_id value in cookie was INVALID! '
u'TYPE:VALUE %s:%s' % (type(user_id), user_id))
except KeyError:
# 'user_id' key did not exist in cookie object.
logging.debug('No \'user_id\' value in cookie.')
except AssertionError:
# The cookie value was invalid!
clear_the_cookie_and_start_again_probably()
except Exception, e:
#something else went wrong!
logging.error(u'An exception you didn\'t count on. Exception: %s' % e)
clear_the_cookie_and_start_again_probably()
raise e
else:
me = User.get_by_id(user_id)
“需要明确的是,这并没有办法参与安全跟踪/留下客户端上的数据,管理用户会话的各种细微差别。”我怎么可以研究这一点,以便我能理解这些细微差别? – zakdances
结帐此页的“客户端Web会议”部分:http://en.wikipedia.org/wiki/Session_(computer_science)。 –
应用服务引擎,你可以看一下GAE的会话,根据该网站,这是” ......一个会话库在谷歌App Engine的Python运行时对所有的会话大小。这是非常快,重量轻(一个文件),使用方便。”。我自己使用它,并没有任何问题。 –