This function update's the user's database entry if there is one. If the user has no database entry, we create one here.
# - - - u p d a t e D a t a b a s e
def updateDatabase ( inputs, db ):
'''Generate a cookie if necessary; update the database.
[ (inputs is an Inputs instance) and
(db is a UserDatabase instance) ->
if (inputs.userId is None) or (inputs.userId is not in db) ->
db := db with a new UserRecord whose userId is a random
string, whose chapterNo is 1, and whose
expiration time is as specified by inputs
return that new UserRecord
else ->
db := db with the UserRecord for inputs.userId updated
as specified by inputs
return that updated UserRecord ]
'''
First we see if the database has a UserRecord for this user. If not, we create a
new one; see Section 7.13, “newUserRecord(): Create the initial
user record”.
#-- 1 --
# [ if db has an entry for inputs.userId ->
# userRecord := the corresponding value
# else ->
# userRecord := a new UserRecord with a randomy
# userId, chapterNo=1, persist=0, and expiration=0 ]
try:
userRecord = db[inputs.userId]
except KeyError:
userRecord = newUserRecord()
Adjust the chapter number up or down if this is a repeat
visit, but no lower than 1 and no higher than the value
specified in Section 7.6.16, “CHAPTER_COUNT”. If this
is the user's first visit, neither inputs.next nor inputs.prev will
be set.
#-- 2 --
if inputs.next:
userRecord.chapterNo = min ( userRecord.chapterNo + 1,
CHAPTER_COUNT )
elif inputs.prev:
userRecord.chapterNo = max ( userRecord.chapterNo - 1,
1 )
Next we adjust the expiration time. See Section 7.6.14, “PERSIST_SECONDS” and Section 7.6.15, “SESSION_SECONDS”.
#-- 3 --
# [ now := current epoch time as an integer in seconds ]
now = int ( time.time() )
#-- 4 --
if inputs.persist:
userRecord.persist = 1
userRecord.expiration = now + PERSIST_SECONDS
else:
userRecord.persist = 0
userRecord.expiration = now + SESSION_SECONDS
Place or replace the user's record in the database.
#-- 5 --
db[userRecord.userId] = userRecord
#-- 6 --
return userRecord