After accessing the page for the first time, the Server can add the Cookie information to the HTTP Header and return it to the browser. The browser automatically saves the information locally;
When you access the same domain name again, the browser sends the Cookie information along with the request. The Server can read the information for processing.
You can set the expiration time for a Cookie, which is automatically deleted by the browser after expiration;
When we want to return the page, the first output is as follows:
[Python]
Print "Content-type: text/plain \ n"
It is actually an HTTP Header. If two line breaks in a row, the HTTP Header is ended and the rest is processed as data;
After the Cookie is included, the output is roughly as follows:
[Python]
Print "Content-Type: text/html"
Print "Set-Cookie: session = 12345"
Print # add a line feed to indicate that the HTTP Header part ends.
Code:
Setcookie. py
[Python]
#! /Usr/bin/env python
Import Cookie
Import datetime
Import random
Expiration = datetime. datetime. now () + datetime. timedelta (days = 30)
Cookie = Cookie. SimpleCookie ()
Cookie ["session"] = random. randint (0)
Cookie ["session"] ["domain"] = "localhost"
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 ()
Getcookie. py
[Python]
#! /Usr/bin/env python
Import Cookie
Import OS
Print "Content-type: text/plain \ n"
Try:
Cookie = Cookie. SimpleCookie (OS. environ ["HTTP_COOKIE"])
Print "session =" + cookie ["session"]. value
Handle T (Cookie. CookieError, KeyError ):
Print "session cookie not set! "
From Avenue to simplicity