Python
  • What’s New in Python 更新
    • What’s New in Python 2.7
    • What’s New in Python 2.6
    • What’s New in Python 2.5
    • What’s New in Python 2.4
    • What’s New in Python 2.3
    • What’s New in Python 2.2
    • What’s New in Python 2.1
    • What’s New in Python 2.0
  • The Python Tutorial
    • 1. Whetting Your Appetite 开胃菜
    • 2. Using the Python Interpreter
    • 3. An Informal Introduction to Python
    • 4. More Control Flow Tools
    • 5. Data Structures
    • 6. Modules
    • 7. Input and Output
    • 8. Errors and Exceptions
    • 9. Classes
    • 10. Brief Tour of the Standard Library
    • 11. Brief Tour of the Standard Library – Part II
    • 12. What Now?
    • 13. Interactive Input Editing and History Substitution
    • 14. Floating Point Arithmetic: Issues and Limitations
  • Python Setup and Usage
    • 1. Command line and environment
    • 2. Using Python on Unix platforms
    • 3. Using Python on Windows
    • 4. Using Python on a Macintosh
  • The Python Language Reference
    • 1. Introduction
    • 2. Lexical analysis
    • 3. Data model
    • 4. Execution model
    • 5. Expressions
    • 6. Simple statements
    • 7. Compound statements
    • 8. Top-level components
    • 9. Full Grammar specification
  • The Python Standard Library
    • 1. Introduction
    • 2. Built-in Functions
    • 3. Non-essential Built-in Functions
    • 4. Built-in Constants
    • 5. Built-in Types
    • 6. Built-in Exceptions
    • 7. String Services
    • 8. Data Types
    • 9. Numeric and Mathematical Modules
    • 10. File and Directory Access
    • 11. Data Persistence
    • 12. Data Compression and Archiving
    • 13. File Formats
    • 14. Cryptographic Services
    • 15. Generic Operating System Services
    • 16. Optional Operating System Services
    • 17. Interprocess Communication and Networking
    • 18. Internet Data Handling
    • 19. Structured Markup Processing Tools
    • 20. Internet Protocols and Support
    • 21. Multimedia Services
    • 22. Internationalization
    • 23. Program Frameworks
    • 24. Graphical User Interfaces with Tk
    • 25. Development Tools
    • 26. Debugging and Profiling
    • 27. Python Runtime Services
    • 28. Custom Python Interpreters
    • 29. Restricted Execution
    • 30. Importing Modules
    • 31. Python Language Services
    • 32. Python compiler package
    • 33. Miscellaneous Services
    • 34. MS Windows Specific Services
    • 35. Unix Specific Services
    • 36. Mac OS X specific services
    • 37. MacPython OSA Modules
    • 38. SGI IRIX Specific Services
    • 39. SunOS Specific Services
    • 40. Undocumented Modules
  • Extending and Embedding the Python Interpreter
    • 1. Extending Python with C or C++
    • 2. Defining New Types
    • 3. Building C and C++ Extensions with distutils
    • 4. Building C and C++ Extensions on Windows
    • 5. Embedding Python in Another Application
  • Python/C API Reference Manual
    • Introduction
    • The Very High Level Layer
    • Reference Counting
    • Exception Handling
    • Utilities
    • Abstract Objects Layer
    • Concrete Objects Layer
    • Initialization, Finalization, and Threads
    • Memory Management
    • Object Implementation Support
  • Distributing Python Modules
    • 1. An Introduction to Distutils
    • 2. Writing the Setup Script
    • 3. Writing the Setup Configuration File
    • 4. Creating a Source Distribution
    • 5. Creating Built Distributions
    • 6. The Python Package Index (PyPI)
    • 7. Examples
    • 8. Extending Distutils
    • 9. Command Reference
    • 10. API Reference
  • Installing Python Modules
    • Introduction
    • Standard Build and Install
    • Alternate Installation
    • Custom Installation
    • Distutils Configuration Files
    • Building Extensions: Tips and Tricks
  • Python HOWTOs
    • Porting Python 2 Code to Python 3
    • Porting Extension Modules to Python 3
    • Curses Programming with Python
    • Descriptor HowTo Guide
    • Idioms and Anti-Idioms in Python
    • Functional Programming HOWTO
    • Logging HOWTO
    • Logging Cookbook
    • Regular Expression HOWTO
    • Socket Programming HOWTO
    • Sorting HOW TO
    • Unicode HOWTO
    • HOWTO Fetch Internet Resources Using urllib2
    • HOWTO Use Python in the web
    • Argparse Tutorial
  • Python Frequently Asked Questions
    • General Python FAQ
    • Programming FAQ
    • Design and History FAQ
    • Library and Extension FAQ
    • Extending/Embedding FAQ
    • Python on Windows FAQ
    • Graphic User Interface FAQ
    • “Why is Python Installed on my Computer?” FAQ
  • Glossary
  • About these documents
    • Contributors to the Python Documentation
  • Reporting Bugs
    • Documentation bugs
    • Using the Python issue tracker
  • Copyright
  • History and License
    • History of the software
    • Terms and conditions for accessing or otherwise using Python
    • Licenses and Acknowledgements for Incorporated Software
 
Python
  • Docs »
  • 20.22. Cookie — HTTP state management
  • Edit on GitHub

20.22. Cookie — HTTP state management¶

Note

The Cookie module has been renamed to http.cookies in Python 3. The 2to3 tool will automatically adapt imports when converting your sources to Python 3.

Source code: Lib/Cookie.py


The Cookie module defines classes for abstracting the concept of cookies, an HTTP state management mechanism. It supports both simple string-only cookies, and provides an abstraction for having any serializable data-type as cookie value.

The module formerly strictly applied the parsing rules described in the RFC 2109 and RFC 2068 specifications. It has since been discovered that MSIE 3.0x doesn’t follow the character rules outlined in those specs and also many current day browsers and servers have relaxed parsing rules when comes to Cookie handling. As a result, the parsing rules used are a bit less strict.

The character set, string.ascii_letters, string.digits and !#$%&'*+-.^_`|~ denote the set of valid characters allowed by this module in Cookie name (as key).

Note

On encountering an invalid cookie, CookieError is raised, so if your cookie data comes from a browser you should always prepare for invalid data and catch CookieError on parsing.

exception Cookie.CookieError¶

Exception failing because of RFC 2109 invalidity: incorrect attributes, incorrect Set-Cookie header, etc.

class Cookie.BaseCookie([input])¶

This class is a dictionary-like object whose keys are strings and whose values are Morsel instances. Note that upon setting a key to a value, the value is first converted to a Morsel containing the key and the value.

If input is given, it is passed to the load() method.

class Cookie.SimpleCookie([input])¶

This class derives from BaseCookie and overrides value_decode() and value_encode() to be the identity and str() respectively.

class Cookie.SerialCookie([input])¶

This class derives from BaseCookie and overrides value_decode() and value_encode() to be the pickle.loads() and pickle.dumps().

Deprecated since version 2.3: Reading pickled values from untrusted cookie data is a huge security hole, as pickle strings can be crafted to cause arbitrary code to execute on your server. It is supported for backwards compatibility only, and may eventually go away.

class Cookie.SmartCookie([input])¶

This class derives from BaseCookie. It overrides value_decode() to be pickle.loads() if it is a valid pickle, and otherwise the value itself. It overrides value_encode() to be pickle.dumps() unless it is a string, in which case it returns the value itself.

Deprecated since version 2.3: The same security warning from SerialCookie applies here.

A further security note is warranted. For backwards compatibility, the Cookie module exports a class named Cookie which is just an alias for SmartCookie. This is probably a mistake and will likely be removed in a future version. You should not use the Cookie class in your applications, for the same reason why you should not use the SerialCookie class.

See also

Module cookielib
HTTP cookie handling for web clients. The cookielib and Cookie modules do not depend on each other.
RFC 2109 - HTTP State Management Mechanism
This is the state management specification implemented by this module.

20.22.1. Cookie Objects¶

BaseCookie.value_decode(val)¶

Return a decoded value from a string representation. Return value can be any type. This method does nothing in BaseCookie — it exists so it can be overridden.

BaseCookie.value_encode(val)¶

Return an encoded value. val can be any type, but return value must be a string. This method does nothing in BaseCookie — it exists so it can be overridden

In general, it should be the case that value_encode() and value_decode() are inverses on the range of value_decode.

BaseCookie.output([attrs[, header[, sep]]])¶

Return a string representation suitable to be sent as HTTP headers. attrs and header are sent to each Morsel‘s output() method. sep is used to join the headers together, and is by default the combination '\r\n' (CRLF).

Changed in version 2.5: The default separator has been changed from '\n' to match the cookie specification.

BaseCookie.js_output([attrs])¶

Return an embeddable JavaScript snippet, which, if run on a browser which supports JavaScript, will act the same as if the HTTP headers was sent.

The meaning for attrs is the same as in output().

BaseCookie.load(rawdata)¶

If rawdata is a string, parse it as an HTTP_COOKIE and add the values found there as Morsels. If it is a dictionary, it is equivalent to:

for k, v in rawdata.items():
    cookie[k] = v

20.22.2. Morsel Objects¶

class Cookie.Morsel¶

Abstract a key/value pair, which has some RFC 2109 attributes.

Morsels are dictionary-like objects, whose set of keys is constant — the valid RFC 2109 attributes, which are

  • expires
  • path
  • comment
  • domain
  • max-age
  • secure
  • version
  • httponly

The attribute httponly specifies that the cookie is only transfered in HTTP requests, and is not accessible through JavaScript. This is intended to mitigate some forms of cross-site scripting.

The keys are case-insensitive.

New in version 2.6: The httponly attribute was added.

Morsel.value¶

The value of the cookie.

Morsel.coded_value¶

The encoded value of the cookie — this is what should be sent.

Morsel.key¶

The name of the cookie.

Morsel.set(key, value, coded_value)¶

Set the key, value and coded_value attributes.

Morsel.isReservedKey(K)¶

Whether K is a member of the set of keys of a Morsel.

Morsel.output([attrs[, header]])¶

Return a string representation of the Morsel, suitable to be sent as an HTTP header. By default, all the attributes are included, unless attrs is given, in which case it should be a list of attributes to use. header is by default "Set-Cookie:".

Morsel.js_output([attrs])¶

Return an embeddable JavaScript snippet, which, if run on a browser which supports JavaScript, will act the same as if the HTTP header was sent.

The meaning for attrs is the same as in output().

Morsel.OutputString([attrs])¶

Return a string representing the Morsel, without any surrounding HTTP or JavaScript.

The meaning for attrs is the same as in output().

20.22.3. Example¶

The following example demonstrates how to use the Cookie module.

>>> import Cookie
>>> C = Cookie.SimpleCookie()
>>> C["fig"] = "newton"
>>> C["sugar"] = "wafer"
>>> print C # generate HTTP headers
Set-Cookie: fig=newton
Set-Cookie: sugar=wafer
>>> print C.output() # same thing
Set-Cookie: fig=newton
Set-Cookie: sugar=wafer
>>> C = Cookie.SimpleCookie()
>>> C["rocky"] = "road"
>>> C["rocky"]["path"] = "/cookie"
>>> print C.output(header="Cookie:")
Cookie: rocky=road; Path=/cookie
>>> print C.output(attrs=[], header="Cookie:")
Cookie: rocky=road
>>> C = Cookie.SimpleCookie()
>>> C.load("chips=ahoy; vienna=finger") # load from a string (HTTP header)
>>> print C
Set-Cookie: chips=ahoy
Set-Cookie: vienna=finger
>>> C = Cookie.SimpleCookie()
>>> C.load('keebler="E=everybody; L=\\"Loves\\"; fudge=\\012;";')
>>> print C
Set-Cookie: keebler="E=everybody; L=\"Loves\"; fudge=\012;"
>>> C = Cookie.SimpleCookie()
>>> C["oreo"] = "doublestuff"
>>> C["oreo"]["path"] = "/"
>>> print C
Set-Cookie: oreo=doublestuff; Path=/
>>> C["twix"] = "none for you"
>>> C["twix"].value
'none for you'
>>> C = Cookie.SimpleCookie()
>>> C["number"] = 7 # equivalent to C["number"] = str(7)
>>> C["string"] = "seven"
>>> C["number"].value
'7'
>>> C["string"].value
'seven'
>>> print C
Set-Cookie: number=7
Set-Cookie: string=seven
>>> # SerialCookie and SmartCookie are deprecated
>>> # using it can cause security loopholes in your code.
>>> C = Cookie.SerialCookie()
>>> C["number"] = 7
>>> C["string"] = "seven"
>>> C["number"].value
7
>>> C["string"].value
'seven'
>>> print C
Set-Cookie: number="I7\012."
Set-Cookie: string="S'seven'\012p1\012."
>>> C = Cookie.SmartCookie()
>>> C["number"] = 7
>>> C["string"] = "seven"
>>> C["number"].value
7
>>> C["string"].value
'seven'
>>> print C
Set-Cookie: number="I7\012."
Set-Cookie: string=seven
Next Previous

© Copyright 1990-2013, Python Software Foundation. Last updated on Dec 01, 2013.

Sphinx theme provided by Read the Docs