Предложения 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)