PyMOTW: Cookie
The Cookie module defines classes for parsing and creating HTTP cookie headers.
Module: Cookie
Purpose: Working with HTTP cookies from the server side.
Python Version: 2.1 and later
Description:
Cookies have been a part of the HTTP protocol for a long time. All of the modern web development frameworks provide easy access to cookies so a programmer almost never has to worry about how to format them or make sure the headers are sent properly. It can be instructive to understand how cookies work, though, and the options available.
The Cookie module implements a parser for cookies that is mostly RFC 2109 compliant. It is a little less strict than the standard because MSIE 3.0x does not support the entire standard.
Creating and Setting a Cookie:
Cookies are used as state management, and as such as usually set by the server to be stored and returned by the client. The most trivial example of creating a cookie looks something like:
import Cookie
c = Cookie.SimpleCookie()
c['mycookie'] = 'cookie_value'
print c
The output is a valid
Set-Cookie header ready to be passed to the client as part of the HTTP response:
$ python Cookie_setheaders.py
Set-Cookie: mycookie=cookie_value
Morsels:
It is also possible to control the other aspects of a cookie, such as the expiration, path, and domain. In fact, all of the RFC attributes for cookies can be managed through the
Morsel object representing the cookie value.import Cookie
import datetime
def show_cookie(c):
print c
for key, morsel in c.iteritems():
print 'key =', morsel.key
print ' value =', morsel.value
print ' coded_value =', morsel.coded_value
for name in morsel.keys():
if morsel[name]:
print ' %s = %s' % (name, morsel[name])
c = Cookie.SimpleCookie()
# A cookie with a value that has to be encoded to fit into the header
c['encoded_value_cookie'] = '"cookie_value"'
c['encoded_value_cookie']['comment'] = 'Notice that this cookie value has escaped quotes'
# A cookie that only applies to part of a site
c['restricted_cookie'] = 'cookie_value'
c['restricted_cookie']['path'] = '/sub/path'
c['restricted_cookie']['domain'] = 'PyMOTW'
c['restricted_cookie']['secure'] = True
# A cookie that expires in 5 minutes
c['with_max_age'] = 'expires in 5 minutes'
c['with_max_age']['max-age'] = 300 # seconds
# A cookie that expires at a specific time
c['expires_at_time'] = 'cookie_value'
expires = datetime.datetime.now() + datetime.timedelta(hours=1)
c['expires_at_time']['expires'] = expires.strftime('%a, %d %b %Y %H:%M:%S') # Wdy, DD-Mon-YY HH:MM:SS GMT
show_cookie(c)
The above example includes two different methods for setting stored cookies that expire. You can set
max-age to a number of seconds, or expires to a date and time when the cookie should be discarded.
$ python Cookie_Morsel.py
Set-Cookie: encoded_value_cookie="\"cookie_value\""; Comment=Notice that this cookie value has escaped quotes
Set-Cookie: expires_at_time=cookie_value; expires=Sun, 01 Jun 2008 11:37:00
Set-Cookie: restricted_cookie=cookie_value; Domain=PyMOTW; Path=/sub/path; secure
Set-Cookie: with_max_age="expires in 5 minutes"; Max-Age=300
key = restricted_cookie
value = cookie_value
coded_value = cookie_value
domain = PyMOTW
secure = True
path = /sub/path
key = with_max_age
value = expires in 5 minutes
coded_value = "expires in 5 minutes"
max-age = 300
key = encoded_value_cookie
value = "cookie_value"
coded_value = "\"cookie_value\""
comment = Notice that this cookie value has escaped quotes
key = expires_at_time
value = cookie_value
coded_value = cookie_value
expires = Sun, 01 Jun 2008 11:37:00
Both the Cookie and Morsel objects act like dictionaries. The Morsel responds to a fixed set of keys:
- expires
- path
- comment
- domain
- max-age
- secure
- version
The keys for the Cookie instance are the names of the individual cookies being stored. That information is also available from the
key attribute of the Morsel.Encoded Values:
The cookie header may require values to be encoded so they can be parsed properly.
import Cookie
c = Cookie.SimpleCookie()
c['integer'] = 5
c['string_with_quotes'] = 'He said, "Hello, World!"'
for name in ['integer', 'string_with_quotes']:
print c[name].key
print ' %s' % c[name]
print ' value=%s' % c[name].value, type(c[name].value)
print ' coded_value=%s' % c[name].coded_value
The Morsel.value is always the decoded value of the cookie, while Morsel.coded_value is always the representation to be used for transmitting the value to the client. Both values are always strings. Values saved to a cookie that are not strings are converted automatically.
$ python Cookie_coded_value.py
integer
Set-Cookie: integer=5
value=5 <type 'str'>
coded_value=5
string_with_quotes
Set-Cookie: string_with_quotes="He said, \"Hello, World!\""
value=He said, "Hello, World!" <type 'str'>
coded_value="He said, \"Hello, World!\""
Receiving and Parsing Cookie Headers:
Once the
Set-Cookie headers are received by the client, it will return those cookies to the server on subsequent requests using the Cookie header. The incoming header will look like:
Cookie: integer=5; string_with_quotes="He said, \"Hello, World!\""
The cookies are either available directly from the headers or, depending on your web server/framework, the
HTTP_COOKIE environment variable. To decode them, pass the string without the header prefix to the SimpleCookie when instantiating it, or use the load() method.import Cookie
HTTP_COOKIE = r'integer=5; string_with_quotes="He said, \"Hello, World!\""'
print 'From constructor:'
c = Cookie.SimpleCookie(HTTP_COOKIE)
print c
print 'From load():'
c = Cookie.SimpleCookie()
c.load(HTTP_COOKIE)
print c
$ python Cookie_parse.py
From constructor:
Set-Cookie: integer=5
Set-Cookie: string_with_quotes="He said, \"Hello, World!\""
From load():
Set-Cookie: integer=5
Set-Cookie: string_with_quotes="He said, \"Hello, World!\""
Alternative Output Formats:
Besides using the
Set-Cookie header, it is possible to use JavaScript to add cookies to a client. SimpleCookie and Morsel provide JavaScript output via the js_output() method:import Cookie
c = Cookie.SimpleCookie()
c['mycookie'] = 'cookie_value'
c['another_cookie'] = 'second value'
print c.js_output()
$ python Cookie_js_output.py
<script type="text/javascript">
<!-- begin hiding
document.cookie = "another_cookie="second value"";
// end hiding -->
</script>
<script type="text/javascript">
<!-- begin hiding
document.cookie = "mycookie=cookie_value";
// end hiding -->
</script>
Deprecated Classes:
All of these examples have used SimpleCookie. The Cookie module also provides 2 other classes, SerialCookie and SmartCookie. SerialCookie can handle any values that can be pickled. SmartCookie figures out whether a value needs to be unpickled or if it is a simple value. Since both of these classes use pickles, they are potential security holes in your application and you should not use them. It is safer to store state on the server, and give the client a session key instead.
References:
cookielib (for working with cookies in an HTTP client)
RFC 2109, HTTP State Management Mechanism
Python Module of the Week Home
Download Sample Code
Technorati Tags:
python, PyMOTW
Twitter
1 comments:
VIAGRA MAKES IT EASIER TO CONTROL IMPOTENCY
Each year, the thousand of people who suffer from erectile dysfunction increases due to a contrast of factors. Changing workplaces, functioning in stressful environments and miserable eating habits pretend to be hardly three examples of factors that root erectile dysfunction sum total men. Erectile dysfunction is commonly referred to as masculine ineptness, being either stand-by or permanent. Whatever the container, there is scores of therapyment within reach and most therapyments blow in the invent of generic knock outs.
Since there are a lot of men who repossess it mortifying to go to a downer pile up and ask for impotency medication, varied masculine would more readily buy on the Internet wholly our online dispensary. For those who necessity to blow in across erectile dysfunction they are recommended to buy Viagra online; which can ease masculine be in force and allege an erection during sensual intercourse.
Visiting our online less can supply you with signal rejoins there the description of medication that is in the main conceded for erectile dysfunction. You can also learn more there the inall symptoms. Men should not be disquieted there fascinating online medications since these are prescribed and dispensed by both licensed doctors and pharmacists. So, you can buy these knock outs without any affronted by hurdles.
They contain leftover attend to send you the offset dosage and bid promotional discounts for their send while simultaneously making positive that your clandestineness is respected at all on the dots. Conveyance pro teems are prompt. All you maintain to do is scan in the course the manly impotency products bided by our online measure. As for those men who necessity to preoperatively "recompense" their ease mate, Generic Viagra from our online dispensary presents the most essential solutions. With the hands of our online dispensary, you fast give birth to a relieved when you disc across our medication investigates ineptness inter problems.
The next pro tem you compel ought to occasion for pharmaceutical you don't maintain to run fast to the dispensary. Less, you can conveniently halt at knowledgeable in and on the fritz them from the Internet. Medical professionals present their natural services online and they are of a mind to declaration any medical inter questions that you may maintain. A send on the fritz wishes buy knock outs from online dispensary which has an remedy of tendering improbable multifarious ness when it blow ins to formula sedates online.
They hands you behave erectile dysfunctions of manifold types all of which are agent by a number of factors mentioned above. Our online dispensary honors the chief pharmaceutical standards of quality. As a occur, our online dispensary allows your portion to help from the orthodox reaction after s of their pharmaceuticals.
Author: Michael Joseph http://www.onlinepharmacy.vg/catalog/-c-32_117.html
Post a Comment