Simple session management proposal

38 views
Skip to first unread message

Sven Hartenstein

unread,
Sep 7, 2011, 2:30:18 PM9/7/11
to rr...@googlegroups.com
Hi Rook fans,

I am veeery new to Rook. Jeffrey, thank you very much for building and
sharing it!

I was looking for session management, i.e. "saving" data for later use
in the same R session and found this thread which seemed to suggest
that there is no session management for Rook (yet):
https://groups.google.com/group/rrook/browse_thread/thread/d21635b530f328bf

Below, I share a function that I think could supply very simple
session management to Rook with the use of a "session environment".
Now, I am not only new to Rook but also know very little about R's
concept of environments, so that I do not know whether my code is
nonsense because I missed something crucial or useful. It seems to
"work" but maybe there are limitations? I would very much enjoy to get
some feedback on that.

Sven


library(Rook)

sess <- function(var, # a character string
value=NULL # NULL or a value to assign
) {
if (!exists(".RookSessionEnv")) {
assign(".RookSessionEnv", new.env(parent=.GlobalEnv), envir=.GlobalEnv)
}
if (is.null(value)) { # get value
if (exists(var, envir=.RookSessionEnv)) {
return(get(var, envir=.RookSessionEnv))
} else {
return(FALSE)
}
} else { # set value
assign(var, value, envir=.RookSessionEnv)
}
}

app <- function(env){
req <- Rook::Request$new(env)
res <- Rook::Response$new()

if (sess("counter")==FALSE) sess("counter", 0)
count <- sess("counter")+1
sess("counter", count)

res$write(paste('<b>Counter is',sess("counter"),'</b>\n'))
res$write('<form method="POST">\n')
res$write('<input type="submit" name="Submit">\n</form>\n<br>')
res$finish()
}

s <- Rhttpd$new()
s$add(app=app, name='sessiontest')
s$start(quiet=TRUE)
s$browse('sessiontest')

### End of code

Michele

unread,
Oct 30, 2013, 12:47:05 PM10/30/13
to rr...@googlegroups.com
It works like a charm. Thanks. What I would do is (since the data are quite small) saving on the log on the disk. For example:

    sink("RookSessionEnv.csv")
    cat(var, value, sep=",")
    sink()

after assign statement. This is quite simplistic (the above will overwrite the same line again and again), but the idea is to save (safely) the session log. It'd be cool to have a proper log with clients' ip address. In which case the above can be changed to sink("RookSessionEnv.csv", append=T) and then cat()ting ip and connection time.
Reply all
Reply to author
Forward
0 new messages