Cookies and Sessions

4,107 views
Skip to first unread message

Yago

unread,
Apr 25, 2012, 6:49:23 PM4/25/12
to web...@googlegroups.com
I'm quite new to web2py and a noob at it. I've been struggling with the difference between cookies and sessions. For what I've read the main difference is that you store cookies on the clients side and sessions on the server side, also that cookies expire and sessions get erased when you close the browser! But I have plenty of questions about them and how to use them(in web2py)

1. What can you store in them? 
                I've seen till now that you can store a dict and lists in a session, and I'm having trouble using cookies but I guess text is the only thing you can store...  

2. When are they deleted?
               According to what I googled cookies expire after a certain time(I've seen you can set this in w2p) and sessions are deleted when you exit the browser

3. Could you use cookies as temporary DB?
                If I'm right and can only store text I guess this would be complicated, but then the question is if you can modify the expiring time so it never expires unless the user deletes it? 
                    I mean you could use it to store user statistics for example? This is one of the things I want to implement but having trouble doing it. Let me show you what I'm trying 

I first do this                                 
def cookieCreate():
    
    response.cookies['cookie_test'] = 1
    response.cookies['cookie_test']['expires'] = 24 * 3600
    response.cookies['cookie_test']['path'] = '/'
then
 if request.cookies.has_key('cookie_test'):
            value = request.cookies['cookie_test'].value
            response.cookies['cookie_prueba'] = str( 1 + int(value)) #Shouldn't this update the cookie on the clients side?
        else: 
            cookieCreate()
As you can see, I want to implement a sort of counter that doesn't get deleted to develop some statistics later(how many games he played for example), and don't want to have a DB yet ( I want to learn how to work with cookies)

4. Where are they stored?
                 I imagine cookies are stored where the browser decides, then why the "path"? and while session exists where are they stored?

5. Can you store a cookie in a session and viceversa?

6. If sessions have to somehow be stored at the server how do you know which one belongs to whom? Is the a unique id? 


Well thank you in advance to whoever can help me, I just discovered yesterday there was this group!

               

Keith Edmunds

unread,
Apr 27, 2012, 2:19:08 AM4/27/12
to web...@googlegroups.com
On Wed, 25 Apr 2012 15:49:23 -0700 (PDT), varel...@gmail.com said:

> I'm quite new to web2py and a noob at it. I've been struggling with the
> difference between cookies and sessions...But I have plenty of questions
> about them and how to use them(in web2py)

I think you should approach them from a different perspective. You are
doing the equivalent of looking at a screwdriver and asking what you can
do with it, whereas you may be better off saying, "How can I replace this
hard disk?". In other words, what problem are you trying to solve?

That said, I'll try to offer some guidance. I suggest you ignore cookies
altogether. Web2py uses them, but YOU don't have to. Think of the session
as a temporary store to allow you to pass variables from one place to
another. Given that HTTP[S] is a stateless protocol, it can only tell you
that a user clicked on a link or typed a URL in the browser, not that they
have put 25 widgets in their shopping cart (that's simplifying it a
little, but hopefully you get the point).

In your code, you can use the session to store the contents of the
shopping cart (for example). So, when they click on 'buy', you might do
something like:

if session.cart:
session.cart.append(dict(item='widget',q=2))
else:
session.cart = [dict(item='widget',q=2)]

Later, when they checkout, you can do:

for orderline in session.cart:
process(orderline['item'],orderline['q'])

There are neater ways to do this, particularly if you use Storage()
objects rather than dictionaries, but the principle is that you can use
the session to give variables persistence between requests.

> *1. What can you store in them? *

In a session: anything than can be pickled (notable NOT user-defined
objects).

> *2. When are they deleted?*

When you do session.forget()

> *3. Could you use cookies as temporary DB?*

What are you trying to achieve?

Hopefully that gives you some idea...
--
"You can have everything in life you want if you help enough other people
get what they want" - Zig Ziglar.

Who did you help today?

Yago

unread,
Apr 27, 2012, 10:17:41 AM4/27/12
to web...@googlegroups.com
I think i  screw up answering because i don't see it, what i wanted to do basically was to avoid registration, so i could put the name and some data in the cookies and use it to identify him and even retrieve some data(how many times they connected to me) and things like that. I know they could delete their cookies but i don`t really care about it, so the main purpose was identification and learning. So know that i was recommended not to use cookies i'd like to know if i could do this with sessions.

If you don't use session.forget() sessions aren't deleted? 
as long as the code is executed within the same session by the same user (provided the user has not deleted session cookies and the session did not expire).
 
that's what the book says and what does it mean being in the same session if it isn't deleted?? sessions expire?? session cookies means that web2py stores sessions in cookies?  

But if sessions are not deleted and they have a unique id I could possibly use this to identify the user without using a login! 

Thanks, Yago

Anthony

unread,
Apr 27, 2012, 10:21:29 AM4/27/12
to web...@googlegroups.com
I'm quite new to web2py and a noob at it. I've been struggling with the difference between cookies and sessions. For what I've read the main difference is that you store cookies on the clients side and sessions on the server side

Yes, cookies are sent back and forth between the server and the client. You create a cookie on the server and it gets sent to the client. The client will then send it back with every request (until it expires). Although sessions are stored on the server (in files by default, though they can also be stored in the database), cookies are also involved in the implementation of sessions. In order to associate a particular server-side session with a particular client, a session cookie is passed between the client and server with a unique key that identifies the session on the server.
 
also that cookies expire and sessions get erased when you close the browser!

Technically, the server-side session does not get erased when you close the browser (though you can explicitly clean up old session files using a script like this one: http://code.google.com/p/web2py/source/browse/scripts/sessions2trash.py). However, the session cookie on the browser does get deleted by the browser when you close the browser. Any cookie that does not have an expiration set is considered a session cookie by the browser and deleted when the browser quits. As a result, even though the old session file may remain on the server, it is no longer accessible once the associated cookie is no longer being sent back by the browser.
 
But I have plenty of questions about them and how to use them(in web2py)

1. What can you store in them? 
                I've seen till now that you can store a dict and lists in a session, and I'm having trouble using cookies but I guess text is the only thing you can store...  

Technically, text is the only thing you can store in either, but non-string objects can be pickled and unpickled for storage in both sessions and cookies. So, you should be able to store dicts and lists in sessions and cookies -- web2py will handle the pickling and unpickling. More complex objects cannot be stored unless you define special pickling and unpickling functions for them (which is the case for Row and Rows objects, for example).
 

2. When are they deleted?
               According to what I googled cookies expire after a certain time(I've seen you can set this in w2p) and sessions are deleted when you exit the browser

Answered above. 

 
3. Could you use cookies as temporary DB?
                If I'm right and can only store text I guess this would be complicated, but then the question is if you can modify the expiring time so it never expires unless the user deletes it? 
                    I mean you could use it to store user statistics for example? This is one of the things I want to implement but having trouble doing it. Let me show you what I'm trying 

I first do this                                 
def cookieCreate():
    
    response.cookies['cookie_test'] = 1
    response.cookies['cookie_test']['expires'] = 24 * 3600
    response.cookies['cookie_test']['path'] = '/'
then
 if request.cookies.has_key('cookie_test'):
            value = request.cookies['cookie_test'].value
            response.cookies['cookie_prueba'] = str( 1 + int(value)) #Shouldn't this update the cookie on the clients side?
        else: 
            cookieCreate()
As you can see, I want to implement a sort of counter that doesn't get deleted to develop some statistics later(how many games he played for example), and don't want to have a DB yet ( I want to learn how to work with cookies)

Yes, the above should work, though I notice your last line references 'cookie_prueba' -- perhaps you meant that to be 'cookie_test' (so it will increment the value of 'cookie_test' on each request). Try response.flash = response.cookies['cookie_test'].value, and on each page refresh you should see the flash message increment by one.


4. Where are they stored?
                 I imagine cookies are stored where the browser decides, then why the "path"?

The "path" attribute tells the browser with which URL requests to send the cookie -- it refers to the URL path (i.e., the part of the URL after the domain). Setting the path to "/" tells the browser to send the cookie to all URLs within the domain (i.e., all paths). See http://en.wikipedia.org/wiki/HTTP_cookie#Domain_and_Path
 
and while session exists where are they stored?

By default in /applications/yourapp/sessions, but you can also store them in the database. See http://web2py.com/books/default/chapter/29/4#session.
 

5. Can you store a cookie in a session and viceversa?

I suppose you could read the value of a cookie and then store it in the session (not sure why). You could also effectively store session data in a cookie (instead of using the server-side session). You would do that by creating your own cookie without an expiration (which makes it a session cookie) -- in this case, you would not be using the web2py session functionality. The problem is that it's not secure -- either the user or an attacker could tamper with the contents of the cookie before sending it back. There are ways to make cookie based sessions secure via encryption, but web2py doesn't include any cookie based session functionality. If you happen to be storing large amounts of data in the session, cookie based sessions may not be ideal because you'll be passing all the data back and forth over the wire on every request.
 

6. If sessions have to somehow be stored at the server how do you know which one belongs to whom? Is the a unique id? 

Answered above. Yes, a unique ID is generated. 

Anthony

Anthony

unread,
Apr 27, 2012, 10:27:01 AM4/27/12
to web...@googlegroups.com
> *2. When are they deleted?*

When you do session.forget()

session.forget() does not delete the session file -- it just tells web2py not to save any changes to the session during the current request.

Anthony 

Yago

unread,
Apr 27, 2012, 10:40:55 AM4/27/12
to web...@googlegroups.com
That makes it all really clear, thank you so much Anthony. The browser deletes the session cookie when you close it, but there's still the server session. What happens to that? I mean when you open the browser again do you get assigned another session or do you 'reconnect' to the old one maintaining the id? if yes i could use that id as my login value to identify the user and if the answer is no, then why isn't it deleted from the folder?

Sry to be a pain with this just want to make sure I really get it!! ;b

Derek

unread,
Apr 27, 2012, 3:00:35 PM4/27/12
to web...@googlegroups.com
Session cookies would be deleted after browser close, so you'd be assigned a new session. The files are not deleted because the server has no way of knowing if the person has restarted their browser or not.

Anthony

unread,
Apr 27, 2012, 4:27:05 PM4/27/12
to web...@googlegroups.com
Technically, the server-side session does not get erased when you close the browser (though you can explicitly clean up old session files using a script like this one: http://code.google.com/p/web2py/source/browse/scripts/sessions2trash.py). However, the session cookie on the browser does get deleted by the browser when you close the browser.

I should note there is one exception to the session cookie being deleted upon closing the browser. If you are using Auth and set auth.settings.remember_me_form = True, upon login with the "Remember me" option checked, it will set a 30 day expiration on the session cookie (so, from the browser's perspective, it is technically no longer a "session" cookie). In that case, the session will survive across multiple browser sessions.

Anthony

Derek

unread,
Apr 27, 2012, 5:32:15 PM4/27/12
to web...@googlegroups.com
Oh, one more thing - if you want to delete the sessions, errors, and caches, click the 'clean' button in admin.


On Friday, April 27, 2012 7:40:55 AM UTC-7, Yago wrote:

Anthony

unread,
Apr 27, 2012, 9:37:33 PM4/27/12
to web...@googlegroups.com
Oh, one more thing - if you want to delete the sessions, errors, and caches, click the 'clean' button in admin.

That's useful if you want to pack the application, but you may not want to do that on production, as you might delete active sessions, errors that you haven't viewed yet, etc. To remove expired sessions, it might be better to run a background task like http://code.google.com/p/web2py/source/browse/scripts/sessions2trash.py.

Anthony 
Reply all
Reply to author
Forward
0 new messages