Learning Python Network Programming

(Sean Pound) #1
Chapter 2

Know your cookies


It's worth looking at the properties of cookies in more detail. Let's examine the
cookies that GitHub sent us in the preceding section.


To do this, we need to pull the cookies out of the cookie jar. The CookieJar module
doesn't let us access them directly, but it supports the iterator protocol. So, a quick
way of getting them is to create a list from it:





cookies = list(cookie_jar)
cookies
[Cookie(version=0, name='logged_in', value='no', ...),
Cookie(version=0, name='_gh_sess', value='eyJzZxNzaW9uX...', ...)
]





You can see that we have two Cookie objects. Now, let's pull out some information
from the first one:





cookies[0].name
'logged_in'
cookies[0].value
'no'





The cookie's name allows the server to quickly reference it. This cookie is clearly a
part of the mechanism that GitHub uses for finding out whether we've logged in yet.
Next, let's do the following:





cookies[0].domain
'.github.com'
cookies[0].path
'/'





The domain and the path are the areas for which this cookie is valid, so our urllib
opener will include this cookie in any request that it sends to http://www.github.com and
its sub-domains, where the path is anywhere below the root.


Now, let's look at the cookie's lifetime:





cookies[0].expires
2060882017





This is a Unix timestamp; we can convert it to datetime:





import datetime
datetime.datetime.fromtimestamp(cookies[0].expires)
datetime.datetime(2035, 4, 22, 20, 13, 37)




Free download pdf