In my code I'm using
user_id = self.request.cookies.get( 'user_id', '' )
if user_id != '':
me = User.get_by_id( int( user_id ) )
but to me this doesn't look right even though it technically works...it looks imprecise. Is there a better way I can check for the existence of a cookie?
I've never use AppEngine but I guess request.cookies
is just a normal dictionary object like for example in Django. You can try the following:
if 'user_id' in self.request.cookies:
# cookie exists
Try and Except clauses are very handy for situations like this where you need a clear and obvious workflow with a hair trigger invalidate everything catch all.
To be clear, this does not approach the various nuances involved in securely tracking/managing a user session by leaving data on the client.
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.