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

什么';使用python/GAE对cookie进行存在性检查的最佳方法是什么?,python,google-app-engine,cookies,Python,Google App Engine,Cookies,在我的代码中,我正在使用 user_id = self.request.cookies.get( 'user_id', '' ) if user_id != '': me = User.get_by_id( int( user_id ) ) 但对我来说,这看起来并不正确,即使它在技术上可行……它看起来不精确。有没有更好的方法来检查cookie的存在?我从来没有使用过AppEngine,但我猜是请求。cookie只是一个普通的字典对象,例如在Django中。您可以尝试以下操作:

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

user_id = self.request.cookies.get( 'user_id', '' )

if user_id != '':
        me = User.get_by_id( int( user_id ) )

但对我来说,这看起来并不正确,即使它在技术上可行……它看起来不精确。有没有更好的方法来检查cookie的存在?

我从来没有使用过AppEngine,但我猜是
请求。cookie
只是一个普通的字典对象,例如在Django中。您可以尝试以下操作:

if 'user_id' in self.request.cookies:
    # cookie exists

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)

“需要明确的是,这并不能通过将数据留在客户端来处理安全跟踪/管理用户会话所涉及的各种细微差别。”我如何进一步研究这一点,以便了解这些细微差别?请查看本页的“客户端web会话”部分:。对于AppEngine,您可以查看gae会话,根据网站,它是“…一个用于所有会话大小的Google App Engine上Python运行时的会话库。它非常快速、轻量级(一个文件),并且易于使用。”。我自己用,一点问题都没有。