在Python/GAE中如何检查cookie是否存在?

1 投票
2 回答
3852 浏览
提问于 2025-04-17 01:22

在我的代码中,我使用了

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

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

但是我觉得这样写不太对,虽然从技术上来说是可以工作的……看起来不太准确。有没有更好的方法可以检查一个cookie是否存在呢?

2 个回答

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

我从来没有使用过AppEngine,但我猜request.cookies就像Django中的普通字典对象一样。你可以试试下面的代码:

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

撰写回答