在我的代码中我正在使用
user_id = self.request.cookies.get( 'user_id', '' )
if user_id != '':
me = User.get_by_id( int( user_id ) )
但是对我来说这看起来并不正确,即使它在技术上有效......它看起来不精确。有没有更好的方法可以检查cookie的存在?
答案 0 :(得分:2)
我从不使用AppEngine,但我猜request.cookies
只是一个普通的字典对象,例如在Django中。您可以尝试以下方法:
if 'user_id' in self.request.cookies:
# cookie exists
答案 1 :(得分:1)
Try and Except子句对于这样的情况非常方便,你需要一个明确而明显的工作流程,并且头发触发器使所有内容无效捕获所有内容。
需要明确的是,这并未涉及通过在客户端上保留数据来安全地跟踪/管理用户会话所涉及的各种细微差别。
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)