Home Backend Development Python Tutorial python使用cookie库操保存cookie详解

python使用cookie库操保存cookie详解

Jun 06, 2016 am 11:29 AM

Cookie用于服务器实现会话,用户登录及相关功能时进行状态管理。要在用户浏览器上安装cookie,HTTP服务器向HTTP响应添加类似以下内容的HTTP报头:

代码如下:


Set-Cookie:session=8345234;expires=Sun,15-Nov-2013 15:00:00 GMT;path=/;domain=baidu.com

expires是cookie的生存周期,path是cookie的有效路径,domain是cookie的有效域.

路径"path"用于设置可以读取一个cookie的最顶层的目录.将cookie的路径设置为你的网页最顶层的目录可以让该该目录下的所有网页都能访问该cookie.

方法:在你的cookie中加入path=/; 如果你只想让"food" 目录中的网页可以使用该cookie,则你加入path=/food.

domain:有些网站有许多小的域名,例如百度可能还在"news.baidu.com" "zhidao.baidu.com" 和"v.baidu.com" 域名下有网页.如果想让"baidu.com"下的所有机器都可以读取该cookie,必须在cookie中加入 "domain=.baidu.com" .

用户浏览器会存储Cookie直到过期,浏览器会向符合path和domain的服务器发送类似以下内容的HTTP请求报头:

Cookie:session=8345234。

例如,登陆www.baidu.com的时候,百度服务器发送回的HTTP响应报头中cookie是:

代码如下:


Set-Cookie:H_PS_PSSID=4681_4567_1452_9876_4759; path=/; domain=.baidu.com
Set-Cookie:BDSVRTM=74; path=/  

浏览器的HTTP请求报头:

代码如下:


Cookie:BAIDUID=0FD996SDFG12********107B9C227F4C:FG=1; locale=zh; bdshare_firstime=1384567418140; NBID=D830DD2345HH2818A9F4134E5A2D778D3B:FG=1; H_PS_LC=4_shadu2014; BD_CK_SAM=1; H_PS_PSSID=4681_4567_1452_9876_4759

浏览器将cookie发送回HTTP服务器时,使用key=value字符串的编码形式,不返回expires,path和domain等可选属性。

cookie字符串通常位于HTTP_COOKIE环境变量中,可以如下读取:

代码如下:


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!"


Python中Cookie模块(python3中为http.cookies)提供了一个类似字典的特殊对象SimpleCookie,其中存储并管理着称为Morsel的cookie值集合。

每个Morsel都有name,value以及可选属性(expires,path,domain,comment,max-age,secure,version,httponly)。

SimpleCookie可使用output()方法创建以HTTP报头形式表示的cookie数据输出,用js_output()方法生成包含javascript代码的字符串。

用HTTP_COOKIE生成cookie:

代码如下:


cookie=Cookie.SimpleCookie(os.environ['HTTP_COOKIE'])
print cookie.output()

set cookie:

代码如下:


import Cookie
import datetime
import random

expiration = datetime.datetime.now() + datetime.timedelta(days=30)
cookie = Cookie.SimpleCookie()
cookie["session"] = random.randint(1,1000000000)
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()

输出:

代码如下:


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=/

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1267
29
C# Tutorial
1239
24
Python vs. C  : Applications and Use Cases Compared Python vs. C : Applications and Use Cases Compared Apr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

The 2-Hour Python Plan: A Realistic Approach The 2-Hour Python Plan: A Realistic Approach Apr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Games, GUIs, and More Python: Games, GUIs, and More Apr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python vs. C  : Learning Curves and Ease of Use Python vs. C : Learning Curves and Ease of Use Apr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

How Much Python Can You Learn in 2 Hours? How Much Python Can You Learn in 2 Hours? Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

Python and Time: Making the Most of Your Study Time Python and Time: Making the Most of Your Study Time Apr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

Python: Exploring Its Primary Applications Python: Exploring Its Primary Applications Apr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

See all articles