> If you just need to store data for a single user across requests, you can 
> store it in the session (each user has a separate session). But if you need 
> to store data from multiple users and then process it all together, you can 
> store it in the cache: http://web2py.com/books/default/chapter/29/4#cache.
>
> Anthony
>

Thanks Anthony. The data come from multiple users in my case.

After looking at the caching mechanism provided by web2py, I have a rough 
design in pseudo-code as below.

in controller:

user_data = cache.ram('user_data', lambda:dict(), time_expire=None)

# add the data from this user, this should also update the cached dict?
user_data[this_user_id] = submitted_data

if len(user_data) == some_pre_defined_number:
    # get data out of the dictionary 'user_data' by user Ids
    ...
    # process them and persist results to DB
    ...
    # reset 'user_data' dict by removing it from cache
    cache.ram('user_data', None)

The above implies that the 'if' check is made upon every request by 
individual users, which is somewhat inefficient, but I am not sure if there 
is other better way(s) to implement this logic within web2py. If so, please 
enlighten me!

In addition, I have some specific questions regarding the cache mechanism 
in web2py:
1. when exactly does an object expire in cache? My understanding is that, 
as long as the 'time_expire' value of *the current request* is greater than 
the gap between *the time of current request* and *the time at which the 
requested object was last updated in cache*, then the object behaves as if 
it never expires in cache. This is illustrated by an example in the book, 
if I understand it correctly. Therefore, the only perceivable way (to me) 
for an object to expire is to supply a 'time_expire' value in a request 
that is smaller than the gap between the time of this request and the time 
when the requested object was updated in cache. In other words, if I do:

something = cache.ram('something', lambda:'blah blah', time_expire=1)

effectively, 'something' never expires in cache until I call something like 
the following after t seconds (with t > make_it_expire):

something = cache.ram('something', lambda:'blah blah', 
time_expire=make_it_expire
)

2. An follow-up question is that, when an objects eventually expires in 
cache, does it mean it is completely removed from the cache? i.e. 
equivalent to:

cache.ram(key, None)

or something else happens?

3. The manual says that by setting 'time_expire = 0', it forces the cached 
object to be refreshed. Am I correct in understanding this as the cached 
object will be immediately set to whatever is supplied by the second 
argument of the 'cache.ram' call? Thus 'refreshed' here means 'updated'.

Your thoughts and comments are much appreciated. Thanks!

Reply via email to