Use Python to process cookies

Source: Internet
Author: User

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

Related Article

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.