繁体   English   中英

使用python / GAE对cookie进行存在性检查的最佳方法是什么?

[英]What's the best way to do an existence check on a cookie with python/GAE?

在我的代码中,我正在使用

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和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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM