How python processes cookies

Source: Internet
Author: User
Tags set cookie

To install cookies in your browser, the HTTP Server adds an HTTP header similar to the following to the HTTP response:

Copy codeThe Code is as follows:
Set-Cookie: session = 8345234; expires = Sun, 15-Nov-2013 15:00:00 GMT; path =/; domain = baidu.com

Expires indicates the cookie lifecycle, path indicates the valid path of the cookie, and domain indicates the valid domain of the cookie.

The path "path" is used to set the top-level directory for reading a cookie.

Set the cookie Path to the top-level directory of Your webpage so that all webpages under this directory can access this cookie.

Method: Add path =/to your cookie. If you only want the webpage in the "food" directory to use this cookie, add path =/food ;.

Domain: some websites have many small domain names. For example, Baidu may still have webpages under "news.baidu.com" "zhidao.baidu.com" and "v.baidu.com.

If you want all machines under "baidu.com" to read the cookie, you must add "domain = .baidu.com" to the cookie ".

The user's browser will store the Cookie until it expires, and the browser will send an HTTP request header similar to the following content to the server that complies with the path and domain:
Copy codeThe Code is as follows:
Cookie: session = 8345234.

For example, when you log on to www.baidu.com, the cookie in the HTTP Response Header sent back by the Baidu server is:

Copy codeThe Code is as follows:
Set-Cookie: H_PS_PSSID = 4682134567_1452_9876_4759; path =/; domain = .baidu.com
Set-Cookie: BDSVRTM = 74; path =/

HTTP request header of the browser:

Copy codeThe Code is as follows:
Cookie: BAIDUID = 0FD996SDFG12 ******** rjb9c227f4c: FG = 1; locale = zh; bd1__firstime = 1384567418140; NBID = fingerprint: FG = 1; H_PS_LC = 4_shadu2014; BD_CK_SAM = 1; H_PS_PSSID = 4682134567_1452_9876_4759

When the browser sends the cookie back to the HTTP server, it uses the key = value string encoding format. No optional attributes such as expires, path, and domain are returned.

The cookie string is usually located in the HTTP_COOKIE environment variable and can be read as follows:

Copy codeThe Code is as follows:
Import OS
Print "Content-type: text/plain \ n"
If "HTTP_COOKIE" in OS. environ:
Print OS. environ ["HTTP_COOKIE"]
Else:
Print "HTTP_COOKIE not set! "

In Python, The Cookie module (http. cookies in python2 and python3) provides a special dictionary-like object SimpleCookie, which stores and manages a set of cookie values called Morsel.

Each Morsel has the name, value, and optional attributes (expires, path, domain, comment, max-age, secure, version, httponly ).

SimpleCookie can use the output () method to create a cookie data output in the form of an HTTP header, and use the js_output () method to generate a string containing javascript code.

Use HTTP_COOKIE to generate a cookie:

Copy codeThe Code is as follows:
Cookie = Cookie. SimpleCookie (OS. environ ['HTTP _ cookier'])
Print cookie. output ()

Set cookie:

Copy codeThe Code is as follows:
Import Cookie
Import datetime
Import random

Expiration = datetime. datetime. now () + datetime. timedelta (days = 30)
Cookie = Cookie. SimpleCookie ()
Cookie ["session"] = random. randint (1,000000000)
Cookie ["session"] ["domain"] = ".baidu.com"
Cookie ["session"] ["path"] = "/"
Cookie ["session"] ["expires"] = expiration. strftime ("% a, % d-% B-% Y % H: % M: % S PST ")

Print "Content-type: text/plain"
Print cookie. output ()
Print
Print "Cookie set with:" + cookie. output ()

Output:
Copy codeThe Code is as follows:
Content-type: text/plain
Set-Cookie: session = 155209565; Domain = .jayconrod.com; expires = Mon, 03-Mar-2014 07:42:47 PST; Path =/
Cookie set with: Set-Cookie: session = 155209565; Domain = .jayconrod.com; expires = Mon, 03-Mar-2014 07:42:47 PST; Path =/

In Python, The cookielib Library (http. cookiejar in python3) provides client support for storing and managing cookies.

The main function of this module is to provide objects that can store cookies. This module captures the cookie and resends it in subsequent connection requests. It can also be used

Processes files that contain cookie data.

This module provides the following objects: CookieJar, FileCookieJar, MozillaCookieJar, and LWPCookieJar.

CookieJar objects are stored in the memory.

Copy codeThe Code is as follows:
>>> Import urllib2
>>> Import cookielib
>>> Cookie = cookielib. CookieJar ()
>>> Handler = urllib2.HTTPCookieProcessor (cookie)
>>> Opener = urllib2.build _ opener (handler)
>>> Opener. open ('HTTP: // www.google.com.hk ') <addinfourl at 161806444 whose fp = <socket. _ fileobject object at 0x9a348ac>

The cookie used to access google has been captured.

Let's take a look at the following:
Copy codeThe Code is as follows:
>>> Print cookie
<Cookielib. cookieJar [<Cookie NID = 67 = B6YQoEIEjcqDj-adada_WmNYl_JvADsDEDchFTMtAgERTgRjK452ko6gr9G0Q5p9h1vlmHpCR56XCrWwg1pv6iqhZnaVlnwoeM-Ln7kIUWi92l-X2fvUqgwDnN3qowDW for .google.com.hk/>, <Cookie PREF = ID = 7ae0fa51234ce2b1: FF = 0: NW = 1: TM = 1391219446: LM = 1391219446: S = cFiZ5X8ts9NY3cmk for .google.com.hk/>]>

It seems to be a set of Cookie instances. Cookie instances have attributes such as name, value, path, and expires:

Copy codeThe Code is as follows:
>>> For ck in cookie:
... Print ck. name, ':', ck. value
...
NID: 67 = B6YQoEIEjcqDj-adada_WmNYl_JvADsDEDchFTMtAgERTgRjK452ko6gr9G0Q5p9h1vlmHpCR56XCrWwg1pv6iqhZnaVlnwoeM-Ln7kIUWi92l-X2fvUqgwDnN3qowDW
PREF: ID = 7ae0fa51234ce2b1: FF = 0: NW = 1: TM = 1391219446: LM = 1391219446: S = cFiZ5X8ts9NY3cmk

You can also capture cookies to files.

FileCookieJar (filename)

Create a FileCookieJar instance, retrieve the cookie information, and store the information in the file. filename is the file name.

MozillaCookieJar (filename)

Create a FileCookieJar instance compatible with the Mozilla cookies.txt file.

LWPCookieJar (filename)

Create a FileCookieJar instance that is compatible with libwww-perl Set-Cookie3 files.

Code:

Copy codeThe Code is as follows:
Import urllib2
Import cookielib
Def HandleCookie ():
# Handle cookie whit file
Filenamepolic'filecookiejar.txt'
Url = 'HTTP: // www.google.com.hk'
FileCookieJar = cookielib. LWPCookieJar (filename)
FileCookeJar. save ()
Opener = urllib2.build _ opener (urllib2.HTTPCookieProcessor (FileCookieJar ))
Opener. open (url)
FileCookieJar. save ()
Print open (filename). read ()
# Read cookie from file
Readfilename = "readFileCookieJar.txt"
Using illacookiejarfile = cookielib. Using illacookiejar (readfilename)
Print export illacookiejarfile
MozillaCookieJarFile. load (cookieFilenameMozilla)
Print export illacookiejarfile
If _ name __= = "_ main __":
HandleCookie ()

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.